Skip to content

moplayground.envs

Multi-objective environments. Subclass MultiObjectiveBase to write your own; see Writing an environment.

moplayground.envs.create

Functions:

Name Description
create_environment

Instantiate a MO-Playground environment.

create_environment

create_environment(env_name, env_params, backend='jnp', gaitlib_path=None, **env_kwargs)

Instantiate a MO-Playground environment.

Constructs one of the registered multi-objective environments (MOCheetah, MOHopper, MOAnt, MOWalker, MOHumanoid, NaviGait).

Parameters:

Name Type Description Default
env_name

Registered environment name, e.g. 'MOCheetah'.

required
env_params

ConfigDict of environment parameters (the env_config section of a run config).

required
backend

'jnp' (JAX, for training) or 'np' (NumPy, for evaluation/rollout).

'jnp'
gaitlib_path

Gait library path. Required for NaviGait.

None
**env_kwargs

Extra keyword arguments forwarded to the environment constructor. Currently only consumed by NaviGait (Bruce).

{}

Returns:

Type Description

Tuple (env, env_params) where env is the constructed environment instance and env_params is the ConfigDict of environment parameters passed in.

Raises:

Type Description
Exception

If env_name does not match a registered environment.

Source code in src/moplayground/envs/create.py
def create_environment(env_name, env_params, backend='jnp', gaitlib_path=None, **env_kwargs):
    """Instantiate a MO-Playground environment.

    Constructs one of the registered multi-objective environments
    (``MOCheetah``, ``MOHopper``, ``MOAnt``, ``MOWalker``, ``MOHumanoid``,
    ``NaviGait``).

    Args:
        env_name: Registered environment name, e.g. ``'MOCheetah'``.
        env_params: ``ConfigDict`` of environment parameters (the
            ``env_config`` section of a run config).
        backend: ``'jnp'`` (JAX, for training) or ``'np'`` (NumPy, for
            evaluation/rollout).
        gaitlib_path: Gait library path. Required for ``NaviGait``.
        **env_kwargs: Extra keyword arguments forwarded to the environment
            constructor. Currently only consumed by ``NaviGait`` (Bruce).

    Returns:
        Tuple ``(env, env_params)`` where ``env`` is the constructed
        environment instance and ``env_params`` is the ``ConfigDict`` of
        environment parameters passed in.

    Raises:
        Exception: If ``env_name`` does not match a registered environment.
    """
    common_kwargs = {
        'backend': backend,
        'env_params': env_params
    }

    match env_name:
        case 'MOCheetah':
            from moplayground.envs.dmcontrol.cheetah import MOCheetah
            env = MOCheetah(**common_kwargs)
        case 'MOHopper':
            from moplayground.envs.dmcontrol.hopper import MOHopper
            env = MOHopper(**common_kwargs)
        case 'MOAnt':
            from moplayground.envs.dmcontrol.ant import MOAnt
            env = MOAnt(**common_kwargs)
        case 'MOWalker':
            from moplayground.envs.dmcontrol.walker import MOWalker
            env = MOWalker(**common_kwargs)
        case 'MOHumanoid':
            from moplayground.envs.dmcontrol.humanoid import MOHumanoid
            env = MOHumanoid(**common_kwargs)
        case 'NaviGait':
            from moplayground.envs.locomotion.bruce.navigait import Bruce
            env = Bruce(
                gaitlib_path    = gaitlib_path,
                gait_type       = 'P2',
                animate         = False,
                **common_kwargs,
                **env_kwargs
            )
        case _:
            raise Exception(f'Unknown enviornment {env_name}.')
    return env, env_params

moplayground.envs.generic.mobase

Classes:

Name Description
MultiObjectiveBase

Base environment that emits a vector-valued reward.

Multi2SingleObjective

Wrap a multi-objective env to expose a scalar reward.

MultiObjectiveBase

Bases: SwappableBase

Base environment that emits a vector-valued reward.

Extends minimal_mjx.envs.generic.base.SwappableBase so concrete environments can be constructed against either NumPy or JAX backends. Per-step reward components are bucketed into objective groups defined by env_params.reward.optimization.objectives (one entry per output dimension of the reward vector) and an optional set of shared_objectives that are added to every dimension.

Parameters:

Name Type Description Default
xml_path Path

Path to the MuJoCo XML model.

required
env_params ConfigDict

ConfigDict with at least reward.weights, reward.optimization.objectives (list of lists of reward keys, one list per objective dimension), and reward.optimization.shared_objectives (list of reward keys added to every objective).

required
backend str

'jnp' for JAX (training), 'np' for NumPy (eval).

'jnp'
num_free int

Number of free joints in the model. Forwarded to SwappableBase.

3

Methods:

Name Description
get_reward_and_metrics

Combine per-key rewards into a vector reward plus updated metrics.

Attributes:

Name Type Description
objectives
shared_objectives
Source code in src/moplayground/envs/generic/mobase.py
class MultiObjectiveBase(SwappableBase):
    """Base environment that emits a vector-valued reward.

    Extends ``minimal_mjx.envs.generic.base.SwappableBase`` so concrete
    environments can be constructed against either NumPy or JAX backends.
    Per-step reward components are bucketed into objective groups defined by
    ``env_params.reward.optimization.objectives`` (one entry per output
    dimension of the reward vector) and an optional set of
    ``shared_objectives`` that are added to every dimension.

    Args:
        xml_path: Path to the MuJoCo XML model.
        env_params: ConfigDict with at least ``reward.weights``,
            ``reward.optimization.objectives`` (list of lists of reward keys,
            one list per objective dimension), and
            ``reward.optimization.shared_objectives`` (list of reward keys
            added to every objective).
        backend: ``'jnp'`` for JAX (training), ``'np'`` for NumPy (eval).
        num_free: Number of free joints in the model. Forwarded to
            ``SwappableBase``.
    """

    def __init__(self,
        xml_path          : Path,
        env_params        : config_dict.ConfigDict,
        backend           : str = 'jnp',
        num_free          : int = 3
    ):
        self.objectives        = env_params.reward.optimization.objectives
        self.shared_objectives = env_params.reward.optimization.shared_objectives
        super().__init__(
            xml_path   = xml_path,
            env_params = env_params,
            backend    = backend,
            num_free   = num_free
        )

    def get_reward_and_metrics(
        self,
        rewards : jax.Array,
        metrics : dict
    ) -> tuple[jax.Array, dict[str, jax.Array]]:
        """Combine per-key rewards into a vector reward plus updated metrics.

        Each entry of ``self.objectives`` maps to one component of the
        returned reward vector, computed as a weighted sum of the listed
        per-key rewards. Shared objectives are then added to every
        component.

        Args:
            rewards: Mapping from reward key to scalar reward for the
                current step.
            metrics: Existing metrics dict to extend.

        Returns:
            ``(reward, metrics)`` where ``reward`` has shape
            ``(len(self.objectives),)`` and ``metrics`` is the updated
            metrics dict.
        """
        metrics = self.get_metrics(metrics, rewards)

        weights = self.params.reward.weights
        mo_reward = self._np.array([])
        for rew_objs in self.objectives:
            reward = 0
            for key in rew_objs:
                reward += weights[key] * rewards[key]
            mo_reward = self._np.hstack([mo_reward, reward])
        shared_reward = {k: rewards[k] * weights[k] for k in self.shared_objectives}
        reward = mo_reward + sum(shared_reward.values())

        return reward, metrics

objectives instance-attribute

objectives = env_params.reward.optimization.objectives

shared_objectives instance-attribute

shared_objectives = env_params.reward.optimization.shared_objectives

get_reward_and_metrics

get_reward_and_metrics(rewards: Array, metrics: dict) -> tuple[Array, dict[str, Array]]

Combine per-key rewards into a vector reward plus updated metrics.

Each entry of self.objectives maps to one component of the returned reward vector, computed as a weighted sum of the listed per-key rewards. Shared objectives are then added to every component.

Parameters:

Name Type Description Default
rewards Array

Mapping from reward key to scalar reward for the current step.

required
metrics dict

Existing metrics dict to extend.

required

Returns:

Type Description
tuple[Array, dict[str, Array]]

(reward, metrics) where reward has shape (len(self.objectives),) and metrics is the updated metrics dict.

Source code in src/moplayground/envs/generic/mobase.py
def get_reward_and_metrics(
    self,
    rewards : jax.Array,
    metrics : dict
) -> tuple[jax.Array, dict[str, jax.Array]]:
    """Combine per-key rewards into a vector reward plus updated metrics.

    Each entry of ``self.objectives`` maps to one component of the
    returned reward vector, computed as a weighted sum of the listed
    per-key rewards. Shared objectives are then added to every
    component.

    Args:
        rewards: Mapping from reward key to scalar reward for the
            current step.
        metrics: Existing metrics dict to extend.

    Returns:
        ``(reward, metrics)`` where ``reward`` has shape
        ``(len(self.objectives),)`` and ``metrics`` is the updated
        metrics dict.
    """
    metrics = self.get_metrics(metrics, rewards)

    weights = self.params.reward.weights
    mo_reward = self._np.array([])
    for rew_objs in self.objectives:
        reward = 0
        for key in rew_objs:
            reward += weights[key] * rewards[key]
        mo_reward = self._np.hstack([mo_reward, reward])
    shared_reward = {k: rewards[k] * weights[k] for k in self.shared_objectives}
    reward = mo_reward + sum(shared_reward.values())

    return reward, metrics

Multi2SingleObjective

Wrap a multi-objective env to expose a scalar reward.

Replaces the vector reward from the wrapped environment with the inner product reward · weighting, so the wrapped env can be plugged into standard single-objective PPO. All other attributes/methods are delegated to the underlying env via __getattr__.

Parameters:

Name Type Description Default
env

A MultiObjectiveBase (or compatible) environment whose reset/step return states with vector rewards.

required
weighting

Per-objective weights, length must match the env's reward dimension.

required

Methods:

Name Description
reset
step

Attributes:

Name Type Description
env
weighting
Source code in src/moplayground/envs/generic/mobase.py
class Multi2SingleObjective:
    """Wrap a multi-objective env to expose a scalar reward.

    Replaces the vector reward from the wrapped environment with the inner
    product ``reward · weighting``, so the wrapped env can be plugged into
    standard single-objective PPO. All other attributes/methods are
    delegated to the underlying ``env`` via ``__getattr__``.

    Args:
        env: A ``MultiObjectiveBase`` (or compatible) environment whose
            ``reset``/``step`` return states with vector rewards.
        weighting: Per-objective weights, length must match the env's
            reward dimension.
    """

    def __init__(self, env, weighting):
        self.env = env
        self.weighting = weighting

    def reset(self, rng):
        state = self.env.reset(rng)
        return state.replace(reward=self.env._np.sum(state.reward * self.env._np.array(self.weighting)))

    def step(self, state, action):
        state = self.env.step(state, action)
        return state.replace(reward=self._np.sum(state.reward * self.env._np.array(self.weighting)))

    def __getattr__(self, name):
        """
        Called only if `name` is not found on self.
        Delegate lookup to the base object.
        """
        return getattr(self.env, name)

env instance-attribute

env = env

weighting instance-attribute

weighting = weighting

reset

reset(rng)
Source code in src/moplayground/envs/generic/mobase.py
def reset(self, rng):
    state = self.env.reset(rng)
    return state.replace(reward=self.env._np.sum(state.reward * self.env._np.array(self.weighting)))

step

step(state, action)
Source code in src/moplayground/envs/generic/mobase.py
def step(self, state, action):
    state = self.env.step(state, action)
    return state.replace(reward=self._np.sum(state.reward * self.env._np.array(self.weighting)))

DeepMind Control tasks

moplayground.envs.dmcontrol.cheetah

Classes:

Name Description
MOCheetah

Multi-Objective Cheetah Environment.

MOCheetah

Bases: MultiObjectiveBase

Multi-Objective Cheetah Environment. Objectives are speed, energy, and jumping height.

Methods:

Name Description
reset
state_vector
step
fall_termination
reward_function
reward_height
reward_alive
reward_energy
reward_run
reward_done

Attributes:

Name Type Description
action_size
Source code in src/moplayground/envs/dmcontrol/cheetah.py
class MOCheetah(MultiObjectiveBase):
    """Multi-Objective Cheetah Environment. 
    Objectives are speed, energy, and jumping height."""

    def __init__(
        self,
        env_params        : config_dict.ConfigDict,
        backend           : str,
        xml_path          : str = CheetahInterface.XML,
    ):
        super().__init__(
            xml_path          = xml_path,
            env_params        = env_params,
            backend           = backend,
        )

    def reset(self, rng: jax.Array) -> mjx_env.State:
        rng, qpos_key, qvel_key = self._split(rng, 3)
        qpos = self._np.hstack([
            self._np.array(CheetahInterface.DEFAULT_FF),
            self._np.array(CheetahInterface.DEFAULT_JT)
        ])
        qvel = self._np.zeros(self.mj_model.nv)
        ctrl = self._np.zeros(self.mj_model.nu)

        data = self._data_init_fn(
            qpos         = qpos,
            qvel         = qvel,
            ctrl         = ctrl,
            time         = 0.0,
            xfrc_applied = self._np.zeros((self._mj_model.nbody, 6)),
        )
        info = {}
        info['xposbefore'] = 0.0
        info['xposafter']  = 0.01
        info['ang']        = 0.0

        done = self._np.array(0.0)
        rewards = self.reward_function(
            data   = data,
            action = ctrl,
            info   = info,
            done   = False,
        )
        reward, metrics = self.get_reward_and_metrics(rewards, {})

        obs = self._get_obs(data, info)
        return self._state_init_fn(data, obs, reward, done, metrics, info)

    def state_vector(self, data):
        return self._np.hstack([data.qpos, data.qvel])

    def step(self, state: mjx_env.State, action: jax.Array) -> mjx_env.State:
        state.info['xposbefore'] = state.data.qpos[0]
        action = self._np.clip(
            self.params.action_scale * action, 
            -1.0,
            1.0
        )
        data = self._step_fn(state.data, action)
        state.info['xposafter'] = data.qpos[0]
        state.info['ang']       = data.qpos[2]

        done = self.fall_termination(state.info)
        rewards = self.reward_function(
            data   = data,
            action = action,
            info   = state.info,
            done   = done
        )
        reward, metrics = self.get_reward_and_metrics(rewards, state.metrics)
        obs = self._get_obs(
            data,
            state.info
        )
        done = done.astype(float)
        return self._state_init_fn(data, obs, reward, done, metrics, state.info)

    def fall_termination(
        self,  
        info: dict
    ):
        return self._np.array(
            ~(abs(info['ang']) < self._np.deg2rad(50))
        )

    def _get_obs(self, data: mjx.Data, info: dict[str, Any]) -> jax.Array:
        obs = self._np.concatenate([
            data.qpos[1:],
            self._np.clip(data.qvel, -10.0, 10.0),
        ])
        return {
            'state': obs,
            'privileged_state': obs
        }

    @property
    def action_size(self):
        return 6

    def reward_function(
        self,
        data,
        action,
        info,
        done
    ):
        rewards = {
            'alive'  : self.reward_alive(),
            'energy' : self.reward_energy(action),
            'height' : self.reward_height(data),
            'run'    : self.reward_run(info),
            'done'   : self.reward_done(done)
        }
        return rewards

    def reward_height(self, data: mjx.Data):
        return data.qpos[1] - CheetahInterface.DEFAULT_FF[1] + 0.2

    def reward_alive(self):
        return 1.0

    def reward_energy(self, action):
        return 4.0 - 1.0 * self._np.square(action).sum()

    def reward_run(self, info):
        reward_run = (info['xposafter'] - info['xposbefore']) / self.dt
        return self._np.min(self._np.array([4.0, reward_run]))

    def reward_done(self, done):
        return self._np.array(done)

action_size property

action_size

reset

reset(rng: Array) -> State
Source code in src/moplayground/envs/dmcontrol/cheetah.py
def reset(self, rng: jax.Array) -> mjx_env.State:
    rng, qpos_key, qvel_key = self._split(rng, 3)
    qpos = self._np.hstack([
        self._np.array(CheetahInterface.DEFAULT_FF),
        self._np.array(CheetahInterface.DEFAULT_JT)
    ])
    qvel = self._np.zeros(self.mj_model.nv)
    ctrl = self._np.zeros(self.mj_model.nu)

    data = self._data_init_fn(
        qpos         = qpos,
        qvel         = qvel,
        ctrl         = ctrl,
        time         = 0.0,
        xfrc_applied = self._np.zeros((self._mj_model.nbody, 6)),
    )
    info = {}
    info['xposbefore'] = 0.0
    info['xposafter']  = 0.01
    info['ang']        = 0.0

    done = self._np.array(0.0)
    rewards = self.reward_function(
        data   = data,
        action = ctrl,
        info   = info,
        done   = False,
    )
    reward, metrics = self.get_reward_and_metrics(rewards, {})

    obs = self._get_obs(data, info)
    return self._state_init_fn(data, obs, reward, done, metrics, info)

state_vector

state_vector(data)
Source code in src/moplayground/envs/dmcontrol/cheetah.py
def state_vector(self, data):
    return self._np.hstack([data.qpos, data.qvel])

step

step(state: State, action: Array) -> State
Source code in src/moplayground/envs/dmcontrol/cheetah.py
def step(self, state: mjx_env.State, action: jax.Array) -> mjx_env.State:
    state.info['xposbefore'] = state.data.qpos[0]
    action = self._np.clip(
        self.params.action_scale * action, 
        -1.0,
        1.0
    )
    data = self._step_fn(state.data, action)
    state.info['xposafter'] = data.qpos[0]
    state.info['ang']       = data.qpos[2]

    done = self.fall_termination(state.info)
    rewards = self.reward_function(
        data   = data,
        action = action,
        info   = state.info,
        done   = done
    )
    reward, metrics = self.get_reward_and_metrics(rewards, state.metrics)
    obs = self._get_obs(
        data,
        state.info
    )
    done = done.astype(float)
    return self._state_init_fn(data, obs, reward, done, metrics, state.info)

fall_termination

fall_termination(info: dict)
Source code in src/moplayground/envs/dmcontrol/cheetah.py
def fall_termination(
    self,  
    info: dict
):
    return self._np.array(
        ~(abs(info['ang']) < self._np.deg2rad(50))
    )

reward_function

reward_function(data, action, info, done)
Source code in src/moplayground/envs/dmcontrol/cheetah.py
def reward_function(
    self,
    data,
    action,
    info,
    done
):
    rewards = {
        'alive'  : self.reward_alive(),
        'energy' : self.reward_energy(action),
        'height' : self.reward_height(data),
        'run'    : self.reward_run(info),
        'done'   : self.reward_done(done)
    }
    return rewards

reward_height

reward_height(data: Data)
Source code in src/moplayground/envs/dmcontrol/cheetah.py
def reward_height(self, data: mjx.Data):
    return data.qpos[1] - CheetahInterface.DEFAULT_FF[1] + 0.2

reward_alive

reward_alive()
Source code in src/moplayground/envs/dmcontrol/cheetah.py
def reward_alive(self):
    return 1.0

reward_energy

reward_energy(action)
Source code in src/moplayground/envs/dmcontrol/cheetah.py
def reward_energy(self, action):
    return 4.0 - 1.0 * self._np.square(action).sum()

reward_run

reward_run(info)
Source code in src/moplayground/envs/dmcontrol/cheetah.py
def reward_run(self, info):
    reward_run = (info['xposafter'] - info['xposbefore']) / self.dt
    return self._np.min(self._np.array([4.0, reward_run]))

reward_done

reward_done(done)
Source code in src/moplayground/envs/dmcontrol/cheetah.py
def reward_done(self, done):
    return self._np.array(done)

moplayground.envs.dmcontrol.hopper

Classes:

Name Description
MOHopper

Multi-Objective Hopper Environment. Objectives are speed by height.

MOHopper

Bases: MultiObjectiveBase

Multi-Objective Hopper Environment. Objectives are speed by height.

Methods:

Name Description
reset
step
fall_termination
reward_function
reward_upright
reward_alive
reward_ctrl_cost
reward_run
reward_jump
reward_done
reward_energy

Attributes:

Name Type Description
action_size
Source code in src/moplayground/envs/dmcontrol/hopper.py
class MOHopper(MultiObjectiveBase):
    """Multi-Objective Hopper Environment. Objectives are speed by height."""
    def __init__(
        self,
        env_params        : config_dict.ConfigDict,
        backend           : str,
    ):
        super().__init__(
            xml_path          = HopperInterface.XML,
            env_params        = env_params,
            backend           = backend,
            num_free          = 3
        )

    def reset(self, rng: jax.Array) -> mjx_env.State:
        qpos = self._np.hstack([
            HopperInterface.DEFAULT_FF,
            HopperInterface.DEFAULT_JT
        ])
        qvel = self._np.zeros(self.mj_model.nv)
        ctrl = qpos[self.qpos_free:].copy()

        data = self._data_init_fn(
            qpos         = qpos,
            qvel         = qvel,
            ctrl         = ctrl,
            time         = 0.0,
            xfrc_applied = self._np.zeros((self._mj_model.nbody, 6)),
        )
        info = {}
        info['posbefore'] = 0.0
        info['posafter']  = 0.01
        info['height']    = 0.0
        info['ang']       = 0.0

        done = self._np.array(0.0).astype(self._np.float32)
        rewards = self.reward_function(
            data   = data,
            action = ctrl,
            info   = info,
            done   = False,
        )
        reward, metrics = self.get_reward_and_metrics(rewards, {})

        obs = self._get_obs(data, info)
        return self._state_init_fn(data, obs, reward, done, metrics, info)

    def step(self, state: mjx_env.State, action: jax.Array) -> mjx_env.State:
        action = self._np.array(self.params.action_scale) * action
        state.info['posbefore'] = state.data.qpos[0]
        data = self._step_fn(state.data, action)
        state.info['posafter'], state.info['height'], state.info['ang'] = data.qpos[0:3]

        done = self.fall_termination(data)
        rewards = self.reward_function(
            data   = data,
            action = action,
            info   = state.info,
            done   = done
        )
        reward, metrics = self.get_reward_and_metrics(rewards, state.metrics)
        done = done.astype(float)
        obs = self._get_obs(
            data,
            state.info
        )
        return self._state_init_fn(data, obs, reward, done, metrics, state.info)

    def fall_termination(
        self,  
        data: mjx.Data
    ):
        height = data.qpos[1] < 0.2
        base_angle  = self._np.abs(data.qpos[2]) > self._np.deg2rad(270)
        return height | base_angle

    def _get_obs(self, data: mjx.Data, info: dict) -> jax.Array:
        obs = self._np.concatenate([
            data.qpos[1:],
            self._np.clip(data.qvel, -10.0, 10.0),
        ])
        return {
            'state': obs,
            'privileged_state': obs
        }

    @property
    def action_size(self):
        return 4

    def reward_function(
        self,
        data,
        action,
        info,
        done
    ):
        rewards = {
            'alive'     : self.reward_alive(),
            'ctrl_cost' : self.reward_ctrl_cost(action),
            'run'       : self.reward_run(info),
            'jump'      : self.reward_jump(info),
            'upright'   : self.reward_upright(info),
            'done'      : self.reward_done(done)
        }
        return rewards

    def reward_upright(self, info):
        return self._np.clip(
            info['height'] - 0.4,
            0.2 - 0.4,
            0.0,
        )

    def reward_alive(self):
        return 1.0

    def reward_ctrl_cost(self, action):
        return self._np.square(action).sum()

    def reward_run(self, info):
        return (info['posafter'] - info['posbefore']) / self.dt

    def reward_jump(self, info):
        return self._np.clip(
            info['height'] - HopperInterface.DEFAULT_FF[1] + 0.2,
            0.0,
            self._np.inf,
        )

    def reward_done(self, done):
        return self._np.array(done)

    def reward_energy(self, action):
        return 4.0 - 1.0 * self._np.square(action).sum()

action_size property

action_size

reset

reset(rng: Array) -> State
Source code in src/moplayground/envs/dmcontrol/hopper.py
def reset(self, rng: jax.Array) -> mjx_env.State:
    qpos = self._np.hstack([
        HopperInterface.DEFAULT_FF,
        HopperInterface.DEFAULT_JT
    ])
    qvel = self._np.zeros(self.mj_model.nv)
    ctrl = qpos[self.qpos_free:].copy()

    data = self._data_init_fn(
        qpos         = qpos,
        qvel         = qvel,
        ctrl         = ctrl,
        time         = 0.0,
        xfrc_applied = self._np.zeros((self._mj_model.nbody, 6)),
    )
    info = {}
    info['posbefore'] = 0.0
    info['posafter']  = 0.01
    info['height']    = 0.0
    info['ang']       = 0.0

    done = self._np.array(0.0).astype(self._np.float32)
    rewards = self.reward_function(
        data   = data,
        action = ctrl,
        info   = info,
        done   = False,
    )
    reward, metrics = self.get_reward_and_metrics(rewards, {})

    obs = self._get_obs(data, info)
    return self._state_init_fn(data, obs, reward, done, metrics, info)

step

step(state: State, action: Array) -> State
Source code in src/moplayground/envs/dmcontrol/hopper.py
def step(self, state: mjx_env.State, action: jax.Array) -> mjx_env.State:
    action = self._np.array(self.params.action_scale) * action
    state.info['posbefore'] = state.data.qpos[0]
    data = self._step_fn(state.data, action)
    state.info['posafter'], state.info['height'], state.info['ang'] = data.qpos[0:3]

    done = self.fall_termination(data)
    rewards = self.reward_function(
        data   = data,
        action = action,
        info   = state.info,
        done   = done
    )
    reward, metrics = self.get_reward_and_metrics(rewards, state.metrics)
    done = done.astype(float)
    obs = self._get_obs(
        data,
        state.info
    )
    return self._state_init_fn(data, obs, reward, done, metrics, state.info)

fall_termination

fall_termination(data: Data)
Source code in src/moplayground/envs/dmcontrol/hopper.py
def fall_termination(
    self,  
    data: mjx.Data
):
    height = data.qpos[1] < 0.2
    base_angle  = self._np.abs(data.qpos[2]) > self._np.deg2rad(270)
    return height | base_angle

reward_function

reward_function(data, action, info, done)
Source code in src/moplayground/envs/dmcontrol/hopper.py
def reward_function(
    self,
    data,
    action,
    info,
    done
):
    rewards = {
        'alive'     : self.reward_alive(),
        'ctrl_cost' : self.reward_ctrl_cost(action),
        'run'       : self.reward_run(info),
        'jump'      : self.reward_jump(info),
        'upright'   : self.reward_upright(info),
        'done'      : self.reward_done(done)
    }
    return rewards

reward_upright

reward_upright(info)
Source code in src/moplayground/envs/dmcontrol/hopper.py
def reward_upright(self, info):
    return self._np.clip(
        info['height'] - 0.4,
        0.2 - 0.4,
        0.0,
    )

reward_alive

reward_alive()
Source code in src/moplayground/envs/dmcontrol/hopper.py
def reward_alive(self):
    return 1.0

reward_ctrl_cost

reward_ctrl_cost(action)
Source code in src/moplayground/envs/dmcontrol/hopper.py
def reward_ctrl_cost(self, action):
    return self._np.square(action).sum()

reward_run

reward_run(info)
Source code in src/moplayground/envs/dmcontrol/hopper.py
def reward_run(self, info):
    return (info['posafter'] - info['posbefore']) / self.dt

reward_jump

reward_jump(info)
Source code in src/moplayground/envs/dmcontrol/hopper.py
def reward_jump(self, info):
    return self._np.clip(
        info['height'] - HopperInterface.DEFAULT_FF[1] + 0.2,
        0.0,
        self._np.inf,
    )

reward_done

reward_done(done)
Source code in src/moplayground/envs/dmcontrol/hopper.py
def reward_done(self, done):
    return self._np.array(done)

reward_energy

reward_energy(action)
Source code in src/moplayground/envs/dmcontrol/hopper.py
def reward_energy(self, action):
    return 4.0 - 1.0 * self._np.square(action).sum()

moplayground.envs.dmcontrol.walker

Hopper environment.

Classes:

Name Description
MOWalker

Multi-Objective Ant Environment. Objectives are speed by energy.

MOWalker

Bases: MultiObjectiveBase

Multi-Objective Ant Environment. Objectives are speed by energy.

Methods:

Name Description
reset
state_vector
step
termination
reward_function
reward_alive
reward_energy
reward_run
reward_done

Attributes:

Name Type Description
action_size
Source code in src/moplayground/envs/dmcontrol/walker.py
class MOWalker(MultiObjectiveBase):
    """Multi-Objective Ant Environment. Objectives are speed by energy."""

    def __init__(
        self,
        env_params        : config_dict.ConfigDict,
        backend           : str,
        xml_path          : str = WalkerInterface.XML,
    ):
        super().__init__(
            xml_path          = xml_path,
            env_params        = env_params,
            backend           = backend,
            num_free          = 3
        )

    def reset(self, rng: jax.Array) -> mjx_env.State:
        qpos = self._np.hstack([
            WalkerInterface.DEFAULT_FF,
            WalkerInterface.DEFAULT_JT
        ])
        qvel = self._np.zeros(self.mj_model.nv)
        ctrl = qpos[self.qpos_free:].copy()

        data = self._data_init_fn(
            qpos         = qpos,
            qvel         = qvel,
            ctrl         = ctrl,
            time         = 0.0,
            xfrc_applied = self._np.zeros((self._mj_model.nbody, 6)),
        )
        info = {}
        info['posbefore'] = data.qpos[0]
        info['posafter']  = data.qpos[0] + 0.01

        done = self._np.array(0.0)
        rewards = self.reward_function(
            data   = data,
            action = ctrl,
            info   = info,
            done   = False,
        )
        reward, metrics = self.get_reward_and_metrics(rewards, {})

        obs = self._get_obs(data, info)
        return self._state_init_fn(data, obs, reward, done, metrics, info)

    def state_vector(self, data):
        return self._np.hstack([data.qpos, data.qvel])

    def step(self, state: mjx_env.State, action: jax.Array) -> mjx_env.State:
        state.info['posbefore'] = state.data.qpos[0]
        action = self._np.clip(
            self.params.action_scale * action, 
            -1.0,
             1.0
        )
        data = self._step_fn(state.data, action)
        state.info['posafter'] = data.qpos[0]

        done = self.termination(data)
        rewards = self.reward_function(
            data   = data,
            action = action,
            info   = state.info,
            done   = done
        )
        reward, metrics = self.get_reward_and_metrics(rewards, state.metrics)
        obs = self._get_obs(
            data,
            state.info
        )
        done = done.astype(float)
        return self._state_init_fn(data, obs, reward, done, metrics, state.info)

    def termination(
        self,
        data: mjx.Data,
    ):
        height, ang = data.qpos[1:3]
        good_height = (height > 0.8) & (height < 2.0)
        good_ang    = (ang > -1.0) & (ang < 1.0)
        return ~(good_height & good_ang)

    def _get_obs(self, data: mjx.Data, info: dict[str, Any]) -> jax.Array:
        obs = self._np.concatenate([
            data.qpos[1:],
            self._np.clip(
                data.qvel,
                -10.0,
                10.0
            ),
        ])
        return {
            'state': obs,
            'privileged_state': obs
        }

    @property
    def action_size(self):
        return 6

    def reward_function(
        self,
        data,
        action,
        info,
        done
    ):
        rewards = {
            'alive'  : self.reward_alive(),
            'energy' : self.reward_energy(action),
            'run'    : self.reward_run(info),
            'done'   : self.reward_done(done)
        }
        return rewards

    def reward_alive(self):
        return 1.0

    def reward_energy(self, action):
        return 4.0 - 1.0 * self._np.square(action).sum()

    def reward_run(self, info):
        vx = (info['posafter'] - info['posbefore']) / self.dt
        return vx

    def reward_done(self, done):
        return self._np.array(done)

action_size property

action_size

reset

reset(rng: Array) -> State
Source code in src/moplayground/envs/dmcontrol/walker.py
def reset(self, rng: jax.Array) -> mjx_env.State:
    qpos = self._np.hstack([
        WalkerInterface.DEFAULT_FF,
        WalkerInterface.DEFAULT_JT
    ])
    qvel = self._np.zeros(self.mj_model.nv)
    ctrl = qpos[self.qpos_free:].copy()

    data = self._data_init_fn(
        qpos         = qpos,
        qvel         = qvel,
        ctrl         = ctrl,
        time         = 0.0,
        xfrc_applied = self._np.zeros((self._mj_model.nbody, 6)),
    )
    info = {}
    info['posbefore'] = data.qpos[0]
    info['posafter']  = data.qpos[0] + 0.01

    done = self._np.array(0.0)
    rewards = self.reward_function(
        data   = data,
        action = ctrl,
        info   = info,
        done   = False,
    )
    reward, metrics = self.get_reward_and_metrics(rewards, {})

    obs = self._get_obs(data, info)
    return self._state_init_fn(data, obs, reward, done, metrics, info)

state_vector

state_vector(data)
Source code in src/moplayground/envs/dmcontrol/walker.py
def state_vector(self, data):
    return self._np.hstack([data.qpos, data.qvel])

step

step(state: State, action: Array) -> State
Source code in src/moplayground/envs/dmcontrol/walker.py
def step(self, state: mjx_env.State, action: jax.Array) -> mjx_env.State:
    state.info['posbefore'] = state.data.qpos[0]
    action = self._np.clip(
        self.params.action_scale * action, 
        -1.0,
         1.0
    )
    data = self._step_fn(state.data, action)
    state.info['posafter'] = data.qpos[0]

    done = self.termination(data)
    rewards = self.reward_function(
        data   = data,
        action = action,
        info   = state.info,
        done   = done
    )
    reward, metrics = self.get_reward_and_metrics(rewards, state.metrics)
    obs = self._get_obs(
        data,
        state.info
    )
    done = done.astype(float)
    return self._state_init_fn(data, obs, reward, done, metrics, state.info)

termination

termination(data: Data)
Source code in src/moplayground/envs/dmcontrol/walker.py
def termination(
    self,
    data: mjx.Data,
):
    height, ang = data.qpos[1:3]
    good_height = (height > 0.8) & (height < 2.0)
    good_ang    = (ang > -1.0) & (ang < 1.0)
    return ~(good_height & good_ang)

reward_function

reward_function(data, action, info, done)
Source code in src/moplayground/envs/dmcontrol/walker.py
def reward_function(
    self,
    data,
    action,
    info,
    done
):
    rewards = {
        'alive'  : self.reward_alive(),
        'energy' : self.reward_energy(action),
        'run'    : self.reward_run(info),
        'done'   : self.reward_done(done)
    }
    return rewards

reward_alive

reward_alive()
Source code in src/moplayground/envs/dmcontrol/walker.py
def reward_alive(self):
    return 1.0

reward_energy

reward_energy(action)
Source code in src/moplayground/envs/dmcontrol/walker.py
def reward_energy(self, action):
    return 4.0 - 1.0 * self._np.square(action).sum()

reward_run

reward_run(info)
Source code in src/moplayground/envs/dmcontrol/walker.py
def reward_run(self, info):
    vx = (info['posafter'] - info['posbefore']) / self.dt
    return vx

reward_done

reward_done(done)
Source code in src/moplayground/envs/dmcontrol/walker.py
def reward_done(self, done):
    return self._np.array(done)

moplayground.envs.dmcontrol.ant

Classes:

Name Description
MOAnt

Multi-Objective Ant Environment. Objectives are vx by vy.

MOAnt

Bases: MultiObjectiveBase

Multi-Objective Ant Environment. Objectives are vx by vy.

Methods:

Name Description
reset
state_vector
step
fall_termination
reward_function
reward_alive
reward_energy
reward_vx
reward_vy

Attributes:

Name Type Description
action_size
Source code in src/moplayground/envs/dmcontrol/ant.py
class MOAnt(MultiObjectiveBase):
    """Multi-Objective Ant Environment. Objectives are vx by vy."""


    def __init__(
        self,
        env_params        : config_dict.ConfigDict,
        backend           : str,
    ):
        super().__init__(
            xml_path          = AntInterface.XML,
            env_params        = env_params,
            backend           = backend,
        )

    def reset(self, rng: jax.Array) -> mjx_env.State:
        rng, qpos_key, qvel_key = self._split(rng, 3)
        qpos = self._np.hstack([
            AntInterface.DEFAULT_FF,
            AntInterface.DEFAULT_JT
        ])
        qvel = self._np.zeros(self.mj_model.nv)
        ctrl = self._np.zeros(self.mj_model.nu)

        data = self._data_init_fn(
            qpos         = qpos,
            qvel         = qvel,
            ctrl         = ctrl,
            time         = 0.0,
            xfrc_applied = self._np.zeros((self._mj_model.nbody, 6)),
        )
        info = {}
        info['xposbefore'] = data.qpos[0]
        info['yposbefore'] = data.qpos[1]
        info['xposafter']  = data.qpos[0] + 0.01
        info['yposafter']  = data.qpos[1] + 0.01

        done = self._np.array(0.0)
        rewards = self.reward_function(
            data   = data,
            action = ctrl,
            info   = info,
            done   = False,
        )
        reward, metrics = self.get_reward_and_metrics(rewards, {})

        obs = self._get_obs(data, info)
        return self._state_init_fn(data, obs, reward, done, metrics, info)

    def state_vector(self, data):
        return self._np.hstack([data.qpos, data.qvel])

    def step(self, state: mjx_env.State, action: jax.Array) -> mjx_env.State:
        state.info['xposbefore'] = state.data.qpos[0]
        state.info['yposbefore'] = state.data.qpos[1]
        action = self._np.clip(
            self.params.action_scale * action, 
            -1.0,
            1.0
        )
        data = self._step_fn(state.data, action)
        state.info['xposafter'] = data.qpos[0]
        state.info['yposafter'] = data.qpos[1]

        done = self.fall_termination(data)
        rewards = self.reward_function(
            data   = data,
            action = action,
            info   = state.info,
            done   = done
        )
        reward, metrics = self.get_reward_and_metrics(rewards, state.metrics)
        obs = self._get_obs(
            data,
            state.info
        )
        done = done.astype(float)
        return self._state_init_fn(data, obs, reward, done, metrics, state.info)

    def fall_termination(
        self,
        data
    ):
        infinite_state = ~self._np.isfinite(data.qpos).all()
        flipped_over = data.sensordata[2] < 0.45
        return infinite_state | flipped_over

    def _get_obs(self, data: mjx.Data, info: dict[str, Any]) -> jax.Array:
        obs = self._np.concatenate([
            data.qpos[2:],
            data.qvel,
        ])
        return {
            'state': obs,
            'privileged_state': obs
        }

    @property
    def action_size(self):
        return self.mj_model.nu

    def reward_function(
        self,
        data,
        action,
        info,
        done
    ):
        rewards = {
            'alive'  : self.reward_alive(),
            'energy' : self.reward_energy(action),
            'vx'     : self.reward_vx(info),
            'vy'     : self.reward_vy(info)
        }
        return rewards

    def reward_alive(self):
        return 1.0

    def reward_energy(self, action):
        return 8.0 - 1.0 * self._np.square(action).sum()

    def reward_vx(self, info):
        vx = (info['xposafter'] - info['xposbefore']) / self.dt
        return vx

    def reward_vy(self, info):
        vy = (info['yposafter'] - info['yposbefore']) / self.dt
        return vy

action_size property

action_size

reset

reset(rng: Array) -> State
Source code in src/moplayground/envs/dmcontrol/ant.py
def reset(self, rng: jax.Array) -> mjx_env.State:
    rng, qpos_key, qvel_key = self._split(rng, 3)
    qpos = self._np.hstack([
        AntInterface.DEFAULT_FF,
        AntInterface.DEFAULT_JT
    ])
    qvel = self._np.zeros(self.mj_model.nv)
    ctrl = self._np.zeros(self.mj_model.nu)

    data = self._data_init_fn(
        qpos         = qpos,
        qvel         = qvel,
        ctrl         = ctrl,
        time         = 0.0,
        xfrc_applied = self._np.zeros((self._mj_model.nbody, 6)),
    )
    info = {}
    info['xposbefore'] = data.qpos[0]
    info['yposbefore'] = data.qpos[1]
    info['xposafter']  = data.qpos[0] + 0.01
    info['yposafter']  = data.qpos[1] + 0.01

    done = self._np.array(0.0)
    rewards = self.reward_function(
        data   = data,
        action = ctrl,
        info   = info,
        done   = False,
    )
    reward, metrics = self.get_reward_and_metrics(rewards, {})

    obs = self._get_obs(data, info)
    return self._state_init_fn(data, obs, reward, done, metrics, info)

state_vector

state_vector(data)
Source code in src/moplayground/envs/dmcontrol/ant.py
def state_vector(self, data):
    return self._np.hstack([data.qpos, data.qvel])

step

step(state: State, action: Array) -> State
Source code in src/moplayground/envs/dmcontrol/ant.py
def step(self, state: mjx_env.State, action: jax.Array) -> mjx_env.State:
    state.info['xposbefore'] = state.data.qpos[0]
    state.info['yposbefore'] = state.data.qpos[1]
    action = self._np.clip(
        self.params.action_scale * action, 
        -1.0,
        1.0
    )
    data = self._step_fn(state.data, action)
    state.info['xposafter'] = data.qpos[0]
    state.info['yposafter'] = data.qpos[1]

    done = self.fall_termination(data)
    rewards = self.reward_function(
        data   = data,
        action = action,
        info   = state.info,
        done   = done
    )
    reward, metrics = self.get_reward_and_metrics(rewards, state.metrics)
    obs = self._get_obs(
        data,
        state.info
    )
    done = done.astype(float)
    return self._state_init_fn(data, obs, reward, done, metrics, state.info)

fall_termination

fall_termination(data)
Source code in src/moplayground/envs/dmcontrol/ant.py
def fall_termination(
    self,
    data
):
    infinite_state = ~self._np.isfinite(data.qpos).all()
    flipped_over = data.sensordata[2] < 0.45
    return infinite_state | flipped_over

reward_function

reward_function(data, action, info, done)
Source code in src/moplayground/envs/dmcontrol/ant.py
def reward_function(
    self,
    data,
    action,
    info,
    done
):
    rewards = {
        'alive'  : self.reward_alive(),
        'energy' : self.reward_energy(action),
        'vx'     : self.reward_vx(info),
        'vy'     : self.reward_vy(info)
    }
    return rewards

reward_alive

reward_alive()
Source code in src/moplayground/envs/dmcontrol/ant.py
def reward_alive(self):
    return 1.0

reward_energy

reward_energy(action)
Source code in src/moplayground/envs/dmcontrol/ant.py
def reward_energy(self, action):
    return 8.0 - 1.0 * self._np.square(action).sum()

reward_vx

reward_vx(info)
Source code in src/moplayground/envs/dmcontrol/ant.py
def reward_vx(self, info):
    vx = (info['xposafter'] - info['xposbefore']) / self.dt
    return vx

reward_vy

reward_vy(info)
Source code in src/moplayground/envs/dmcontrol/ant.py
def reward_vy(self, info):
    vy = (info['yposafter'] - info['yposbefore']) / self.dt
    return vy

moplayground.envs.dmcontrol.humanoid

Classes:

Name Description
MOHumanoid

Multi-Objective Humanoid Environment. Objectives are speed by energy.

MOHumanoid

Bases: MultiObjectiveBase

Multi-Objective Humanoid Environment. Objectives are speed by energy.

Methods:

Name Description
reset
mass_center
step
fall_termination
reward_function
reward_alive
reward_run
reward_done
reward_energy
joint_angles

Returns the state without global orientation or position.

torso_vertical_orientation

Returns the z-projection of the torso orientation matrix.

com_position

Returns the position of the center of mass in global coordinates.

head_height

Returns the height of the torso.

torso_upright

Returns projection from z-axes of torso to the z-axes of world.

extremities

Returns end effector positions in the egocentric frame.

Attributes:

Name Type Description
qfrc_max
action_size
Source code in src/moplayground/envs/dmcontrol/humanoid.py
class MOHumanoid(MultiObjectiveBase):
    """Multi-Objective Humanoid Environment. Objectives are speed by energy."""

    def __init__(
        self,
        env_params: config_dict.ConfigDict,
        backend:    str,
    ):
        super().__init__(
            xml_path          = HumanoidInterface.XML,
            env_params        = env_params,
            backend           = backend,
            num_free          = 7
        )
        self.qfrc_max = self.params.action_scale * self._np.sum(self.mj_model.actuator_gear[:, 0]) 

    def reset(self, rng: jax.Array) -> mjx_env.State:
        qpos = self._np.hstack([
            HumanoidInterface.DEFAULT_FF,
            HumanoidInterface.DEFAULT_JT
        ])
        qvel = self._np.zeros(self.mj_model.nv)
        ctrl = qpos[self.qpos_free:].copy()

        data = self._data_init_fn(
            qpos         = qpos,
            qvel         = qvel,
            ctrl         = ctrl,
            time         = 0.0,
            xfrc_applied = self._np.zeros((self._mj_model.nbody, 6)),
        )

        info = {}
        info['posbefore'] = 0.0
        info['posafter']  = 0.01

        done = self._np.array(0.0)
        rewards = self.reward_function(
            data   = data,
            action = ctrl,
            info   = info,
            done   = False,
        )
        reward, metrics = self.get_reward_and_metrics(rewards, {})

        obs = self._get_obs(data, info)
        return self._state_init_fn(data, obs, reward, done, metrics, info)

    def mass_center(self, data):
        mass = self._np.expand_dims(self._mj_model.body_mass, 1)
        xpos = data.xipos
        return (self._np.sum(mass * xpos, 0) / self._np.sum(mass))[0]

    def step(self, state: mjx_env.State, action: jax.Array) -> mjx_env.State:
        action = self.params.action_scale * action
        state.info['posbefore'] = self.mass_center(state.data)
        data = self._step_fn(state.data, action)
        state.info['posafter'] = self.mass_center(data)

        done = self.fall_termination(data)
        rewards = self.reward_function(
            data   = data,
            action = action,
            info   = state.info,
            done   = done
        )
        reward, metrics = self.get_reward_and_metrics(rewards, state.metrics)
        obs = self._get_obs(
            data,
            state.info
        )
        done = done.astype(float)
        return self._state_init_fn(data, obs, reward, done, metrics, state.info)

    def fall_termination(self, data):
        return data.qpos[2] < 0.6

    def _get_obs(self, data: mjx.Data, info: dict) -> jax.Array:
        del info  # Unused.
        return self._np.concatenate([
            self.joint_angles(data),
            self.head_height(data).reshape(1),
            self.extremities(data).ravel(),
            self.torso_vertical_orientation(data),
            HumanoidInterface.com_vel(data),
            data.qvel,
        ])

    @property
    def action_size(self):
        return self._mj_model.nu

    def reward_function(
        self,
        data,
        action,
        info,
        done
    ):
        rewards = {
            'alive'     : self.reward_alive(),
            'energy'    : self.reward_energy(data, action),
            'run'       : self.reward_run(info),
            'done'      : self.reward_done(done)
        }
        return rewards

    def reward_alive(self):
        return 1.0

    def reward_run(self, info):
        return (info['posafter'] - info['posbefore']) / self.dt

    def reward_done(self, done):
        return self._np.array(done)

    def reward_energy(self, data, action):
        # norm_actuation = self._np.sum(self._np.abs(data.ctrl)) * 1 / self.params.action_scale
        # energy = (self.mj_model.nu - norm_actuation)
        # return energy
        # print(self._np.sum(self.params.action_scale * self.mj_model.actuator_gear))
        # quit()
        # actuation_lvl = self._np.sum((data.qfrc_actuator))
        # return actuation_lvl

        energy = self._np.max(
            self._np.array(
                [3.0 - self._np.sum(self._np.square(action / self.params.action_scale)),
                0.0]
            )
        )
        return energy


    def joint_angles(self, data: mjx.Data) -> jax.Array:
        """Returns the state without global orientation or position."""
        return data.qpos[self.qpos_free:]

    def torso_vertical_orientation(self, data: mjx.Data) -> jax.Array:
        """Returns the z-projection of the torso orientation matrix."""
        return data.xmat[HumanoidInterface.TORSO_ID].reshape((3,3))[2]

    def com_position(self, data: mjx.Data) -> jax.Array:
        """Returns the position of the center of mass in global coordinates."""
        return data.subtree_com[HumanoidInterface.TORSO_ID]

    def head_height(self, data: mjx.Data) -> jax.Array:
        """Returns the height of the torso."""
        return data.xpos[HumanoidInterface.HEAD_ID, -1]

    def torso_upright(self, data: mjx.Data) -> jax.Array:
        """Returns projection from z-axes of torso to the z-axes of world."""
        return data.xmat[HumanoidInterface.TORSO_ID, 2, 2]

    def extremities(self, data: mjx.Data) -> jax.Array:
        """Returns end effector positions in the egocentric frame."""
        torso_frame   = data.xmat[HumanoidInterface.TORSO_ID].reshape((3,3))
        torso_pos     = data.xpos[HumanoidInterface.TORSO_ID]
        torso_to_limb = data.xpos[HumanoidInterface.TORSO_ID] - torso_pos
        return (torso_to_limb @ torso_frame).ravel()

qfrc_max instance-attribute

qfrc_max = self.params.action_scale * self._np.sum(self.mj_model.actuator_gear[:, 0])

action_size property

action_size

reset

reset(rng: Array) -> State
Source code in src/moplayground/envs/dmcontrol/humanoid.py
def reset(self, rng: jax.Array) -> mjx_env.State:
    qpos = self._np.hstack([
        HumanoidInterface.DEFAULT_FF,
        HumanoidInterface.DEFAULT_JT
    ])
    qvel = self._np.zeros(self.mj_model.nv)
    ctrl = qpos[self.qpos_free:].copy()

    data = self._data_init_fn(
        qpos         = qpos,
        qvel         = qvel,
        ctrl         = ctrl,
        time         = 0.0,
        xfrc_applied = self._np.zeros((self._mj_model.nbody, 6)),
    )

    info = {}
    info['posbefore'] = 0.0
    info['posafter']  = 0.01

    done = self._np.array(0.0)
    rewards = self.reward_function(
        data   = data,
        action = ctrl,
        info   = info,
        done   = False,
    )
    reward, metrics = self.get_reward_and_metrics(rewards, {})

    obs = self._get_obs(data, info)
    return self._state_init_fn(data, obs, reward, done, metrics, info)

mass_center

mass_center(data)
Source code in src/moplayground/envs/dmcontrol/humanoid.py
def mass_center(self, data):
    mass = self._np.expand_dims(self._mj_model.body_mass, 1)
    xpos = data.xipos
    return (self._np.sum(mass * xpos, 0) / self._np.sum(mass))[0]

step

step(state: State, action: Array) -> State
Source code in src/moplayground/envs/dmcontrol/humanoid.py
def step(self, state: mjx_env.State, action: jax.Array) -> mjx_env.State:
    action = self.params.action_scale * action
    state.info['posbefore'] = self.mass_center(state.data)
    data = self._step_fn(state.data, action)
    state.info['posafter'] = self.mass_center(data)

    done = self.fall_termination(data)
    rewards = self.reward_function(
        data   = data,
        action = action,
        info   = state.info,
        done   = done
    )
    reward, metrics = self.get_reward_and_metrics(rewards, state.metrics)
    obs = self._get_obs(
        data,
        state.info
    )
    done = done.astype(float)
    return self._state_init_fn(data, obs, reward, done, metrics, state.info)

fall_termination

fall_termination(data)
Source code in src/moplayground/envs/dmcontrol/humanoid.py
def fall_termination(self, data):
    return data.qpos[2] < 0.6

reward_function

reward_function(data, action, info, done)
Source code in src/moplayground/envs/dmcontrol/humanoid.py
def reward_function(
    self,
    data,
    action,
    info,
    done
):
    rewards = {
        'alive'     : self.reward_alive(),
        'energy'    : self.reward_energy(data, action),
        'run'       : self.reward_run(info),
        'done'      : self.reward_done(done)
    }
    return rewards

reward_alive

reward_alive()
Source code in src/moplayground/envs/dmcontrol/humanoid.py
def reward_alive(self):
    return 1.0

reward_run

reward_run(info)
Source code in src/moplayground/envs/dmcontrol/humanoid.py
def reward_run(self, info):
    return (info['posafter'] - info['posbefore']) / self.dt

reward_done

reward_done(done)
Source code in src/moplayground/envs/dmcontrol/humanoid.py
def reward_done(self, done):
    return self._np.array(done)

reward_energy

reward_energy(data, action)
Source code in src/moplayground/envs/dmcontrol/humanoid.py
def reward_energy(self, data, action):
    # norm_actuation = self._np.sum(self._np.abs(data.ctrl)) * 1 / self.params.action_scale
    # energy = (self.mj_model.nu - norm_actuation)
    # return energy
    # print(self._np.sum(self.params.action_scale * self.mj_model.actuator_gear))
    # quit()
    # actuation_lvl = self._np.sum((data.qfrc_actuator))
    # return actuation_lvl

    energy = self._np.max(
        self._np.array(
            [3.0 - self._np.sum(self._np.square(action / self.params.action_scale)),
            0.0]
        )
    )
    return energy

joint_angles

joint_angles(data: Data) -> Array

Returns the state without global orientation or position.

Source code in src/moplayground/envs/dmcontrol/humanoid.py
def joint_angles(self, data: mjx.Data) -> jax.Array:
    """Returns the state without global orientation or position."""
    return data.qpos[self.qpos_free:]

torso_vertical_orientation

torso_vertical_orientation(data: Data) -> Array

Returns the z-projection of the torso orientation matrix.

Source code in src/moplayground/envs/dmcontrol/humanoid.py
def torso_vertical_orientation(self, data: mjx.Data) -> jax.Array:
    """Returns the z-projection of the torso orientation matrix."""
    return data.xmat[HumanoidInterface.TORSO_ID].reshape((3,3))[2]

com_position

com_position(data: Data) -> Array

Returns the position of the center of mass in global coordinates.

Source code in src/moplayground/envs/dmcontrol/humanoid.py
def com_position(self, data: mjx.Data) -> jax.Array:
    """Returns the position of the center of mass in global coordinates."""
    return data.subtree_com[HumanoidInterface.TORSO_ID]

head_height

head_height(data: Data) -> Array

Returns the height of the torso.

Source code in src/moplayground/envs/dmcontrol/humanoid.py
def head_height(self, data: mjx.Data) -> jax.Array:
    """Returns the height of the torso."""
    return data.xpos[HumanoidInterface.HEAD_ID, -1]

torso_upright

torso_upright(data: Data) -> Array

Returns projection from z-axes of torso to the z-axes of world.

Source code in src/moplayground/envs/dmcontrol/humanoid.py
def torso_upright(self, data: mjx.Data) -> jax.Array:
    """Returns projection from z-axes of torso to the z-axes of world."""
    return data.xmat[HumanoidInterface.TORSO_ID, 2, 2]

extremities

extremities(data: Data) -> Array

Returns end effector positions in the egocentric frame.

Source code in src/moplayground/envs/dmcontrol/humanoid.py
def extremities(self, data: mjx.Data) -> jax.Array:
    """Returns end effector positions in the egocentric frame."""
    torso_frame   = data.xmat[HumanoidInterface.TORSO_ID].reshape((3,3))
    torso_pos     = data.xpos[HumanoidInterface.TORSO_ID]
    torso_to_limb = data.xpos[HumanoidInterface.TORSO_ID] - torso_pos
    return (torso_to_limb @ torso_frame).ravel()

moplayground.envs.dmcontrol.interface

Classes:

Name Description
CheetahInterface
HopperInterface
AntInterface
WalkerInterface
HumanoidInterface

Attributes:

Name Type Description
INTERFACE_PATH

INTERFACE_PATH module-attribute

INTERFACE_PATH = pathlib.Path(__file__).resolve().parent

CheetahInterface

Attributes:

Name Type Description
XML
DEFAULT_FF
DEFAULT_JT
Source code in src/moplayground/envs/dmcontrol/interface.py
class CheetahInterface:
    XML         = Path(INTERFACE_PATH / 'model/cheetah.xml')
    DEFAULT_FF  = [0.0, 0.0, 0.0]
    DEFAULT_JT  = [0.0] * 6

XML class-attribute instance-attribute

XML = Path(INTERFACE_PATH / 'model/cheetah.xml')

DEFAULT_FF class-attribute instance-attribute

DEFAULT_FF = [0.0, 0.0, 0.0]

DEFAULT_JT class-attribute instance-attribute

DEFAULT_JT = [0.0] * 6

HopperInterface

Attributes:

Name Type Description
XML
DEFAULT_FF
DEFAULT_JT
Source code in src/moplayground/envs/dmcontrol/interface.py
class HopperInterface:
    XML        = Path(INTERFACE_PATH / 'model/hopper.xml')
    DEFAULT_FF = [0.0, 1.0, 0.0]
    DEFAULT_JT = [0.0] * 4

XML class-attribute instance-attribute

XML = Path(INTERFACE_PATH / 'model/hopper.xml')

DEFAULT_FF class-attribute instance-attribute

DEFAULT_FF = [0.0, 1.0, 0.0]

DEFAULT_JT class-attribute instance-attribute

DEFAULT_JT = [0.0] * 4

AntInterface

Attributes:

Name Type Description
XML
DEFAULT_FF
DEFAULT_JT
Source code in src/moplayground/envs/dmcontrol/interface.py
class AntInterface:
    XML        = Path(INTERFACE_PATH / 'model/ant.xml')
    DEFAULT_FF = [0.0, 0.0, 1.0] + [1.0, 0.0, 0.0, 0.0]
    DEFAULT_JT = [0.0, 0.5,
                  0.0, -0.5,
                  0.0, -0.5,
                  0.0, 0.5]

XML class-attribute instance-attribute

XML = Path(INTERFACE_PATH / 'model/ant.xml')

DEFAULT_FF class-attribute instance-attribute

DEFAULT_FF = [0.0, 0.0, 1.0] + [1.0, 0.0, 0.0, 0.0]

DEFAULT_JT class-attribute instance-attribute

DEFAULT_JT = [0.0, 0.5, 0.0, -0.5, 0.0, -0.5, 0.0, 0.5]

WalkerInterface

Attributes:

Name Type Description
XML
DEFAULT_FF
DEFAULT_JT
Source code in src/moplayground/envs/dmcontrol/interface.py
class WalkerInterface:
    XML        = Path(INTERFACE_PATH / 'model/walker.xml')
    DEFAULT_FF = [0.0, 1.5, 0.0]
    DEFAULT_JT = [0.0] * 6

XML class-attribute instance-attribute

XML = Path(INTERFACE_PATH / 'model/walker.xml')

DEFAULT_FF class-attribute instance-attribute

DEFAULT_FF = [0.0, 1.5, 0.0]

DEFAULT_JT class-attribute instance-attribute

DEFAULT_JT = [0.0] * 6

HumanoidInterface

Methods:

Name Description
com_vel

Returns the velocity of the center of mass in global coordinates.

Attributes:

Name Type Description
XML
MJ_MODEL
DEFAULT_FF
DEFAULT_JT
HEAD_ID
TORSO_ID
LH_ID
RH_ID
LF_ID
RF_ID
EXTREMITY_IDS
Source code in src/moplayground/envs/dmcontrol/interface.py
class HumanoidInterface:
    XML           = Path(INTERFACE_PATH / 'model/humanoid.xml')
    MJ_MODEL      = mj.MjModel.from_xml_path(XML.as_posix())
    DEFAULT_FF    = [0.0, 0.0, 1.4, 1.0, 0.0, 0.0, 0.0]
    DEFAULT_JT    = [0.0] * 21
    HEAD_ID       = MJ_MODEL.body('head').id
    TORSO_ID      = MJ_MODEL.body('torso').id
    LH_ID         = MJ_MODEL.body('left_hand').id
    RH_ID         = MJ_MODEL.body('right_hand').id
    LF_ID         = MJ_MODEL.body('left_foot').id
    RF_ID         = MJ_MODEL.body('right_foot').id
    EXTREMITY_IDS = [LH_ID, RH_ID, LF_ID, RF_ID]

    @classmethod
    def com_vel(cls, data: mjx.Data) -> jax.Array:
        """Returns the velocity of the center of mass in global coordinates."""
        return mjx_env.get_sensor_data(cls.MJ_MODEL, data, "torso_subtreelinvel")

XML class-attribute instance-attribute

XML = Path(INTERFACE_PATH / 'model/humanoid.xml')

MJ_MODEL class-attribute instance-attribute

MJ_MODEL = mj.MjModel.from_xml_path(XML.as_posix())

DEFAULT_FF class-attribute instance-attribute

DEFAULT_FF = [0.0, 0.0, 1.4, 1.0, 0.0, 0.0, 0.0]

DEFAULT_JT class-attribute instance-attribute

DEFAULT_JT = [0.0] * 21

HEAD_ID class-attribute instance-attribute

HEAD_ID = MJ_MODEL.body('head').id

TORSO_ID class-attribute instance-attribute

TORSO_ID = MJ_MODEL.body('torso').id

LH_ID class-attribute instance-attribute

LH_ID = MJ_MODEL.body('left_hand').id

RH_ID class-attribute instance-attribute

RH_ID = MJ_MODEL.body('right_hand').id

LF_ID class-attribute instance-attribute

LF_ID = MJ_MODEL.body('left_foot').id

RF_ID class-attribute instance-attribute

RF_ID = MJ_MODEL.body('right_foot').id

EXTREMITY_IDS class-attribute instance-attribute

EXTREMITY_IDS = [LH_ID, RH_ID, LF_ID, RF_ID]

com_vel classmethod

com_vel(data: Data) -> Array

Returns the velocity of the center of mass in global coordinates.

Source code in src/moplayground/envs/dmcontrol/interface.py
@classmethod
def com_vel(cls, data: mjx.Data) -> jax.Array:
    """Returns the velocity of the center of mass in global coordinates."""
    return mjx_env.get_sensor_data(cls.MJ_MODEL, data, "torso_subtreelinvel")

Bipedal locomotion

moplayground.envs.locomotion.generic.bipedal

Classes:

Name Description
BipedalBase

Atalante walker task.

Attributes:

Name Type Description
CHILD_ERROR

CHILD_ERROR module-attribute

CHILD_ERROR = 'Please implement in child class'

BipedalBase

Bases: MultiObjectiveBase

Atalante walker task.

Methods:

Name Description
periodic_push

Assigns random pushes/perturbations that turn on and off based on the

randomize_velocity
reset

Resets the environment to an initial state. Takes in a random key

get_bounds
get_curriculum_level
make_history
update_history
randomize_dynamics
noisy

Generates zero-mean uniform noise in [-lim, lim]. Limits are scaled

handle_env_customization
add_random_ff
add_random_joint_state
get_fall_termination
Source code in src/moplayground/envs/locomotion/generic/bipedal.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
class BipedalBase(MultiObjectiveBase):
    """Atalante walker task."""

    def __init__(self,
                 xml_path: Path,
                 env_params: config_dict.ConfigDict,
                 backend = 'jnp',
        ):
        """Initializes the base bipedal environment for RL training and 
        evaluation. This class implements core functionalities that are common 
        among various bipedal tasks, such as the Atalante X Exoskeleton, 
        Unitree G1, Westwood robotics BRUCE, and others. Moreover, this class 
        implements a swappable backend for JAX and NumPy, allowing for 
        flexibility when it comes to training and evaluation (i.e. JAX for
        training and NumPy for evaluation).

        Args:
            xml_path: Path to the XML file defining the robot and environment.
            config: Configuration dictionary for the environment.
            config_overrides: Optional dictionary to override specific config values.
            backend: Backend to use for computations, either 'jnp' for JAX or 'np' for NumPy.
        """
        super().__init__(
            xml_path    = xml_path,
            env_params  = env_params,
            backend     = backend,
            num_free    = 7
        )

    def periodic_push(
        self, data, info: dict, body_id: int
    ):
        """Assigns random pushes/perturbations that turn on and off based on the
        configuration and the current state of the environment. 

        Args:
            data: MJX data for the robot/environment
            info: State info dict; holds the push RNG and timers
            body_id: the body to apply the push to
        """
        # Get random keys
        info["rng"], pert_r_rng, pert_theta_rng = self._split(
            info["rng"], 3
        )

        # Compute the perturbation
        pert_on = info['push_on'].astype(self._np.int32)
        pert_t0 = info['push_t0']
        push_durations = self._np.array([info['nopush_duration'], info['push_duration']])
        pert_tau = data.time + self.params.ctrl_dt * 2 - pert_t0
        change_pert_state = (pert_tau % push_durations[pert_on]) < self.params.ctrl_dt
        info['push_t0'] = change_pert_state * data.time + (1 - change_pert_state) * pert_t0
        info['push_on'] = change_pert_state * (1 - pert_on) + (1 - change_pert_state) * pert_on

        curriculum = self._np.clip(
            data.time / (1 * self.params.ctrl_dt), 0, 1
        )
        push_config = self.params.push
        r_sample = self._uniform(
            key=pert_r_rng,
            shape=1,
            minval=curriculum * (1 - push_config.annulus_width),
            maxval=curriculum 
        )[0]
        theta_sample = self._uniform(
            key=pert_theta_rng,
            shape=1,
            minval=0.0,
            maxval=2 * self._np.pi
        )[0]
        pertx = push_config.major_lim * r_sample * self._np.cos(theta_sample)
        perty = push_config.minor_lim * r_sample * self._np.sin(theta_sample)
        pertx, perty = self._np.where(
            self._np.all(self._np.abs(info['vdes']) <= self._np.array(self.params.push.max_vdes)),
            self._np.array([pertx, perty]),
            self._np.zeros(2)
        )

        cmd_pert = info['push_override']
        pertx = (1 - cmd_pert) * pertx + cmd_pert * info['push_override_xy'][0]
        perty = (1 - cmd_pert) * perty + cmd_pert * info['push_override_xy'][1]
        rel_pert_vec = self._np.array([pertx, perty, 0.0])
        rel_pert_vec = change_pert_state * rel_pert_vec + (1 - change_pert_state) * info['curr_pert']
        rel_pert_vec = info['push_on'] * rel_pert_vec
        info['curr_pert'] = rel_pert_vec


        rpy = geo.quat2euler(self._np, data.qpos[3:7])
        rot_mat = geo.rotz(self._np, rpy[2])
        global_pert = rot_mat @ rel_pert_vec

        perturbation_vec = self._np.array([
            *global_pert, # force (x, y, z)
            0.0,   0.0,   0.0  # torque (x, y, z)    
        ])

        new_xfrc_applied = self._set_val_fn(
            arr=self._np.copy(data.xfrc_applied),
            val=perturbation_vec,
            min_idx=body_id,
            max_idx=body_id + 1
        )
        data = self._set_xfrc_fn(data, new_xfrc_applied)
        return data, info

    def randomize_velocity(
        self, data_info, override: bool = False
    ):
        data, info = data_info
        info["rng"], v_rng = self._split(
            info["rng"], 2
        )

        tau = data.time - info['vdes_t0'] + self.params.ctrl_dt * 2
        change = (tau % info['vdes_duration']) < self.params.ctrl_dt
        vel_max = self._np.array((self.params.command.lin_vel_x,
                                  self.params.command.lin_vel_y,
                                  self.params.command.ang_vel_z))
        new_v = self._uniform(
            v_rng,
            shape=(3,),
            minval=vel_max[:, 0],
            maxval=vel_max[:, 1]
        )
        info['vdes'] = change * new_v + (1 - change) * info['vdes']
        info['vdes_t0'] = change * data.time + (1 - change) * info['vdes_t0']

        override = self._np.array(override, dtype=self._np.bool_)
        info['vdes'] = override * new_v + (1 - override) * info['vdes']

        return info

    def reset(
        self,
        rng: jax.Array,
        data: mjx.Data,
        torso_id: int,
        floor_id: int,
        ndof: int,
        num_resets: int = 0,
        njoint: int | None = None,
    ) -> mjx_env.State:
        """Resets the environment to an initial state. Takes in a random key
        (rng) as input and outputs the first state of the environment."""
        # Initialize history buffers
        his_len = self.params.history_length
        qpos_history       = self._np.zeros((his_len, self.nq))
        qvel_history       = self._np.zeros((his_len, self.nv))
        noisy_qpos_history = self._np.zeros((his_len, self.nq))
        noisy_qvel_history = self._np.zeros((his_len, self.nv))
        act_history        = self._np.zeros((his_len, self.action_size))

        # Set a simple info dict...
        info = {
            # Random variable
            'rng':                rng,

            # Basic proprioception
            'act_history':        act_history,
            'qpos_history':       qpos_history,
            'noisy_qpos_history': noisy_qpos_history,
            'qvel_history':       qvel_history,
            'noisy_qvel_history': noisy_qvel_history,

            # Push disturbances
            'push_on':            self._np.array(1),
            'push_duration':      self.params.push.push_duration,
            'nopush_duration':    self.params.push.nopush_duration,
            'push_t0':            data.time,
            'curr_pert':          self._np.zeros(3),
            'push_override':      False,
            'push_override_xy':   self._np.zeros(2),

            # Velocity commands
            'vdes':               self._np.array(self.params.initialization.vdes),
            'vdes_t0':            data.time,
            'vdes_duration':      self.params.command.vdes_duration,

            'num_resets':         num_resets + 1
        }

        # Randomize the dynamics of the environment
        dr_params = self.randomize_dynamics(
            rng,
            info     = info,
            torso_id = torso_id,
            floor_id = floor_id,
            ndof     = ndof,
            njoint   = njoint,
        )
        info = info | dr_params

        reward, done = self._np.zeros(2)
        obs, metrics = None, {}
        state = self._state_init_fn(data, obs, reward, done, metrics, info)

        return state

    def get_bounds(
        self,
        percent_change
    ):
        return 1 + self._np.array([-percent_change, percent_change])

    def get_curriculum_level(
        self,
        info
    ):
        if not self.params.curriculum.enabled:
            return self.params.curriculum.scale

        completion = self._np.clip(
            info['num_resets'] / self.params.curriculum.scaling_iterations,
            0.0,
            1.0
        )
        return self.params.curriculum.scale * completion

    def make_history(self, data, length):
        history = self._np.repeat(
            data[self._np.newaxis, :],
            length,
            axis=0
        )

        return history

    def update_history(self, history, new_data):
        history = self._np.roll(history, shift=1, axis=0)
        return self._set_val_fn(history, new_data, max_idx=1)

    def randomize_dynamics(
        self,
        rng,
        info,
        torso_id,
        floor_id,
        ndof,
        njoint = None
    ) -> dict[str | jax.Array]:
        DR = self.params.domain_randomization 
        curr_level = self.get_curriculum_level(info)

        def set_random_params(
            _rng,
            dr_param,
            old_arr,
            rand_shape,
            op=lambda x, y: x * y,
            min_idx=None,
            max_idx=None
        ):
            _rng, key = self._split(_rng)
            bounds = self.get_bounds(dr_param * curr_level)
            rand_val = self._uniform(
                key    = key,
                shape  = rand_shape,
                minval = bounds[0],
                maxval = bounds[1]
            )
            new_arr = self._set_val_fn(
                arr     = old_arr,
                val     = op(old_arr[min_idx:max_idx], rand_val),
                min_idx = min_idx,
                max_idx = max_idx
            )

            return _rng, new_arr

        # FLOOR FRICTION
        rng, floor_friction = set_random_params(
            _rng       = rng,
            dr_param   = DR.params.floor_friction,
            old_arr    = self._mjx_model.geom_friction[floor_id],
            rand_shape = (),
            max_idx    = 1
        )
        geom_friction = self._set_val_fn(
            arr     = self._mjx_model.geom_friction,
            val     = floor_friction,
            min_idx = floor_id,
            max_idx = floor_id + 1
        )

        # DOF FRICTION
        rng, dof_frictionloss = set_random_params(
            _rng       = rng,
            dr_param   = DR.params.dof_frictionloss,
            old_arr    = self._mjx_model.dof_frictionloss,
            rand_shape = njoint,
            min_idx    = geo.FREE3D_VEL,
            max_idx    = None
        )

        # DOF ARMATURE
        rng, dof_armature = set_random_params(
            _rng       = rng,
            dr_param   = DR.params.dof_armature,
            old_arr    = self._mjx_model.dof_armature,
            rand_shape = njoint,
            min_idx    = geo.FREE3D_VEL,
            max_idx    = None
        )

        # DOF DAMPING
        rng, dof_damping = set_random_params(
            _rng       = rng,
            dr_param   = DR.params.dof_damping,
            old_arr    = self._mjx_model.dof_damping,
            rand_shape = njoint,
            min_idx    = geo.FREE3D_VEL,
            max_idx    = None
        )

        # TORSO MASS
        rng, body_mass = set_random_params(
            _rng       = rng,
            dr_param   = DR.params.torso_mass,
            old_arr    = self._mjx_model.body_mass,
            rand_shape = (),
            min_idx    = torso_id,
            max_idx    = torso_id + 1
        )

        # OTHER BODY MASS
        # TODO

        # TORSO COM
        rng, key = self._split(rng)
        torso_com_bounds = curr_level * self._np.array([
            -DR.params.torso_com,
            DR.params.torso_com
        ])
        torso_com = self._uniform(
            key,
            shape=(3,),
            minval=torso_com_bounds[0],
            maxval=torso_com_bounds[1]
        )
        # print('Torso CoM:', torso_com)
        body_ipos = self._set_val_fn(
            arr     = self._mjx_model.body_ipos,
            val     = self._mjx_model.body_ipos[torso_id] + torso_com,
            min_idx = torso_id,
            max_idx = torso_id + 1
        )

        # OTHER BODIES COM
        rng, key = self._split(rng)
        body_com_bounds = curr_level * self._np.array([
            -DR.params.body_com,
            DR.params.body_com
        ])
        body_com = self._uniform(
            key,
            shape=body_ipos.shape,
            minval=body_com_bounds[0],
            maxval=body_com_bounds[1]
        )
        except_torso = self._np.array(
            self._np.ones(self.mj_model.nbody) == torso_id
        ).astype(int)
        body_ipos = body_ipos + body_com * except_torso[:, self._np.newaxis]

        # GAINS
        rng, key = self._split(rng)
        gain_multiplier_bounds = self.get_bounds(DR.params.gain_multiplier * curr_level)
        gain_multiplier = self._uniform(
            key,
            shape=(self.mj_model.actuator_gainprm.shape[0]),
            minval=gain_multiplier_bounds[0],
            maxval=gain_multiplier_bounds[1]
        )[:, self._np.newaxis]
        actuator_gainprm = gain_multiplier * self._mj_model.actuator_gainprm
        actuator_biasprm = gain_multiplier * self._mj_model.actuator_biasprm

        # TIMECONST
        timeconst_multiplier_bounds = self.get_bounds(DR.params.timeconst * curr_level)
        timeconst = self._uniform(
            key,
            shape=(self.mj_model.actuator_dynprm.shape[0]),
            minval=timeconst_multiplier_bounds[0],
            maxval=timeconst_multiplier_bounds[1]
        )[:, self._np.newaxis]
        actuator_dynprm = timeconst * self._mj_model.actuator_dynprm

        # # FOOT COLLISION ANGLE
        # geom_id = 6
        # foot_angle_bounds = self.get_bounds(DR.params.foot_angle * curr_level)
        # foot_angle_offset = self._uniform(
        #     key,
        #     minval=foot_angle_bounds[0],
        #     maxval=foot_angle_bounds[1]
        # )
        # quat_offset = geo.euler2quat(np, np.array([0, 0, foot_angle_offset]))
        # new_quat = geo.quat_mul(np, quat_offset, model.geom_quat[geom_id])

        return {
            'geom_friction'       : geom_friction,
            'dof_frictionloss'    : dof_frictionloss,
            'dof_damping'         : dof_damping,
            'dof_armature'        : dof_armature,
            'body_mass'           : body_mass,
            'body_ipos'           : body_ipos,
            'actuator_gainprm'    : actuator_gainprm,
            'actuator_biasprm'    : actuator_biasprm,
            'actuator_dynprm'     : actuator_dynprm,
        }


    def noisy(self, rng, value: jax.Array, lim: jax.Array, curr_level: jax.Array):
        """Generates zero-mean uniform noise in [-lim, lim]. Limits are scaled
        by curr_level (curriculum level)."""
        rng, temp = self._split(rng)
        lim = curr_level * lim
        noise = self._uniform(
            key    = temp,
            shape  = value.shape,
            minval = -lim,
            maxval = lim
        )
        noisy_value = noise + value
        return rng, noisy_value

    def handle_env_customization(self, state: mjx_env.State, push_body_id):
        # Assign perturbations if necessary
        def apply_push(local_state): 
            data, info = self.periodic_push(
                local_state.data,
                local_state.info.copy(),
                body_id=push_body_id
            )
            return data, info

        def no_push(local_state):
            return local_state.data, local_state.info

        data, info = self._cond(
            self.params.push.enabled,
            apply_push,
            no_push,
            state
        )
        state = state.replace(data=data, info=info)

        def apply_rand_dynamics(mjx_model):
            """Applies random dynamics to the model."""
            temp_model = self._set_model_params_fn(
                mjx_model,
                geom_friction    = state.info['geom_friction'],
                dof_frictionloss = state.info['dof_frictionloss'],
                dof_armature     = state.info['dof_armature'],
                dof_damping      = state.info['dof_damping'],
                body_mass        = state.info['body_mass'],
                body_ipos        = state.info['body_ipos'],
                actuator_gainprm = state.info['actuator_gainprm'],
                actuator_biasprm = state.info['actuator_biasprm'],
                actuator_dynprm  = state.info['actuator_dynprm']
            )
            return temp_model

        def get_normal_dynamics(mjx_model):
            """Returns the original model without any randomization."""
            return mjx_model

        temp_model = self._cond(
            self.params.domain_randomization.enabled,
            apply_rand_dynamics,
            get_normal_dynamics,
            self._mjx_model
        )
        return state, temp_model

    def add_random_ff(self, ff_key: jax.Array, qpos: jax.Array) -> jax.Array:
        _, xy_key, yaw_key = self._split(ff_key, 3)
        dxy = self._uniform(xy_key, (2,), minval=-0.5, maxval=0.5)
        # qpos = qpos.at[0:2].set(qpos[0:2] + dxy)
        qpos = self._set_val_fn(
            arr     = qpos,
            val     = qpos[0:2] + dxy, 
            min_idx = 0,
            max_idx = 2
        )
        yaw = self._uniform(yaw_key, (1,), minval=-3.14, maxval=3.14)
        # roll = self._uniform(key, (1,), minval=-0.04, maxval=0.04)
        # pitch = self._uniform(key, (1,), minval=-0.1, maxval=0.1)
        # quat = geo.quat_mul(self._np, geo.angle2quat(self._np, self._np.array([1, 0, 0]), roll), quat)
        # quat = geo.quat_mul(self._np, geo.angle2quat(self._np, self._np.array([0, 1, 0]), pitch), quat)
        quat = geo.angle2quat(self._np, self._np.array([0, 0, 1]), yaw)
        new_quat = geo.quat_mul(self._np, quat, qpos[3:7])
        qpos = self._set_val_fn(
            arr     = qpos,
            val     = new_quat,
            min_idx = 3,
            max_idx = 7
        )
        return qpos

    def add_random_joint_state(
            self,
            jt_key: jax.Array,
            qpos: jax.Array,
            minval: jax.Array,
            maxval: jax.Array
        ):
        # TODO: This does not appropriately handle joints with no limits
        val = self._uniform(jt_key, qpos[self.qpos_free:].shape[0], minval=minval, maxval=maxval)
        val = self._np.clip(val + qpos[self.qpos_free:], *self._jt_lims)
        qpos = self._set_val_fn(qpos, val, min_idx=geo.FREE3D_POS, max_idx=None)
        return qpos

    def get_fall_termination(
            self, data: mjx.Data, base_height_min: jax.Array
        ) -> jax.Array:
        # Terminates if joint limits are exceeded or the robot falls.
        enabled = self._np.array(self.params.termination.enabled)
        fallen = self._np.array(data.qpos[2] < base_height_min)
        return enabled & fallen

periodic_push

periodic_push(data, info: dict, body_id: int)

Assigns random pushes/perturbations that turn on and off based on the configuration and the current state of the environment.

Parameters:

Name Type Description Default
data

MJX data for the robot/environment

required
info dict

State info dict; holds the push RNG and timers

required
body_id int

the body to apply the push to

required
Source code in src/moplayground/envs/locomotion/generic/bipedal.py
def periodic_push(
    self, data, info: dict, body_id: int
):
    """Assigns random pushes/perturbations that turn on and off based on the
    configuration and the current state of the environment. 

    Args:
        data: MJX data for the robot/environment
        info: State info dict; holds the push RNG and timers
        body_id: the body to apply the push to
    """
    # Get random keys
    info["rng"], pert_r_rng, pert_theta_rng = self._split(
        info["rng"], 3
    )

    # Compute the perturbation
    pert_on = info['push_on'].astype(self._np.int32)
    pert_t0 = info['push_t0']
    push_durations = self._np.array([info['nopush_duration'], info['push_duration']])
    pert_tau = data.time + self.params.ctrl_dt * 2 - pert_t0
    change_pert_state = (pert_tau % push_durations[pert_on]) < self.params.ctrl_dt
    info['push_t0'] = change_pert_state * data.time + (1 - change_pert_state) * pert_t0
    info['push_on'] = change_pert_state * (1 - pert_on) + (1 - change_pert_state) * pert_on

    curriculum = self._np.clip(
        data.time / (1 * self.params.ctrl_dt), 0, 1
    )
    push_config = self.params.push
    r_sample = self._uniform(
        key=pert_r_rng,
        shape=1,
        minval=curriculum * (1 - push_config.annulus_width),
        maxval=curriculum 
    )[0]
    theta_sample = self._uniform(
        key=pert_theta_rng,
        shape=1,
        minval=0.0,
        maxval=2 * self._np.pi
    )[0]
    pertx = push_config.major_lim * r_sample * self._np.cos(theta_sample)
    perty = push_config.minor_lim * r_sample * self._np.sin(theta_sample)
    pertx, perty = self._np.where(
        self._np.all(self._np.abs(info['vdes']) <= self._np.array(self.params.push.max_vdes)),
        self._np.array([pertx, perty]),
        self._np.zeros(2)
    )

    cmd_pert = info['push_override']
    pertx = (1 - cmd_pert) * pertx + cmd_pert * info['push_override_xy'][0]
    perty = (1 - cmd_pert) * perty + cmd_pert * info['push_override_xy'][1]
    rel_pert_vec = self._np.array([pertx, perty, 0.0])
    rel_pert_vec = change_pert_state * rel_pert_vec + (1 - change_pert_state) * info['curr_pert']
    rel_pert_vec = info['push_on'] * rel_pert_vec
    info['curr_pert'] = rel_pert_vec


    rpy = geo.quat2euler(self._np, data.qpos[3:7])
    rot_mat = geo.rotz(self._np, rpy[2])
    global_pert = rot_mat @ rel_pert_vec

    perturbation_vec = self._np.array([
        *global_pert, # force (x, y, z)
        0.0,   0.0,   0.0  # torque (x, y, z)    
    ])

    new_xfrc_applied = self._set_val_fn(
        arr=self._np.copy(data.xfrc_applied),
        val=perturbation_vec,
        min_idx=body_id,
        max_idx=body_id + 1
    )
    data = self._set_xfrc_fn(data, new_xfrc_applied)
    return data, info

randomize_velocity

randomize_velocity(data_info, override: bool = False)
Source code in src/moplayground/envs/locomotion/generic/bipedal.py
def randomize_velocity(
    self, data_info, override: bool = False
):
    data, info = data_info
    info["rng"], v_rng = self._split(
        info["rng"], 2
    )

    tau = data.time - info['vdes_t0'] + self.params.ctrl_dt * 2
    change = (tau % info['vdes_duration']) < self.params.ctrl_dt
    vel_max = self._np.array((self.params.command.lin_vel_x,
                              self.params.command.lin_vel_y,
                              self.params.command.ang_vel_z))
    new_v = self._uniform(
        v_rng,
        shape=(3,),
        minval=vel_max[:, 0],
        maxval=vel_max[:, 1]
    )
    info['vdes'] = change * new_v + (1 - change) * info['vdes']
    info['vdes_t0'] = change * data.time + (1 - change) * info['vdes_t0']

    override = self._np.array(override, dtype=self._np.bool_)
    info['vdes'] = override * new_v + (1 - override) * info['vdes']

    return info

reset

reset(rng: Array, data: Data, torso_id: int, floor_id: int, ndof: int, num_resets: int = 0, njoint: int | None = None) -> State

Resets the environment to an initial state. Takes in a random key (rng) as input and outputs the first state of the environment.

Source code in src/moplayground/envs/locomotion/generic/bipedal.py
def reset(
    self,
    rng: jax.Array,
    data: mjx.Data,
    torso_id: int,
    floor_id: int,
    ndof: int,
    num_resets: int = 0,
    njoint: int | None = None,
) -> mjx_env.State:
    """Resets the environment to an initial state. Takes in a random key
    (rng) as input and outputs the first state of the environment."""
    # Initialize history buffers
    his_len = self.params.history_length
    qpos_history       = self._np.zeros((his_len, self.nq))
    qvel_history       = self._np.zeros((his_len, self.nv))
    noisy_qpos_history = self._np.zeros((his_len, self.nq))
    noisy_qvel_history = self._np.zeros((his_len, self.nv))
    act_history        = self._np.zeros((his_len, self.action_size))

    # Set a simple info dict...
    info = {
        # Random variable
        'rng':                rng,

        # Basic proprioception
        'act_history':        act_history,
        'qpos_history':       qpos_history,
        'noisy_qpos_history': noisy_qpos_history,
        'qvel_history':       qvel_history,
        'noisy_qvel_history': noisy_qvel_history,

        # Push disturbances
        'push_on':            self._np.array(1),
        'push_duration':      self.params.push.push_duration,
        'nopush_duration':    self.params.push.nopush_duration,
        'push_t0':            data.time,
        'curr_pert':          self._np.zeros(3),
        'push_override':      False,
        'push_override_xy':   self._np.zeros(2),

        # Velocity commands
        'vdes':               self._np.array(self.params.initialization.vdes),
        'vdes_t0':            data.time,
        'vdes_duration':      self.params.command.vdes_duration,

        'num_resets':         num_resets + 1
    }

    # Randomize the dynamics of the environment
    dr_params = self.randomize_dynamics(
        rng,
        info     = info,
        torso_id = torso_id,
        floor_id = floor_id,
        ndof     = ndof,
        njoint   = njoint,
    )
    info = info | dr_params

    reward, done = self._np.zeros(2)
    obs, metrics = None, {}
    state = self._state_init_fn(data, obs, reward, done, metrics, info)

    return state

get_bounds

get_bounds(percent_change)
Source code in src/moplayground/envs/locomotion/generic/bipedal.py
def get_bounds(
    self,
    percent_change
):
    return 1 + self._np.array([-percent_change, percent_change])

get_curriculum_level

get_curriculum_level(info)
Source code in src/moplayground/envs/locomotion/generic/bipedal.py
def get_curriculum_level(
    self,
    info
):
    if not self.params.curriculum.enabled:
        return self.params.curriculum.scale

    completion = self._np.clip(
        info['num_resets'] / self.params.curriculum.scaling_iterations,
        0.0,
        1.0
    )
    return self.params.curriculum.scale * completion

make_history

make_history(data, length)
Source code in src/moplayground/envs/locomotion/generic/bipedal.py
def make_history(self, data, length):
    history = self._np.repeat(
        data[self._np.newaxis, :],
        length,
        axis=0
    )

    return history

update_history

update_history(history, new_data)
Source code in src/moplayground/envs/locomotion/generic/bipedal.py
def update_history(self, history, new_data):
    history = self._np.roll(history, shift=1, axis=0)
    return self._set_val_fn(history, new_data, max_idx=1)

randomize_dynamics

randomize_dynamics(rng, info, torso_id, floor_id, ndof, njoint=None) -> dict[str | Array]
Source code in src/moplayground/envs/locomotion/generic/bipedal.py
def randomize_dynamics(
    self,
    rng,
    info,
    torso_id,
    floor_id,
    ndof,
    njoint = None
) -> dict[str | jax.Array]:
    DR = self.params.domain_randomization 
    curr_level = self.get_curriculum_level(info)

    def set_random_params(
        _rng,
        dr_param,
        old_arr,
        rand_shape,
        op=lambda x, y: x * y,
        min_idx=None,
        max_idx=None
    ):
        _rng, key = self._split(_rng)
        bounds = self.get_bounds(dr_param * curr_level)
        rand_val = self._uniform(
            key    = key,
            shape  = rand_shape,
            minval = bounds[0],
            maxval = bounds[1]
        )
        new_arr = self._set_val_fn(
            arr     = old_arr,
            val     = op(old_arr[min_idx:max_idx], rand_val),
            min_idx = min_idx,
            max_idx = max_idx
        )

        return _rng, new_arr

    # FLOOR FRICTION
    rng, floor_friction = set_random_params(
        _rng       = rng,
        dr_param   = DR.params.floor_friction,
        old_arr    = self._mjx_model.geom_friction[floor_id],
        rand_shape = (),
        max_idx    = 1
    )
    geom_friction = self._set_val_fn(
        arr     = self._mjx_model.geom_friction,
        val     = floor_friction,
        min_idx = floor_id,
        max_idx = floor_id + 1
    )

    # DOF FRICTION
    rng, dof_frictionloss = set_random_params(
        _rng       = rng,
        dr_param   = DR.params.dof_frictionloss,
        old_arr    = self._mjx_model.dof_frictionloss,
        rand_shape = njoint,
        min_idx    = geo.FREE3D_VEL,
        max_idx    = None
    )

    # DOF ARMATURE
    rng, dof_armature = set_random_params(
        _rng       = rng,
        dr_param   = DR.params.dof_armature,
        old_arr    = self._mjx_model.dof_armature,
        rand_shape = njoint,
        min_idx    = geo.FREE3D_VEL,
        max_idx    = None
    )

    # DOF DAMPING
    rng, dof_damping = set_random_params(
        _rng       = rng,
        dr_param   = DR.params.dof_damping,
        old_arr    = self._mjx_model.dof_damping,
        rand_shape = njoint,
        min_idx    = geo.FREE3D_VEL,
        max_idx    = None
    )

    # TORSO MASS
    rng, body_mass = set_random_params(
        _rng       = rng,
        dr_param   = DR.params.torso_mass,
        old_arr    = self._mjx_model.body_mass,
        rand_shape = (),
        min_idx    = torso_id,
        max_idx    = torso_id + 1
    )

    # OTHER BODY MASS
    # TODO

    # TORSO COM
    rng, key = self._split(rng)
    torso_com_bounds = curr_level * self._np.array([
        -DR.params.torso_com,
        DR.params.torso_com
    ])
    torso_com = self._uniform(
        key,
        shape=(3,),
        minval=torso_com_bounds[0],
        maxval=torso_com_bounds[1]
    )
    # print('Torso CoM:', torso_com)
    body_ipos = self._set_val_fn(
        arr     = self._mjx_model.body_ipos,
        val     = self._mjx_model.body_ipos[torso_id] + torso_com,
        min_idx = torso_id,
        max_idx = torso_id + 1
    )

    # OTHER BODIES COM
    rng, key = self._split(rng)
    body_com_bounds = curr_level * self._np.array([
        -DR.params.body_com,
        DR.params.body_com
    ])
    body_com = self._uniform(
        key,
        shape=body_ipos.shape,
        minval=body_com_bounds[0],
        maxval=body_com_bounds[1]
    )
    except_torso = self._np.array(
        self._np.ones(self.mj_model.nbody) == torso_id
    ).astype(int)
    body_ipos = body_ipos + body_com * except_torso[:, self._np.newaxis]

    # GAINS
    rng, key = self._split(rng)
    gain_multiplier_bounds = self.get_bounds(DR.params.gain_multiplier * curr_level)
    gain_multiplier = self._uniform(
        key,
        shape=(self.mj_model.actuator_gainprm.shape[0]),
        minval=gain_multiplier_bounds[0],
        maxval=gain_multiplier_bounds[1]
    )[:, self._np.newaxis]
    actuator_gainprm = gain_multiplier * self._mj_model.actuator_gainprm
    actuator_biasprm = gain_multiplier * self._mj_model.actuator_biasprm

    # TIMECONST
    timeconst_multiplier_bounds = self.get_bounds(DR.params.timeconst * curr_level)
    timeconst = self._uniform(
        key,
        shape=(self.mj_model.actuator_dynprm.shape[0]),
        minval=timeconst_multiplier_bounds[0],
        maxval=timeconst_multiplier_bounds[1]
    )[:, self._np.newaxis]
    actuator_dynprm = timeconst * self._mj_model.actuator_dynprm

    # # FOOT COLLISION ANGLE
    # geom_id = 6
    # foot_angle_bounds = self.get_bounds(DR.params.foot_angle * curr_level)
    # foot_angle_offset = self._uniform(
    #     key,
    #     minval=foot_angle_bounds[0],
    #     maxval=foot_angle_bounds[1]
    # )
    # quat_offset = geo.euler2quat(np, np.array([0, 0, foot_angle_offset]))
    # new_quat = geo.quat_mul(np, quat_offset, model.geom_quat[geom_id])

    return {
        'geom_friction'       : geom_friction,
        'dof_frictionloss'    : dof_frictionloss,
        'dof_damping'         : dof_damping,
        'dof_armature'        : dof_armature,
        'body_mass'           : body_mass,
        'body_ipos'           : body_ipos,
        'actuator_gainprm'    : actuator_gainprm,
        'actuator_biasprm'    : actuator_biasprm,
        'actuator_dynprm'     : actuator_dynprm,
    }

noisy

noisy(rng, value: Array, lim: Array, curr_level: Array)

Generates zero-mean uniform noise in [-lim, lim]. Limits are scaled by curr_level (curriculum level).

Source code in src/moplayground/envs/locomotion/generic/bipedal.py
def noisy(self, rng, value: jax.Array, lim: jax.Array, curr_level: jax.Array):
    """Generates zero-mean uniform noise in [-lim, lim]. Limits are scaled
    by curr_level (curriculum level)."""
    rng, temp = self._split(rng)
    lim = curr_level * lim
    noise = self._uniform(
        key    = temp,
        shape  = value.shape,
        minval = -lim,
        maxval = lim
    )
    noisy_value = noise + value
    return rng, noisy_value

handle_env_customization

handle_env_customization(state: State, push_body_id)
Source code in src/moplayground/envs/locomotion/generic/bipedal.py
def handle_env_customization(self, state: mjx_env.State, push_body_id):
    # Assign perturbations if necessary
    def apply_push(local_state): 
        data, info = self.periodic_push(
            local_state.data,
            local_state.info.copy(),
            body_id=push_body_id
        )
        return data, info

    def no_push(local_state):
        return local_state.data, local_state.info

    data, info = self._cond(
        self.params.push.enabled,
        apply_push,
        no_push,
        state
    )
    state = state.replace(data=data, info=info)

    def apply_rand_dynamics(mjx_model):
        """Applies random dynamics to the model."""
        temp_model = self._set_model_params_fn(
            mjx_model,
            geom_friction    = state.info['geom_friction'],
            dof_frictionloss = state.info['dof_frictionloss'],
            dof_armature     = state.info['dof_armature'],
            dof_damping      = state.info['dof_damping'],
            body_mass        = state.info['body_mass'],
            body_ipos        = state.info['body_ipos'],
            actuator_gainprm = state.info['actuator_gainprm'],
            actuator_biasprm = state.info['actuator_biasprm'],
            actuator_dynprm  = state.info['actuator_dynprm']
        )
        return temp_model

    def get_normal_dynamics(mjx_model):
        """Returns the original model without any randomization."""
        return mjx_model

    temp_model = self._cond(
        self.params.domain_randomization.enabled,
        apply_rand_dynamics,
        get_normal_dynamics,
        self._mjx_model
    )
    return state, temp_model

add_random_ff

add_random_ff(ff_key: Array, qpos: Array) -> Array
Source code in src/moplayground/envs/locomotion/generic/bipedal.py
def add_random_ff(self, ff_key: jax.Array, qpos: jax.Array) -> jax.Array:
    _, xy_key, yaw_key = self._split(ff_key, 3)
    dxy = self._uniform(xy_key, (2,), minval=-0.5, maxval=0.5)
    # qpos = qpos.at[0:2].set(qpos[0:2] + dxy)
    qpos = self._set_val_fn(
        arr     = qpos,
        val     = qpos[0:2] + dxy, 
        min_idx = 0,
        max_idx = 2
    )
    yaw = self._uniform(yaw_key, (1,), minval=-3.14, maxval=3.14)
    # roll = self._uniform(key, (1,), minval=-0.04, maxval=0.04)
    # pitch = self._uniform(key, (1,), minval=-0.1, maxval=0.1)
    # quat = geo.quat_mul(self._np, geo.angle2quat(self._np, self._np.array([1, 0, 0]), roll), quat)
    # quat = geo.quat_mul(self._np, geo.angle2quat(self._np, self._np.array([0, 1, 0]), pitch), quat)
    quat = geo.angle2quat(self._np, self._np.array([0, 0, 1]), yaw)
    new_quat = geo.quat_mul(self._np, quat, qpos[3:7])
    qpos = self._set_val_fn(
        arr     = qpos,
        val     = new_quat,
        min_idx = 3,
        max_idx = 7
    )
    return qpos

add_random_joint_state

add_random_joint_state(jt_key: Array, qpos: Array, minval: Array, maxval: Array)
Source code in src/moplayground/envs/locomotion/generic/bipedal.py
def add_random_joint_state(
        self,
        jt_key: jax.Array,
        qpos: jax.Array,
        minval: jax.Array,
        maxval: jax.Array
    ):
    # TODO: This does not appropriately handle joints with no limits
    val = self._uniform(jt_key, qpos[self.qpos_free:].shape[0], minval=minval, maxval=maxval)
    val = self._np.clip(val + qpos[self.qpos_free:], *self._jt_lims)
    qpos = self._set_val_fn(qpos, val, min_idx=geo.FREE3D_POS, max_idx=None)
    return qpos

get_fall_termination

get_fall_termination(data: Data, base_height_min: Array) -> Array
Source code in src/moplayground/envs/locomotion/generic/bipedal.py
def get_fall_termination(
        self, data: mjx.Data, base_height_min: jax.Array
    ) -> jax.Array:
    # Terminates if joint limits are exceeded or the robot falls.
    enabled = self._np.array(self.params.termination.enabled)
    fallen = self._np.array(data.qpos[2] < base_height_min)
    return enabled & fallen

moplayground.envs.locomotion.generic.navigait

Joystick gait tracking for Atalante.

Classes:

Name Description
NaviGait

Implements the NaviGait hybrid architecture for bipedal locomotion. Combines

NaviGait

Bases: BipedalBase

Implements the NaviGait hybrid architecture for bipedal locomotion. Combines gait libraries with traditional reinfrocement learning for enhanced locomotion strategies. For more details, read NaviGait, Janwani et. al. (2026).

This class should be generic to any bipedal robot with a suitable gait library.

Methods:

Name Description
set_initial_data
initialization_randomization
set_gaitlib
reset
update_info
check_reset
animate_data
pre_process_action

Pre-processes the residual actions and re-evaluates the gait library

get_relative_qpos
update_internal_state

Updates the internal state of the environment based on the new data.

get_stand_termination
reward_residual_vel_rate

Attributes:

Name Type Description
animate
num_states
num_degrees
track_yaw
gaitlib
params
Source code in src/moplayground/envs/locomotion/generic/navigait.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
class NaviGait(BipedalBase):
    """
    Implements the NaviGait hybrid architecture for bipedal locomotion. Combines
    gait libraries with traditional reinfrocement learning for enhanced 
    locomotion strategies. For more details, read NaviGait, Janwani et. al.
    (2026).

    This class should be generic to any bipedal robot with a suitable gait
    library.
    """

    def __init__(
        self,
        xml_path,
        gaitlib_path: str,
        num_states: int,
        env_params: config_dict.ConfigDict,
        gait_type='P2',
        backend='jnp',
        num_degree=7,
        animate=False,
        track_yaw=False
    ):
        # Initialize the parent (bipedal) class
        super().__init__(
            xml_path         = xml_path,
            env_params       = env_params,
            backend          = backend,
        )
        self.animate = animate
        self.num_states = num_states
        self.num_degrees = num_degree
        self.track_yaw = track_yaw
        factorial = None
        if backend == 'jnp':
            factorial = jax.scipy.special.factorial
        elif backend == 'np':
            factorial = cpu_factorial

        self.gaitlib = GaitLibrary.from_directory(
            path         = gaitlib_path,
            v0           = self._np.array([0.0, 0.0]),
            num_states   = self.num_states,
            num_degree   = num_degree,
            gnp          = self._np,
            fact         = factorial,
            gait_type    = gait_type,
        )

        # Set the configuration
        self.params = env_params
        self._set_model_vars()

    def _set_model_vars(self) -> None:

        # compute the initial positions and velocities of gait
        self._lowers = self._mj_model.jnt_range[1:, 0]
        self._uppers = self._mj_model.jnt_range[1:, 1]
        self._jt_scale = self._np.array(self.params.jt_scale)
        self._vel_scale = self.params.vel_scale

    def set_initial_data(
        self,
        default_pose: jax.Array
    ):
        init_q = default_pose.copy()
        init_qd = self._np.zeros(self._mj_model.nv)
        init_ctrl = self._np.zeros(self._mj_model.nu)
        init_xfrc = self._np.zeros((self._mj_model.nbody, 6))

        # initialize data
        data = self._data_init_fn(0.0, init_q, init_qd, init_ctrl, init_xfrc)

        return data

    def initialization_randomization(
        self, rng, default_qpos, ndof
    ):
        rng, key = self._split(rng)
        z_bounds = self.get_bounds(self.params.domain_randomization.params.z0)
        rand_z = default_qpos[2] * self._uniform(
            key    = key,
            minval = z_bounds[0],
            maxval = z_bounds[1]
        )
        default_qpos = self._set_val_fn(
            arr     = default_qpos,
            val     = rand_z,
            min_idx = 2,
            max_idx = 3
        )
        if self.params.initialization.strategy == 'random-with-zero':
            rng, vx_rng, vy_rng = self._split(rng, 3)
            lim_vx = self._np.array(self.params.command.lin_vel_x)
            lim_vy = self._np.array(self.params.command.lin_vel_y)
            chosen_vdes = self._np.array([
                self._uniform(vx_rng, minval=lim_vx[0], maxval=lim_vx[1]),
                self._uniform(vy_rng, minval=lim_vy[0], maxval=lim_vy[1])
            ])
            rng, zero_key = self._split(rng)
            chosen_vdes = self._np.where(
                self._uniform(zero_key) > 1 - self.params.initialization.chance_default,
                self._np.zeros(2),
                chosen_vdes
            )
            chosen_vdes = self._np.hstack((chosen_vdes, self._np.array([0.0])))
        else:
            chosen_vdes = self._np.array(self.params.initialization.vdes)


        gaitlib = self.set_gaitlib(
            rng          = rng,
            vdes_gaitlib = chosen_vdes[:2]
        )
        ff_state = gaitlib.ff_evaluate(0)
        jt_state = gaitlib(0)
        des_qpos = self._np.hstack([ff_state[:self.qpos_free], jt_state[:ndof]])
        vdes_is_zero = self._np.all(chosen_vdes[:2] == self._np.zeros(2))
        qpos = self._np.where(
            vdes_is_zero,
            default_qpos.copy(),
            des_qpos
        )
        qvel = self._np.where(
            vdes_is_zero,
            self._np.zeros(self.nv),
            self._np.hstack([ff_state[self.qpos_free:], jt_state[ndof:]])
        )


        if self.params.initialization.strategy == 'manual':
            qpos = des_qpos
            qvel = self._np.hstack([ff_state[self.qpos_free:], jt_state[ndof:]])


        return rng, gaitlib, qpos, qvel


    def set_gaitlib(
        self,
        rng: jax.Array,
        vdes_gaitlib: jax.Array,
    ):
        rng, leg_rng = self._split(rng)

        swing_leg = self._np.array(1.0) # right
        if self.params.start_stance == 'either':
            swing_leg = self._np.round(self._uniform(leg_rng, minval=0, maxval=1))
        elif self.params.start_stance == 'left':
            swing_leg = self._np.array(0.0)

        gaitlib = self.gaitlib.reset_gait(
            vdes      = vdes_gaitlib,
            t         = -0.01,
            swing_leg = swing_leg.astype(self._np.int32)
        )
        return gaitlib


    def reset(
        self,
        rng: jax.Array,
        gaitlib: GaitLibrary,
        global_qpos: jax.Array,
        global_qvel: jax.Array,
        ctrl: jax.Array,
        ndof: int,
        torso_id: int,
        floor_id: int,
        num_resets: int,
        njoint = None,
    ) -> mjx_env.State:        
        data = self._data_init_fn(
            time         = 0.0,
            qpos         = global_qpos,
            qvel         = global_qvel,
            ctrl         = ctrl,
            xfrc_applied = self._np.zeros((self._mj_model.nbody, 6)),
        )
        state = super().reset(rng, data, torso_id, floor_id, ndof, num_resets, njoint = njoint)
        # Calculate offset transform
        relative_base_des = gaitlib.ff_evaluate(0)
        base2global = geo.solve_transform(
            self._np, 
            relative_base_des[:self.qpos_free], 
            global_qpos[:self.qpos_free],
            reset_yaw=True
        )
        # Initialize history buffers.
        his_len = self.params.history_length
        gait_des = gaitlib(0)
        base_des = gaitlib.ff_evaluate(0)
        gait_history = self._np.repeat(gait_des[self._np.newaxis], his_len, axis=0)
        base_history = self._np.repeat(base_des[self._np.newaxis], his_len, axis=0)

        # Setup joint calibration offsets
        rng, key = self._split(rng)
        rand_cal = self.params.initialization.random_jt_calibration
        jt_offset = self._np.zeros(ndof)
        ankle_offset = self._np.array(self.params.ankle_offsets)
        if rand_cal.enabled:
            ankle_offset = ankle_offset + self._uniform(
                key,
                shape=(2),
                minval=rand_cal.minval,
                maxval=rand_cal.maxval
            )
        jt_offset = self._set_val_fn(
            jt_offset,
            ankle_offset[0],
            min_idx=4,
            max_idx=5
        )
        jt_offset = self._set_val_fn(
            jt_offset,
            ankle_offset[1],
            min_idx=9,
            max_idx=10
        )
        additional_info = {
            "rng":                rng,
            'standing':           0.0,
            'last_res_target':    self._np.zeros(ndof),
            'gait_history':       gait_history, 
            'base_history':       base_history,
            'delta_qdot':         self._np.zeros(ndof),
            'jtdot_desired':      self._np.zeros(ndof),
            'base2global':        base2global,
            'old_base2global':    base2global,
            'gaitlib':            gaitlib,
            'vdes':               self._np.hstack((gaitlib.curr_vdes.copy(), self._np.zeros(1))),
            'vdes_res':           self._np.zeros(3),
            'last_vdes_res':      self._np.zeros(3),
            'vel_target':         self._np.zeros(3),
            'res_target':         self._np.zeros(ndof),
            'last_time':          data.time - self.params.ctrl_dt,
            'jt_offset':          jt_offset
        }
        info = state.info | additional_info

        metrics = {}
        for k in self.params.reward.weights.keys():
            metrics[f"reward/{k}"] = self._np.zeros(())

        info['contact'] = self._np.array([False, False])
        obs = None
        reward, done = self._np.zeros(2)
        state = self._state_init_fn(data, obs, reward, done, metrics, info)
        return state

    def update_info(
        self,
        parent_state,
        global_hzd_qpos,
        global_hzd_qvel,
        noisy_gyro,
        noisy_accel,
        qpos_history_len,
        gyro_history_len,
        accel_history_len,
    ):

        base2global = parent_state.info['base2global']
        hzd_relative_qpos = self.get_relative_qpos(global_hzd_qpos, base2global)
        qpos_history = self.make_history(hzd_relative_qpos, qpos_history_len)
        noisy_qpos_history = qpos_history.copy()

        # Don't transform qvel for now...meshing with rpy and quat
        qvel_history = self.make_history(global_hzd_qvel, qpos_history_len)
        noisy_qvel_history = qvel_history.copy()

        gyro_history  = self.make_history(noisy_gyro, gyro_history_len)
        accel_history = self.make_history(noisy_accel, accel_history_len)

        motor_targets = self._np.hstack([
            global_hzd_qpos[self.qpos_free:],
            global_hzd_qvel[self.qvel_free:]
        ])
        motor_target_history = self.make_history(motor_targets, self.params.domain_randomization.action_delay.val[1] + 1)
        additional_info = {
            'gyro_history'        : gyro_history,
            'accel_history'       : accel_history,
            'qpos_history'        : qpos_history,
            'noisy_qpos_history'  : noisy_qpos_history,
            'qvel_history'        : qvel_history,
            'noisy_qvel_history'  : noisy_qvel_history,
            'motor_target_history': motor_target_history,
        }
        additional_info['transform_init'] = self._np.copy(parent_state.info['base2global'])
        updated_info = parent_state.info | additional_info

        return updated_info

    def check_reset(
        self, state: mjx_env.State
    ) -> mjx_env.State:

        def env_reset(rng):
            s = self.reset(rng, num_resets=state.info['num_resets'])
            info = state.info | s.info
            info['num_resets'] = state.info['num_resets']
            metrics = state.metrics | s.metrics
            return self._state_init_fn(
                data=s.data,
                obs=s.obs,
                reward=s.reward,
                done=s.done,
                metrics=metrics,
                info=info
            )

        new_state = self._cond(
            state.data.time < state.info['gaitlib'].t0,
            lambda _: env_reset(state.info['rng']),
            lambda _: state,
            None
        )

        return new_state

    def animate_data(self, state, data, jtpos_des):
        base_qpos = geo.apply_transform(
            self._np,
            state.info['base_history'][0][:self.qpos_free],
            state.info['base2global']
        )
        data.qpos = self._np.hstack([base_qpos, jtpos_des])
        data.qvel = self._np.zeros(self._mj_model.nv)
        data.qvel[:self.qvel_free] = state.info['base_history'][0][self.qpos_free:]

        return data


    def pre_process_action(
        self, 
        time: jax.Array,
        info: dict[str | jax.Array],
        res_joints: jax.Array,
        res_vel: jax.Array,
        recurrent_states: jax.Array,
        ndof: int,
    ) -> jax.Array:
        """Pre-processes the residual actions and re-evaluates the gait library
        to compute the desired joint targets."""

        # Run the residual joint commands through lowpass filter
        dt = time - info['last_time']
        scaled_res_action = self._jt_scale * res_joints
        info['res_target'] = info['res_target'] + dt / self.params.filter_tau * (scaled_res_action - info['res_target'])


        # Calculate a running derivative (Euler velocity) of delta q
        scaled_last_action = info['last_res_target']
        info['delta_qdot'] = info['delta_qdot'] + dt / self.params.filter_tau * ((info['res_target'] - scaled_last_action) / dt - info['delta_qdot'])
        info['last_res_target'] = info['res_target'].copy()

        # Run the residual velocity command through a lowpass filter
        input_res_vel = self._np.hstack((self._vel_scale * res_vel, self._np.zeros(1)))
        info['last_vdes_res'] = info['vdes_res'].copy()
        info['vdes_res'] = info['vdes_res'] + dt / self.params.filter_tau * (input_res_vel - info['vdes_res'])
        vel_cmd_limits = self._np.vstack((
            self.params.command.lin_vel_x,
            self.params.command.lin_vel_y,
            self.params.command.ang_vel_z
        )).T
        info['vel_target'] = self._np.clip(info['vdes'] + info['vdes_res'], *vel_cmd_limits)
        # print(round(self._np.linalg.norm(info['vel_target']), 2))
        # print(self._np.round(info['vdes_res'], 2))

        # Pull the gait corresponding to the desired velocity + residual
        # velocity from the gait library
        def set_new_gait(args: tuple) -> GaitLibrary:
            gaitlib, vdes_gaitlib, t = args
            return gaitlib.set_gait(vdes_gaitlib, t)

        def keep_gait(args: tuple) -> GaitLibrary:
            gaitlib, _, _ = args
            return gaitlib
        gaitlib = info['gaitlib'] 

        gaitlib = self._cond(
            gaitlib.get_step_phase(time) < MIN_SWING_PHASE,
            set_new_gait,
            keep_gait,
            (gaitlib, info['vel_target'][:2], time)
        )
        info['gaitlib'] = gaitlib

        # Calculate the desired joint positions using the gait library
        new_state_des = gaitlib(gaitlib.get_phase(time))
        jt_desired = new_state_des[:ndof]

        # Combine the delta_qdot with qdot desired from the gaitlib to get
        # desired qvel
        jtdot_desired = new_state_des[ndof:] + info['delta_qdot']

        # Compute the final motor targets by adding the residual to desired
        # q_targets = jt_desired + info['res_target'] + info['jt_offset']
        q_targets = info['res_target']

        if self.params.tracking == 'position':
            vel_enabled = self._np.zeros(1)
        elif self.params.tracking == 'position-velocity':
            vel_enabled = self._np.ones(1)
        else:
            raise Exception(f'Tracking mode {self.params.tracking} DNE')

        motor_targets = self._np.hstack([q_targets, vel_enabled * jtdot_desired])
        info['last_time'] = time

        info['act_history'] = self.update_history(
            info['act_history'],
            self._np.hstack([res_joints, res_vel, recurrent_states])
        )

        info['motor_target_history'] = self.update_history(
            info['motor_target_history'],
            motor_targets
        )
        return motor_targets, info

    def get_relative_qpos(
        self,
        qpos,
        base2global
    ):
        relative_qpos = self._np.hstack([
            geo.apply_transform(self._np, qpos[:self.qpos_free], geo.inv_transform(self._np, base2global)),
            qpos[self.qpos_free:],
        ])
        return relative_qpos

    def update_internal_state(
        self,
        time: jax.Array,
        qpos: jax.Array,
        qvel: jax.Array,
        info: dict[str, jax.Array],
        res_joints: jax.Array,
        left_ground_contact: bool,
        right_ground_contact: bool,
        gyro: jax.Array,
        accel: jax.Array,
        ndof: int,
        qpos_noise: float,
        qvel_noise: float,
        attitude_noise: float
    ) -> dict[str | jax.Array]:
        """Updates the internal state of the environment based on the new data.
        Necessary to compute the observations for next policy inference"""

        gaitlib: GaitLibrary = info['gaitlib']
        step_phase = gaitlib.get_step_phase(time)
        phase = gaitlib.get_phase(time)

        # check for a step
        swing_contact = self._cond(
            gaitlib.swing_leg == 0,
            lambda _: left_ground_contact,
            lambda _: right_ground_contact,
            None
        )
        ground_contact = (swing_contact & (step_phase > MIN_SWING_PHASE)) \
                         | (phase >= 1.0)
        # ground_contact = phase >= 1.0

        # Switch stance and remake gait object if necessary
        switch_stance = lambda x: x.impact_reset(time, self._cond)
        keep_stance = lambda x: x

        new_gaitlib = self._cond(
            ground_contact,
            switch_stance,
            keep_stance,
            gaitlib
        )

        # Update the state info with the new gait object and the desired gait targets
        gait_phase = new_gaitlib.get_phase(time)
        # base_pos = state.info['base_des'][:self.qpos_free] + state.info['base_offset']
        new_gait_des = new_gaitlib(gait_phase)
        new_base_des = new_gaitlib.ff_evaluate(gait_phase)
        switched = self._np.astype((ground_contact), self._np.int32)
        heading = geo.extract_yaw(self._np, qpos[3:7])
        euler_yaw = geo.quat2euler(self._np, heading)[2]
        # quit()

        base2global = geo.solve_transform(
            self._np,
            new_base_des[:self.qpos_free],
            qpos[:self.qpos_free],
            cmd_yaw_offset=-1.6 * qpos[1] if self.track_yaw else None #info['vdes'][2]
        )
        info['old_base2global'] = info['base2global'].copy()
        info['base2global'] = switched * base2global + (1 - switched) * info['base2global']
        info['gaitlib'] = new_gaitlib

        # Update history.
        relative_qpos = self.get_relative_qpos(qpos, info['base2global'])
        info['rng'], noisy_jt = self.noisy(
            rng        = info['rng'],
            value      = relative_qpos[self.qpos_free:],
            lim        = qpos_noise,
            curr_level = self.get_curriculum_level(info)
        )
        noisy_jt = noisy_jt + info['jt_offset']
        info['rng'], noisy_omega = self.noisy(
            rng        = info['rng'],
            value      = self._np.zeros(3),
            lim        = attitude_noise,
            curr_level = self.get_curriculum_level(info)
        )
        noisy_quat_additional = geo.euler2quat(self._np, noisy_omega)
        noisy_quat = geo.quat_mul(self._np, noisy_quat_additional, relative_qpos[3:self.qpos_free])
        noisy_qpos = self._np.hstack([
            relative_qpos[:3],
            noisy_quat,
            noisy_jt
        ])
        info['rng'], noisy_qvel = self.noisy(
            rng        = info['rng'],
            value      = qvel,
            lim        = qvel_noise,
            curr_level = self.get_curriculum_level(info)
        )
        qpos_history       = self.update_history(info['qpos_history'], relative_qpos)
        noisy_qpos_history = self.update_history(info['noisy_qpos_history'], noisy_qpos)
        qvel_history       = self.update_history(info['qvel_history'], qvel)
        noisy_qvel_history = self.update_history(info['noisy_qvel_history'], noisy_qvel)
        base_history       = self.update_history(info['base_history'], new_base_des)
        gait_history       = self.update_history(info['gait_history'], new_gait_des)
        gyro_history       = self.update_history(info['gyro_history'], gyro)
        accel_history      = self.update_history(info['accel_history'], accel)

        info['qpos_history']       = qpos_history
        info['noisy_qpos_history'] = noisy_qpos_history
        info['qvel_history']       = qvel_history
        info['noisy_qvel_history'] = noisy_qvel_history
        info['gait_history']       = gait_history
        info['base_history']       = base_history
        info['gyro_history']       = gyro_history
        info['accel_history']      = accel_history

        return info

    def get_stand_termination(self, info, max_stand_time):
        enabled = self._np.array(self.params.termination.enabled)
        standing = info['standing'] > max_stand_time
        return enabled & standing


    def _get_obs(
        self,
        info: dict[str, Any],
        time,
        ndof
    ) -> jax.Array:

        # info['rng'], key = self._split(info['rng'])
        # obs_delay = self.params.domain_randomization.obs_delay
        # rand_delays = self._np.round(self._uniform(
        #     key,
        #     shape=(3,),
        #     minval=self._np.array([obs_delay.gyro[0], obs_delay.accel[0], obs_delay.qpos[0]]),
        #     maxval=self._np.array([obs_delay.gyro[1], obs_delay.accel[1], obs_delay.qpos[1]])
        # )).astype(self._np.int32)

        # gyro_delay, accel_delay, qpos_delay = self._np.where(
        #     self.params.domain_randomization.obs_delay.enabled,
        #     rand_delays,
        #     self._np.ones(3).astype(self._np.int32)
        # )
        gyro_delay, accel_delay, qpos_delay = info['obs_delay'], info['obs_delay'], info['obs_delay']

        his_len = self.params.history_length
        proprioception = self._np.hstack([
            self._splice(info['gyro_history'], (gyro_delay, 0), (his_len, 3)).flatten(),
            self._splice(info['accel_history'], (accel_delay, 0), (his_len, 3)).flatten(),
        ])
        references = self._np.hstack([
            info['gait_history'][0][ndof:],
            info['base_history'][0][self.qpos_free:],
            info['gaitlib'].swing_leg,
            info['gaitlib'].get_phase(time)
        ])

        output_feedback = self._np.hstack([
            info['act_history'].flatten() # includes recurrent states...
        ])

        command = info['vdes'][:2] # only needs xy for observation...

        history = self._np.hstack([
            self._splice(info['noisy_qpos_history'], (qpos_delay, 3), (his_len, self.nq - 3)).flatten(),
            info['gait_history'][:his_len, :ndof].flatten(),
            info['base_history'][:his_len, :self.qpos_free].flatten(),
        ])

        privileged_history = self._np.hstack([
            info['qpos_history'][:his_len].flatten(),
        ])

        disturbance = info['curr_pert']

        obs = self._np.hstack([
            proprioception,
            references,
            output_feedback,
            command,
            history
        ])

        privileged_obs = self._np.hstack([
            obs,
            privileged_history,
            disturbance,
            info['jt_offset']
        ])

        return {
            'state': obs,
            'privileged_state': privileged_obs
        }

    def reward_residual_vel_rate(
        self,
        vdes_res: jax.Array,
        last_vdes_res: jax.Array,
        vdes_res_rate_sigma: jax.Array
    ) -> jax.Array:
        # Penalize the size of the residual.
        err = self._np.sum(self._np.square(vdes_res - last_vdes_res))
        return self.exp_reward(err, vdes_res_rate_sigma)

animate instance-attribute

animate = animate

num_states instance-attribute

num_states = num_states

num_degrees instance-attribute

num_degrees = num_degree

track_yaw instance-attribute

track_yaw = track_yaw

gaitlib instance-attribute

gaitlib = GaitLibrary.from_directory(path=gaitlib_path, v0=self._np.array([0.0, 0.0]), num_states=self.num_states, num_degree=num_degree, gnp=self._np, fact=factorial, gait_type=gait_type)

params instance-attribute

params = env_params

set_initial_data

set_initial_data(default_pose: Array)
Source code in src/moplayground/envs/locomotion/generic/navigait.py
def set_initial_data(
    self,
    default_pose: jax.Array
):
    init_q = default_pose.copy()
    init_qd = self._np.zeros(self._mj_model.nv)
    init_ctrl = self._np.zeros(self._mj_model.nu)
    init_xfrc = self._np.zeros((self._mj_model.nbody, 6))

    # initialize data
    data = self._data_init_fn(0.0, init_q, init_qd, init_ctrl, init_xfrc)

    return data

initialization_randomization

initialization_randomization(rng, default_qpos, ndof)
Source code in src/moplayground/envs/locomotion/generic/navigait.py
def initialization_randomization(
    self, rng, default_qpos, ndof
):
    rng, key = self._split(rng)
    z_bounds = self.get_bounds(self.params.domain_randomization.params.z0)
    rand_z = default_qpos[2] * self._uniform(
        key    = key,
        minval = z_bounds[0],
        maxval = z_bounds[1]
    )
    default_qpos = self._set_val_fn(
        arr     = default_qpos,
        val     = rand_z,
        min_idx = 2,
        max_idx = 3
    )
    if self.params.initialization.strategy == 'random-with-zero':
        rng, vx_rng, vy_rng = self._split(rng, 3)
        lim_vx = self._np.array(self.params.command.lin_vel_x)
        lim_vy = self._np.array(self.params.command.lin_vel_y)
        chosen_vdes = self._np.array([
            self._uniform(vx_rng, minval=lim_vx[0], maxval=lim_vx[1]),
            self._uniform(vy_rng, minval=lim_vy[0], maxval=lim_vy[1])
        ])
        rng, zero_key = self._split(rng)
        chosen_vdes = self._np.where(
            self._uniform(zero_key) > 1 - self.params.initialization.chance_default,
            self._np.zeros(2),
            chosen_vdes
        )
        chosen_vdes = self._np.hstack((chosen_vdes, self._np.array([0.0])))
    else:
        chosen_vdes = self._np.array(self.params.initialization.vdes)


    gaitlib = self.set_gaitlib(
        rng          = rng,
        vdes_gaitlib = chosen_vdes[:2]
    )
    ff_state = gaitlib.ff_evaluate(0)
    jt_state = gaitlib(0)
    des_qpos = self._np.hstack([ff_state[:self.qpos_free], jt_state[:ndof]])
    vdes_is_zero = self._np.all(chosen_vdes[:2] == self._np.zeros(2))
    qpos = self._np.where(
        vdes_is_zero,
        default_qpos.copy(),
        des_qpos
    )
    qvel = self._np.where(
        vdes_is_zero,
        self._np.zeros(self.nv),
        self._np.hstack([ff_state[self.qpos_free:], jt_state[ndof:]])
    )


    if self.params.initialization.strategy == 'manual':
        qpos = des_qpos
        qvel = self._np.hstack([ff_state[self.qpos_free:], jt_state[ndof:]])


    return rng, gaitlib, qpos, qvel

set_gaitlib

set_gaitlib(rng: Array, vdes_gaitlib: Array)
Source code in src/moplayground/envs/locomotion/generic/navigait.py
def set_gaitlib(
    self,
    rng: jax.Array,
    vdes_gaitlib: jax.Array,
):
    rng, leg_rng = self._split(rng)

    swing_leg = self._np.array(1.0) # right
    if self.params.start_stance == 'either':
        swing_leg = self._np.round(self._uniform(leg_rng, minval=0, maxval=1))
    elif self.params.start_stance == 'left':
        swing_leg = self._np.array(0.0)

    gaitlib = self.gaitlib.reset_gait(
        vdes      = vdes_gaitlib,
        t         = -0.01,
        swing_leg = swing_leg.astype(self._np.int32)
    )
    return gaitlib

reset

reset(rng: Array, gaitlib: GaitLibrary, global_qpos: Array, global_qvel: Array, ctrl: Array, ndof: int, torso_id: int, floor_id: int, num_resets: int, njoint=None) -> State
Source code in src/moplayground/envs/locomotion/generic/navigait.py
def reset(
    self,
    rng: jax.Array,
    gaitlib: GaitLibrary,
    global_qpos: jax.Array,
    global_qvel: jax.Array,
    ctrl: jax.Array,
    ndof: int,
    torso_id: int,
    floor_id: int,
    num_resets: int,
    njoint = None,
) -> mjx_env.State:        
    data = self._data_init_fn(
        time         = 0.0,
        qpos         = global_qpos,
        qvel         = global_qvel,
        ctrl         = ctrl,
        xfrc_applied = self._np.zeros((self._mj_model.nbody, 6)),
    )
    state = super().reset(rng, data, torso_id, floor_id, ndof, num_resets, njoint = njoint)
    # Calculate offset transform
    relative_base_des = gaitlib.ff_evaluate(0)
    base2global = geo.solve_transform(
        self._np, 
        relative_base_des[:self.qpos_free], 
        global_qpos[:self.qpos_free],
        reset_yaw=True
    )
    # Initialize history buffers.
    his_len = self.params.history_length
    gait_des = gaitlib(0)
    base_des = gaitlib.ff_evaluate(0)
    gait_history = self._np.repeat(gait_des[self._np.newaxis], his_len, axis=0)
    base_history = self._np.repeat(base_des[self._np.newaxis], his_len, axis=0)

    # Setup joint calibration offsets
    rng, key = self._split(rng)
    rand_cal = self.params.initialization.random_jt_calibration
    jt_offset = self._np.zeros(ndof)
    ankle_offset = self._np.array(self.params.ankle_offsets)
    if rand_cal.enabled:
        ankle_offset = ankle_offset + self._uniform(
            key,
            shape=(2),
            minval=rand_cal.minval,
            maxval=rand_cal.maxval
        )
    jt_offset = self._set_val_fn(
        jt_offset,
        ankle_offset[0],
        min_idx=4,
        max_idx=5
    )
    jt_offset = self._set_val_fn(
        jt_offset,
        ankle_offset[1],
        min_idx=9,
        max_idx=10
    )
    additional_info = {
        "rng":                rng,
        'standing':           0.0,
        'last_res_target':    self._np.zeros(ndof),
        'gait_history':       gait_history, 
        'base_history':       base_history,
        'delta_qdot':         self._np.zeros(ndof),
        'jtdot_desired':      self._np.zeros(ndof),
        'base2global':        base2global,
        'old_base2global':    base2global,
        'gaitlib':            gaitlib,
        'vdes':               self._np.hstack((gaitlib.curr_vdes.copy(), self._np.zeros(1))),
        'vdes_res':           self._np.zeros(3),
        'last_vdes_res':      self._np.zeros(3),
        'vel_target':         self._np.zeros(3),
        'res_target':         self._np.zeros(ndof),
        'last_time':          data.time - self.params.ctrl_dt,
        'jt_offset':          jt_offset
    }
    info = state.info | additional_info

    metrics = {}
    for k in self.params.reward.weights.keys():
        metrics[f"reward/{k}"] = self._np.zeros(())

    info['contact'] = self._np.array([False, False])
    obs = None
    reward, done = self._np.zeros(2)
    state = self._state_init_fn(data, obs, reward, done, metrics, info)
    return state

update_info

update_info(parent_state, global_hzd_qpos, global_hzd_qvel, noisy_gyro, noisy_accel, qpos_history_len, gyro_history_len, accel_history_len)
Source code in src/moplayground/envs/locomotion/generic/navigait.py
def update_info(
    self,
    parent_state,
    global_hzd_qpos,
    global_hzd_qvel,
    noisy_gyro,
    noisy_accel,
    qpos_history_len,
    gyro_history_len,
    accel_history_len,
):

    base2global = parent_state.info['base2global']
    hzd_relative_qpos = self.get_relative_qpos(global_hzd_qpos, base2global)
    qpos_history = self.make_history(hzd_relative_qpos, qpos_history_len)
    noisy_qpos_history = qpos_history.copy()

    # Don't transform qvel for now...meshing with rpy and quat
    qvel_history = self.make_history(global_hzd_qvel, qpos_history_len)
    noisy_qvel_history = qvel_history.copy()

    gyro_history  = self.make_history(noisy_gyro, gyro_history_len)
    accel_history = self.make_history(noisy_accel, accel_history_len)

    motor_targets = self._np.hstack([
        global_hzd_qpos[self.qpos_free:],
        global_hzd_qvel[self.qvel_free:]
    ])
    motor_target_history = self.make_history(motor_targets, self.params.domain_randomization.action_delay.val[1] + 1)
    additional_info = {
        'gyro_history'        : gyro_history,
        'accel_history'       : accel_history,
        'qpos_history'        : qpos_history,
        'noisy_qpos_history'  : noisy_qpos_history,
        'qvel_history'        : qvel_history,
        'noisy_qvel_history'  : noisy_qvel_history,
        'motor_target_history': motor_target_history,
    }
    additional_info['transform_init'] = self._np.copy(parent_state.info['base2global'])
    updated_info = parent_state.info | additional_info

    return updated_info

check_reset

check_reset(state: State) -> State
Source code in src/moplayground/envs/locomotion/generic/navigait.py
def check_reset(
    self, state: mjx_env.State
) -> mjx_env.State:

    def env_reset(rng):
        s = self.reset(rng, num_resets=state.info['num_resets'])
        info = state.info | s.info
        info['num_resets'] = state.info['num_resets']
        metrics = state.metrics | s.metrics
        return self._state_init_fn(
            data=s.data,
            obs=s.obs,
            reward=s.reward,
            done=s.done,
            metrics=metrics,
            info=info
        )

    new_state = self._cond(
        state.data.time < state.info['gaitlib'].t0,
        lambda _: env_reset(state.info['rng']),
        lambda _: state,
        None
    )

    return new_state

animate_data

animate_data(state, data, jtpos_des)
Source code in src/moplayground/envs/locomotion/generic/navigait.py
def animate_data(self, state, data, jtpos_des):
    base_qpos = geo.apply_transform(
        self._np,
        state.info['base_history'][0][:self.qpos_free],
        state.info['base2global']
    )
    data.qpos = self._np.hstack([base_qpos, jtpos_des])
    data.qvel = self._np.zeros(self._mj_model.nv)
    data.qvel[:self.qvel_free] = state.info['base_history'][0][self.qpos_free:]

    return data

pre_process_action

pre_process_action(time: Array, info: dict[str | Array], res_joints: Array, res_vel: Array, recurrent_states: Array, ndof: int) -> Array

Pre-processes the residual actions and re-evaluates the gait library to compute the desired joint targets.

Source code in src/moplayground/envs/locomotion/generic/navigait.py
def pre_process_action(
    self, 
    time: jax.Array,
    info: dict[str | jax.Array],
    res_joints: jax.Array,
    res_vel: jax.Array,
    recurrent_states: jax.Array,
    ndof: int,
) -> jax.Array:
    """Pre-processes the residual actions and re-evaluates the gait library
    to compute the desired joint targets."""

    # Run the residual joint commands through lowpass filter
    dt = time - info['last_time']
    scaled_res_action = self._jt_scale * res_joints
    info['res_target'] = info['res_target'] + dt / self.params.filter_tau * (scaled_res_action - info['res_target'])


    # Calculate a running derivative (Euler velocity) of delta q
    scaled_last_action = info['last_res_target']
    info['delta_qdot'] = info['delta_qdot'] + dt / self.params.filter_tau * ((info['res_target'] - scaled_last_action) / dt - info['delta_qdot'])
    info['last_res_target'] = info['res_target'].copy()

    # Run the residual velocity command through a lowpass filter
    input_res_vel = self._np.hstack((self._vel_scale * res_vel, self._np.zeros(1)))
    info['last_vdes_res'] = info['vdes_res'].copy()
    info['vdes_res'] = info['vdes_res'] + dt / self.params.filter_tau * (input_res_vel - info['vdes_res'])
    vel_cmd_limits = self._np.vstack((
        self.params.command.lin_vel_x,
        self.params.command.lin_vel_y,
        self.params.command.ang_vel_z
    )).T
    info['vel_target'] = self._np.clip(info['vdes'] + info['vdes_res'], *vel_cmd_limits)
    # print(round(self._np.linalg.norm(info['vel_target']), 2))
    # print(self._np.round(info['vdes_res'], 2))

    # Pull the gait corresponding to the desired velocity + residual
    # velocity from the gait library
    def set_new_gait(args: tuple) -> GaitLibrary:
        gaitlib, vdes_gaitlib, t = args
        return gaitlib.set_gait(vdes_gaitlib, t)

    def keep_gait(args: tuple) -> GaitLibrary:
        gaitlib, _, _ = args
        return gaitlib
    gaitlib = info['gaitlib'] 

    gaitlib = self._cond(
        gaitlib.get_step_phase(time) < MIN_SWING_PHASE,
        set_new_gait,
        keep_gait,
        (gaitlib, info['vel_target'][:2], time)
    )
    info['gaitlib'] = gaitlib

    # Calculate the desired joint positions using the gait library
    new_state_des = gaitlib(gaitlib.get_phase(time))
    jt_desired = new_state_des[:ndof]

    # Combine the delta_qdot with qdot desired from the gaitlib to get
    # desired qvel
    jtdot_desired = new_state_des[ndof:] + info['delta_qdot']

    # Compute the final motor targets by adding the residual to desired
    # q_targets = jt_desired + info['res_target'] + info['jt_offset']
    q_targets = info['res_target']

    if self.params.tracking == 'position':
        vel_enabled = self._np.zeros(1)
    elif self.params.tracking == 'position-velocity':
        vel_enabled = self._np.ones(1)
    else:
        raise Exception(f'Tracking mode {self.params.tracking} DNE')

    motor_targets = self._np.hstack([q_targets, vel_enabled * jtdot_desired])
    info['last_time'] = time

    info['act_history'] = self.update_history(
        info['act_history'],
        self._np.hstack([res_joints, res_vel, recurrent_states])
    )

    info['motor_target_history'] = self.update_history(
        info['motor_target_history'],
        motor_targets
    )
    return motor_targets, info

get_relative_qpos

get_relative_qpos(qpos, base2global)
Source code in src/moplayground/envs/locomotion/generic/navigait.py
def get_relative_qpos(
    self,
    qpos,
    base2global
):
    relative_qpos = self._np.hstack([
        geo.apply_transform(self._np, qpos[:self.qpos_free], geo.inv_transform(self._np, base2global)),
        qpos[self.qpos_free:],
    ])
    return relative_qpos

update_internal_state

update_internal_state(time: Array, qpos: Array, qvel: Array, info: dict[str, Array], res_joints: Array, left_ground_contact: bool, right_ground_contact: bool, gyro: Array, accel: Array, ndof: int, qpos_noise: float, qvel_noise: float, attitude_noise: float) -> dict[str | Array]

Updates the internal state of the environment based on the new data. Necessary to compute the observations for next policy inference

Source code in src/moplayground/envs/locomotion/generic/navigait.py
def update_internal_state(
    self,
    time: jax.Array,
    qpos: jax.Array,
    qvel: jax.Array,
    info: dict[str, jax.Array],
    res_joints: jax.Array,
    left_ground_contact: bool,
    right_ground_contact: bool,
    gyro: jax.Array,
    accel: jax.Array,
    ndof: int,
    qpos_noise: float,
    qvel_noise: float,
    attitude_noise: float
) -> dict[str | jax.Array]:
    """Updates the internal state of the environment based on the new data.
    Necessary to compute the observations for next policy inference"""

    gaitlib: GaitLibrary = info['gaitlib']
    step_phase = gaitlib.get_step_phase(time)
    phase = gaitlib.get_phase(time)

    # check for a step
    swing_contact = self._cond(
        gaitlib.swing_leg == 0,
        lambda _: left_ground_contact,
        lambda _: right_ground_contact,
        None
    )
    ground_contact = (swing_contact & (step_phase > MIN_SWING_PHASE)) \
                     | (phase >= 1.0)
    # ground_contact = phase >= 1.0

    # Switch stance and remake gait object if necessary
    switch_stance = lambda x: x.impact_reset(time, self._cond)
    keep_stance = lambda x: x

    new_gaitlib = self._cond(
        ground_contact,
        switch_stance,
        keep_stance,
        gaitlib
    )

    # Update the state info with the new gait object and the desired gait targets
    gait_phase = new_gaitlib.get_phase(time)
    # base_pos = state.info['base_des'][:self.qpos_free] + state.info['base_offset']
    new_gait_des = new_gaitlib(gait_phase)
    new_base_des = new_gaitlib.ff_evaluate(gait_phase)
    switched = self._np.astype((ground_contact), self._np.int32)
    heading = geo.extract_yaw(self._np, qpos[3:7])
    euler_yaw = geo.quat2euler(self._np, heading)[2]
    # quit()

    base2global = geo.solve_transform(
        self._np,
        new_base_des[:self.qpos_free],
        qpos[:self.qpos_free],
        cmd_yaw_offset=-1.6 * qpos[1] if self.track_yaw else None #info['vdes'][2]
    )
    info['old_base2global'] = info['base2global'].copy()
    info['base2global'] = switched * base2global + (1 - switched) * info['base2global']
    info['gaitlib'] = new_gaitlib

    # Update history.
    relative_qpos = self.get_relative_qpos(qpos, info['base2global'])
    info['rng'], noisy_jt = self.noisy(
        rng        = info['rng'],
        value      = relative_qpos[self.qpos_free:],
        lim        = qpos_noise,
        curr_level = self.get_curriculum_level(info)
    )
    noisy_jt = noisy_jt + info['jt_offset']
    info['rng'], noisy_omega = self.noisy(
        rng        = info['rng'],
        value      = self._np.zeros(3),
        lim        = attitude_noise,
        curr_level = self.get_curriculum_level(info)
    )
    noisy_quat_additional = geo.euler2quat(self._np, noisy_omega)
    noisy_quat = geo.quat_mul(self._np, noisy_quat_additional, relative_qpos[3:self.qpos_free])
    noisy_qpos = self._np.hstack([
        relative_qpos[:3],
        noisy_quat,
        noisy_jt
    ])
    info['rng'], noisy_qvel = self.noisy(
        rng        = info['rng'],
        value      = qvel,
        lim        = qvel_noise,
        curr_level = self.get_curriculum_level(info)
    )
    qpos_history       = self.update_history(info['qpos_history'], relative_qpos)
    noisy_qpos_history = self.update_history(info['noisy_qpos_history'], noisy_qpos)
    qvel_history       = self.update_history(info['qvel_history'], qvel)
    noisy_qvel_history = self.update_history(info['noisy_qvel_history'], noisy_qvel)
    base_history       = self.update_history(info['base_history'], new_base_des)
    gait_history       = self.update_history(info['gait_history'], new_gait_des)
    gyro_history       = self.update_history(info['gyro_history'], gyro)
    accel_history      = self.update_history(info['accel_history'], accel)

    info['qpos_history']       = qpos_history
    info['noisy_qpos_history'] = noisy_qpos_history
    info['qvel_history']       = qvel_history
    info['noisy_qvel_history'] = noisy_qvel_history
    info['gait_history']       = gait_history
    info['base_history']       = base_history
    info['gyro_history']       = gyro_history
    info['accel_history']      = accel_history

    return info

get_stand_termination

get_stand_termination(info, max_stand_time)
Source code in src/moplayground/envs/locomotion/generic/navigait.py
def get_stand_termination(self, info, max_stand_time):
    enabled = self._np.array(self.params.termination.enabled)
    standing = info['standing'] > max_stand_time
    return enabled & standing

reward_residual_vel_rate

reward_residual_vel_rate(vdes_res: Array, last_vdes_res: Array, vdes_res_rate_sigma: Array) -> Array
Source code in src/moplayground/envs/locomotion/generic/navigait.py
def reward_residual_vel_rate(
    self,
    vdes_res: jax.Array,
    last_vdes_res: jax.Array,
    vdes_res_rate_sigma: jax.Array
) -> jax.Array:
    # Penalize the size of the residual.
    err = self._np.sum(self._np.square(vdes_res - last_vdes_res))
    return self.exp_reward(err, vdes_res_rate_sigma)

moplayground.envs.locomotion.bruce.navigait

Joystick gait tracking for Atalante.

Classes:

Name Description
Bruce

A class for tracking joystick-controlled gait in a simulated environment.

Bruce

Bases: NaviGait

A class for tracking joystick-controlled gait in a simulated environment.

Methods:

Name Description
reset
get_sensor_values
get_gait_qpos_init
reset_ctrl
step
get_ctrl

Returns the control signal for the environment.

reward_function
reward_energy
get_desired_arm_swing
reward_arm_swinging
reward_foot_contact

Reward for foot contact.

cost_impact_velocity

Attributes:

Name Type Description
nq
nv
action_size int
Source code in src/moplayground/envs/locomotion/bruce/navigait.py
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
class Bruce(NaviGait):
    """
    A class for tracking joystick-controlled gait in a simulated environment.
    """

    def __init__(
        self,
        gaitlib_path    : str,
        env_params      : config_dict.ConfigDict,
        gait_type       = 'P2',
        backend         = 'jnp',
        idealistic      = False,
        animate         = False,
        manual_speed    = None,
        track_yaw       = False
    ):  
        # Initialize the parent class
        super().__init__(
            xml_path          = bruce.OFFICIAL_XML,
            env_params        = env_params,
            num_states        = bruce.NDOF,
            backend           = backend,
            gait_type         = gait_type,
            gaitlib_path      = gaitlib_path,
            animate           = animate,
            track_yaw         = track_yaw
        )
        if idealistic:
            self.params.domain_randomization.enabled                 = False
            self.params.domain_randomization.obs_delay.enabled       = False
            self.params.domain_randomization.action_delay.enabled    = False
            self.params.noise_scale                                  = 0.0
            self.params.curriculum.enabled                           = False
            self.params.start_stance                                 = 'left'
            self.params.initialization.add_random_jt.enabled         = False
            self.params.initialization.random_jt_calibration.enabled = False
            self.params.command.enabled                              = False

        if manual_speed is not None:
            self.params.initialization.strategy   = 'manual'
            self.params.initialization.vdes       = manual_speed

        self.nq = geo.FREE3D_POS + bruce.NDOF
        self.nv = geo.FREE3D_VEL + bruce.NDOF
        jt_lb_crank = bruce.full2crank(self._np, self._mj_model.jnt_range[1:, 0].T)
        jt_ub_crank = bruce.full2crank(self._np, self._mj_model.jnt_range[1:, 1].T)
        self._jt_lims = self._np.vstack((jt_lb_crank[np.newaxis, :], jt_ub_crank[np.newaxis, :]))

    def reset(
        self,
        rng: jax.Array,
        num_resets: int = 0,
    ):

        rng, gaitlib, global_hzd_qpos, global_hzd_qvel = self.initialization_randomization(
            rng          = rng, 
            default_qpos = self._np.hstack([bruce.DEFAULT_FF, bruce.DEFAULT_JT]),
            ndof         = bruce.NDOF
        )

        rng, ff_key, jt_key = self._split(rng, 3)
        if self.params.initialization.add_random_yaw:
            global_hzd_qpos = self.add_random_ff(ff_key, global_hzd_qpos)

        if self.params.initialization.add_random_jt.enabled:
            global_full_qpos = self.add_random_joint_state(
                jt_key = jt_key, 
                qpos   = bruce.ext(self._np, bruce.crank2full, global_hzd_qpos, self.qpos_free),
                minval = self.params.initialization.add_random_jt.minval,
                maxval = self.params.initialization.add_random_jt.maxval
            )
            global_hzd_qpos = bruce.ext(self._np, bruce.full2crank, global_full_qpos, self.qpos_free)

        motor_targets_linkage = self._np.hstack((
            global_hzd_qpos[geo.FREE3D_POS:],
            global_hzd_qvel[geo.FREE3D_VEL:]
        ))

        parent_state = super().reset(
            rng                = rng, 
            gaitlib            = gaitlib,
            global_qpos        = bruce.ext(self._np, bruce.crank2full, global_hzd_qpos, geo.FREE3D_POS),
            global_qvel        = bruce.ext(self._np, bruce.crank2full, global_hzd_qvel, geo.FREE3D_VEL),
            ctrl               = motor_targets_linkage,
            ndof               = bruce.NDOF,
            torso_id           = bruce.TORSO_ID,
            floor_id           = bruce.GROUND_GEOM_ID,
            num_resets         = num_resets,
            njoint             = bruce.NJOINT
        )
        parent_state.info['rng'], noisy_gyro, noisy_accel, raw_contacts = self.get_sensor_values(
            parent_state.info['rng'],
            parent_state.data,
            curr_level=self.get_curriculum_level(parent_state.info)
        )


        his_len = self.params.history_length
        obs_delay = self.params.domain_randomization.obs_delay
        updated_info = self.update_info(
            parent_state      = parent_state,
            global_hzd_qpos   = global_hzd_qpos,
            global_hzd_qvel   = global_hzd_qvel,
            noisy_gyro        = noisy_gyro,
            noisy_accel       = noisy_accel,
            qpos_history_len  = his_len + obs_delay.qpos[1] + 1,
            gyro_history_len  = his_len + obs_delay.gyro[1] + 1,
            accel_history_len = his_len + obs_delay.accel[1] + 1,
        )
        updated_info['rng'], key = self._split(parent_state.info['rng'])
        obs_delay = self.params.domain_randomization.obs_delay
        observation_delay = self._np.round(self._uniform(
            key,
            minval=obs_delay.gyro[0],
            maxval=obs_delay.gyro[1]
        )).astype(self._np.int32)
        updated_info['rng'], key = self._split(parent_state.info['rng'])
        action_delay = self._np.round(self._uniform(
            key,
            minval=self.params.domain_randomization.action_delay.val[0],
            maxval=self.params.domain_randomization.action_delay.val[1]
        )).astype(self._np.int32)
        updated_info['obs_delay'] = observation_delay * self._np.array(obs_delay.enabled).astype(self._np.int32)
        updated_info['act_delay'] = action_delay * self._np.array(self.params.domain_randomization.action_delay.enabled).astype(self._np.int32)

        obs = self._get_obs(
            time        = parent_state.data.time,
            info        = updated_info,
            ndof        = bruce.NDOF
        )
        rewards = self.reward_function(
            parent_state.data,
            updated_info['act_history'][0],
            updated_info,
            parent_state.done
        )
        reward, metrics = self.get_reward_and_metrics(
            rewards, parent_state.metrics
        )
        return parent_state.replace(obs=obs, info=updated_info, reward=reward)

    def get_sensor_values(
        self,
        rng,
        data,
        curr_level
    ):
        rng, noisy_gyro = self.noisy(
            rng,
            value      = bruce.get_gyro(self._mj_model, data),
            lim        = self.params.noise_scale * bruce.GYRO_NOISE,
            curr_level = curr_level
        )
        rng, noisy_accel = self.noisy(
            rng,
            value      = bruce.get_accelerometer(self._mj_model, data),
            lim        = self.params.noise_scale * bruce.ACCEL_NOISE,
            curr_level = curr_level
        )

        raw_contacts = bruce.get_raw_contacts(
            self._np,
            self._mj_model,
            data,
            threshold=bruce.CONTACT_THRESHOLD
        )
        return rng, noisy_gyro, noisy_accel, raw_contacts

    def get_gait_qpos_init(
        self,
        vdes_gaitlib,
        random_seed
    ):
        rng = jax.random.PRNGKey(random_seed)
        gaitlib = self.set_gaitlib(
            rng          = rng,
            vdes_gaitlib = vdes_gaitlib,

        )

        ff_state = gaitlib.ff_evaluate(0)[:geo.FREE3D_POS]
        jt_state = gaitlib(0)[:bruce.NDOF]
        ff_vel = gaitlib.ff_evaluate(0)[geo.FREE3D_POS:]
        jt_vel = gaitlib(0)[bruce.NDOF:]
        return self._np.hstack((ff_state, jt_state)), self._np.hstack((ff_vel, jt_vel))

    def reset_ctrl(
        self,
        initial_vdes: np.ndarray,
        global_hzd_qpos: np.ndarray,
        gyro: np.ndarray,
        accel: np.ndarray,
        random_seed: int,
        policy
    ):
        rng = jax.random.PRNGKey(random_seed)
        gaitlib = self.set_gaitlib(
            rng          = rng,
            vdes_gaitlib = initial_vdes[:2]
        )

        ff_state = gaitlib.ff_evaluate(0)[:geo.FREE3D_POS]
        jt_state = gaitlib(0)[:bruce.NDOF]
        desired_qpos = self._np.hstack((ff_state, jt_state))
        mj_qvel = self._np.zeros(self.mjx_model.nv)
        global_hzd_qvel = self._np.zeros(bruce.NDOF + geo.FREE3D_VEL)

        initial_ctrl = gaitlib(0)

        if self._np.linalg.norm(desired_qpos - global_hzd_qpos) < 0.1:
            # TODO: Change to warning if this is not always an error
            print('WARNING: gait initial qpos is different from actual')

        parent_state = super().reset(
            rng          = rng, 
            gaitlib      = gaitlib,
            global_qpos  = bruce.ext(self._np, bruce.crank2full, global_hzd_qpos, geo.FREE3D_POS),
            global_qvel  = mj_qvel,
            ctrl         = initial_ctrl,
            ndof         = bruce.NDOF,
            njoint       = bruce.NJOINT,
            torso_id     = bruce.TORSO_ID,
            floor_id     = bruce.GROUND_GEOM_ID,
            num_resets   = 0
        )

        his_len = self.params.history_length
        obs_delay = self.params.domain_randomization.obs_delay
        updated_info = self.update_info(
            parent_state    = parent_state,
            global_hzd_qpos = global_hzd_qpos,
            global_hzd_qvel = global_hzd_qvel,
            noisy_gyro      = gyro,
            noisy_accel     = accel,
            qpos_history_len  = his_len + obs_delay.qpos[1] + 1,
            gyro_history_len  = his_len + obs_delay.gyro[1] + 1,
            accel_history_len = his_len + obs_delay.accel[1] + 1
        )
        updated_info['obs_delay'] = 0
        updated_info['act_delay'] = 0

        initial_obs = self._get_obs(
            time         = parent_state.data.time,
            info         = updated_info,
            ndof         = bruce.NDOF
        )
        self.policy = policy

        updated_info['jt_offset'] = self._np.zeros(bruce.NDOF)
        # updated_info['jt_offset'][4] = self.params.ankle_offsets[0]
        # updated_info['jt_offset'][9] = self.params.ankle_offsets[1]
        initial_info = updated_info

        return initial_obs, initial_info        

    def step(
        self, state: mjx_env.State, res_action: jax.Array
    ) -> mjx_env.State:
        # Check if the environment has been reset
        state = self.check_reset(state)
        state, rand_model = self.handle_env_customization(state, bruce.TORSO_ID)

        # Pre-process the action to get the motor targets
        res_jt = res_action[:bruce.NDOF]
        res_vel = res_action[bruce.NDOF:bruce.NDOF+2]
        recurrent_states = res_action[bruce.NDOF+2:]
        motor_targets, info = self.pre_process_action(
            time             = state.data.time,
            info             = state.info,
            res_joints       = res_jt,
            res_vel          = res_vel,
            recurrent_states = recurrent_states,
            ndof             = bruce.NDOF
        )
        motor_targets = motor_targets + self._np.hstack([bruce.DEFAULT_JT, self._np.zeros(bruce.NDOF)])
        # motor_targets = self._splice(info['motor_target_history'], (info['act_delay'], 0), (1, bruce.NDOF*2)).flatten()
        motor_targets_linkage = self._np.hstack([
            bruce.crank2bear(self._np, motor_targets[:bruce.NDOF]),
            bruce.crank2bear(self._np, motor_targets[bruce.NDOF:])
        ])
        # Step the simulation
        data = self._step_fn(state.data, motor_targets_linkage, model=rand_model)

        if self.animate:
            jtpos_des = bruce.crank2full(self._np, state.info['gait_history'][0, :bruce.NDOF])
            phase = state.info['gaitlib'].get_step_phase(data.time)
            des_arm_L, des_arm_R = self.get_desired_arm_swing(phase, state.info['gaitlib'].swing_leg)
            jtpos_des = self._np.hstack([jtpos_des[:18], des_arm_L, des_arm_R])
            data      = self.animate_data(state, data, jtpos_des)
        if False:
            data.qpos[2] = 1.0
            data.qvel[:geo.FREE3D_VEL] = 0.0
            data.qacc[:geo.FREE3D_VEL] = 0.0


        # Compute and update contact information
        state.info['rng'], noisy_gyro, noisy_accel, raw_contacts = self.get_sensor_values(
            state.info['rng'],
            data,
            curr_level = self.get_curriculum_level(state.info)
        )

        # Update the internal state of the environment
        updated_info = self.update_internal_state(
            time                  = data.time,
            qpos                  = bruce.ext(self._np, bruce.full2crank, data.qpos, geo.FREE3D_POS),
            qvel                  = bruce.ext(self._np, bruce.full2crank, data.qvel, geo.FREE3D_VEL),
            info                  = info,
            res_joints            = res_jt,
            right_ground_contact  = False,
            left_ground_contact   = False,
            gyro                  = noisy_gyro,
            accel                 = noisy_accel,
            ndof                  = bruce.NDOF,
            qpos_noise            = self.params.noise_scale * bruce.QPOS_NOISE,
            qvel_noise            = self.params.noise_scale * bruce.QVEL_NOISE,
            attitude_noise        = self.params.noise_scale * bruce.ATTITUDE_NOISE
        )

        # Randomize training variables
        updated_info = self._cond(
            self.params.command.enabled,
            self.randomize_velocity,
            lambda data_info: data_info[1],
            (data, updated_info.copy())
        )

        # Compute the observation
        obs = self._get_obs(
            info         = updated_info,
            time         = data.time,
            ndof         = bruce.NDOF
        )

        # Check if done (fallen over)
        done = self.get_fall_termination(
            data            = data, 
            base_height_min = bruce.MIN_BASE_HEIGHT,  
        )

        rewards = self.reward_function(
            data,
            res_action,
            updated_info,
            done
        )
        reward, metrics = self.get_reward_and_metrics(
            rewards, state.metrics
        )

        done = done.astype(self._np.float32)
        new_state = self._state_init_fn(data, obs, reward, done, metrics, updated_info)
        return new_state

    @property
    def action_size(self) -> int:
        return bruce.NDOF + 2 + self.params.recurrent_states

    def get_ctrl(
        self,
        time: float,
        ext_crank_pos: np.ndarray,
        ext_crank_vel: np.ndarray,
        info: dict[str | np.ndarray],
        gyro: np.ndarray,
        accel: np.ndarray,
    ) -> jax.Array:
        """Returns the control signal for the environment."""

        # Update the internal state of the environment        
        updated_info: dict = self.update_internal_state(
            time                 = time,
            qpos                 = ext_crank_pos,
            qvel                 = ext_crank_vel,
            info                 = info,
            res_joints           = info['act_history'][0, :bruce.NDOF],
            left_ground_contact  = False,
            right_ground_contact = False,
            gyro                 = gyro,
            accel                = accel,
            ndof                 = bruce.NDOF,
            qpos_noise           = 0.0,
            qvel_noise           = 0.0,
            attitude_noise       = 0.0
        )

        # Compute the observation
        obs = self._get_obs(
            info         = updated_info,
            time         = time,
            ndof         = bruce.NDOF
        )

        # Run an inference and preprocess the outputs
        res, _              = self.policy(obs, None)
        res_joints          = self._np.array(res[:bruce.NDOF])
        res_vel             = self._np.array(res[bruce.NDOF:bruce.NDOF+2])
        recurrent_states    = self._np.array(res[bruce.NDOF+2:])

        motor_targets, updated_info = self.pre_process_action(
            time                = time,
            info                = updated_info,
            res_joints          = res_joints,
            res_vel             = res_vel,
            ndof                = bruce.NDOF,
            recurrent_states    = recurrent_states
        )

        return motor_targets, updated_info.copy()

    def reward_function(
        self,
        data: mjx.Data,
        action: jax.Array,
        info: dict[str, Any],
        done: jax.Array,
    ) -> tuple[dict[str, jax.Array], dict[str, jax.Array]]:
        sigmas = self.params.reward.sigmas
        base_des = info['base_history'][1]
        gait_des = info['gait_history'][1]
        global_qpos_act = bruce.ext(
            self._np,
            bruce.full2crank,
            data.qpos,
            self.qpos_free
        )
        global_base = geo.apply_transform(
            _np = self._np,
            qpos = base_des,
            offset = info['old_base2global']
        )
        rewards = {
            'gait_tracking' : self.reward_euclidean_imitation(
                qpos            = global_qpos_act[self.qpos_free:self.qpos_free+10],
                reference       = gait_des[:10],
                imitation_sigma = sigmas.gait_tracking
            ),
            'base_xyz_tracking': self.reward_euclidean_imitation(
                qpos            = global_qpos_act[:3],
                reference       = global_base[:3],
                imitation_sigma = sigmas.base_xyz_tracking
            ),
            'base_quat_tracking': self.exp_reward(
                mag2  = geo.quat_dist(
                            _np = self._np,
                            q1  = global_qpos_act[3:geo.FREE3D_POS],
                            q2  = global_base[3:geo.FREE3D_POS]
                )**2,
                sigma = sigmas.base_quat_tracking
            ),
            'minimize_energy': self.reward_energy(
                data.qfrc_actuator
            ),
            'vel_residual_size' : self.reward_vector_size(
                v          = self._vel_scale * info['act_history'][0, bruce.NDOF:],
                size_sigma = sigmas.vel_residual_size
            ),
            'vel_residual_rate' : self.reward_residual_vel_rate(
                vdes_res            = self._vel_scale * info['act_history'][0, bruce.NDOF:],
                last_vdes_res       = self._vel_scale * info['act_history'][1, bruce.NDOF:],
                vdes_res_rate_sigma = sigmas.vel_residual_rate
            ),
            'res_jt_rate': 1.0 - self.reward_action_rate(
                act           = self._jt_scale * info['act_history'][0, :bruce.NDOF],
                last_act      = self._jt_scale * info['act_history'][1, :bruce.NDOF],
                last_last_act = self._jt_scale * info['act_history'][2, :bruce.NDOF],
            ),
            'joint_rate': 0.2 - self.reward_action_rate(
                act           = info['qpos_history'][0, self.qpos_free:self.qpos_free + bruce.NDOF],
                last_act      = info['qpos_history'][1, self.qpos_free:self.qpos_free + bruce.NDOF],
                last_last_act = info['qpos_history'][2, self.qpos_free:self.qpos_free + bruce.NDOF],
            ),
            'arm_swinging': self.reward_arm_swinging(
                qpos_crank        = global_qpos_act[self.qpos_free:],
                step_phase        = info['gaitlib'].get_step_phase(data.time),
                swing_foot        = info['gaitlib'].swing_leg,
                arm_swing_sigma   = sigmas.arm_swing_sigma
            ),
            'arm_static': self.reward_euclidean_imitation(
                qpos            = global_qpos_act[self.qpos_free+10:self.qpos_free+16],
                reference       = gait_des[10:16],
                imitation_sigma = sigmas.arm_swing_sigma
            ),
        }
        return rewards

    def reward_energy(
        self,
        qfrc_actuator
    ):
        torque_limits = self.mj_model.actuator_forcerange
        energy = self._np.sum(self._np.square(qfrc_actuator))
        max_energy = self._np.sum(self._np.square(torque_limits[:, 1]))
        return self._np.max(self._np.array([0.9 * max_energy - energy, 0.0]))

    def get_desired_arm_swing(
        self,
        step_phase,
        swing_foot
    ):
        SHLDR_AMP = 0.4
        ELBW_AMP  = 0.3
        des_arm_L = self._np.array([
            -SHLDR_AMP * self._np.cos(self._np.pi * step_phase + self._np.pi * swing_foot),
            1.0,
            ELBW_AMP * (-self._np.cos(self._np.pi * step_phase + self._np.pi * swing_foot) + 1)
        ])
        des_arm_R = self._np.array([
            -SHLDR_AMP * self._np.cos(self._np.pi * step_phase + self._np.pi * swing_foot),
            -1.0,
            -ELBW_AMP * (-self._np.cos(self._np.pi * step_phase + self._np.pi * (swing_foot + 1)) + 1)
        ])
        return des_arm_L, des_arm_R

    def reward_arm_swinging(
        self,
        qpos_crank,
        step_phase,
        swing_foot,
        arm_swing_sigma
    ):
        arm_swing_des = self._np.hstack(self.get_desired_arm_swing(
            step_phase, swing_foot
        ))
        return self.reward_euclidean_imitation(
            qpos_crank[10:],
            arm_swing_des,
            arm_swing_sigma
        )

    def reward_foot_contact(
        self,
        ground_contact: jax.Array,
        swing_foot: jax.Array
    ) -> jax.Array:
        """Reward for foot contact."""
        feet_des = self._np.array([Leg.LEFT, Leg.RIGHT]) == swing_foot
        # print(f'ground contact: {ground_contact}, feet des: {feet_des}')
        contact_reward = self._np.sum(feet_des == ground_contact.astype(self._np.float32))

        return contact_reward / 2.0

    def cost_impact_velocity(
        self,
        ground_contact: jax.Array,
        foot_velocity: jax.Array
    ):
        fz = foot_velocity[:, -1]
        return self._np.linalg.norm(fz * ground_contact)

nq instance-attribute

nq = geo.FREE3D_POS + bruce.NDOF

nv instance-attribute

nv = geo.FREE3D_VEL + bruce.NDOF

action_size property

action_size: int

reset

reset(rng: Array, num_resets: int = 0)
Source code in src/moplayground/envs/locomotion/bruce/navigait.py
def reset(
    self,
    rng: jax.Array,
    num_resets: int = 0,
):

    rng, gaitlib, global_hzd_qpos, global_hzd_qvel = self.initialization_randomization(
        rng          = rng, 
        default_qpos = self._np.hstack([bruce.DEFAULT_FF, bruce.DEFAULT_JT]),
        ndof         = bruce.NDOF
    )

    rng, ff_key, jt_key = self._split(rng, 3)
    if self.params.initialization.add_random_yaw:
        global_hzd_qpos = self.add_random_ff(ff_key, global_hzd_qpos)

    if self.params.initialization.add_random_jt.enabled:
        global_full_qpos = self.add_random_joint_state(
            jt_key = jt_key, 
            qpos   = bruce.ext(self._np, bruce.crank2full, global_hzd_qpos, self.qpos_free),
            minval = self.params.initialization.add_random_jt.minval,
            maxval = self.params.initialization.add_random_jt.maxval
        )
        global_hzd_qpos = bruce.ext(self._np, bruce.full2crank, global_full_qpos, self.qpos_free)

    motor_targets_linkage = self._np.hstack((
        global_hzd_qpos[geo.FREE3D_POS:],
        global_hzd_qvel[geo.FREE3D_VEL:]
    ))

    parent_state = super().reset(
        rng                = rng, 
        gaitlib            = gaitlib,
        global_qpos        = bruce.ext(self._np, bruce.crank2full, global_hzd_qpos, geo.FREE3D_POS),
        global_qvel        = bruce.ext(self._np, bruce.crank2full, global_hzd_qvel, geo.FREE3D_VEL),
        ctrl               = motor_targets_linkage,
        ndof               = bruce.NDOF,
        torso_id           = bruce.TORSO_ID,
        floor_id           = bruce.GROUND_GEOM_ID,
        num_resets         = num_resets,
        njoint             = bruce.NJOINT
    )
    parent_state.info['rng'], noisy_gyro, noisy_accel, raw_contacts = self.get_sensor_values(
        parent_state.info['rng'],
        parent_state.data,
        curr_level=self.get_curriculum_level(parent_state.info)
    )


    his_len = self.params.history_length
    obs_delay = self.params.domain_randomization.obs_delay
    updated_info = self.update_info(
        parent_state      = parent_state,
        global_hzd_qpos   = global_hzd_qpos,
        global_hzd_qvel   = global_hzd_qvel,
        noisy_gyro        = noisy_gyro,
        noisy_accel       = noisy_accel,
        qpos_history_len  = his_len + obs_delay.qpos[1] + 1,
        gyro_history_len  = his_len + obs_delay.gyro[1] + 1,
        accel_history_len = his_len + obs_delay.accel[1] + 1,
    )
    updated_info['rng'], key = self._split(parent_state.info['rng'])
    obs_delay = self.params.domain_randomization.obs_delay
    observation_delay = self._np.round(self._uniform(
        key,
        minval=obs_delay.gyro[0],
        maxval=obs_delay.gyro[1]
    )).astype(self._np.int32)
    updated_info['rng'], key = self._split(parent_state.info['rng'])
    action_delay = self._np.round(self._uniform(
        key,
        minval=self.params.domain_randomization.action_delay.val[0],
        maxval=self.params.domain_randomization.action_delay.val[1]
    )).astype(self._np.int32)
    updated_info['obs_delay'] = observation_delay * self._np.array(obs_delay.enabled).astype(self._np.int32)
    updated_info['act_delay'] = action_delay * self._np.array(self.params.domain_randomization.action_delay.enabled).astype(self._np.int32)

    obs = self._get_obs(
        time        = parent_state.data.time,
        info        = updated_info,
        ndof        = bruce.NDOF
    )
    rewards = self.reward_function(
        parent_state.data,
        updated_info['act_history'][0],
        updated_info,
        parent_state.done
    )
    reward, metrics = self.get_reward_and_metrics(
        rewards, parent_state.metrics
    )
    return parent_state.replace(obs=obs, info=updated_info, reward=reward)

get_sensor_values

get_sensor_values(rng, data, curr_level)
Source code in src/moplayground/envs/locomotion/bruce/navigait.py
def get_sensor_values(
    self,
    rng,
    data,
    curr_level
):
    rng, noisy_gyro = self.noisy(
        rng,
        value      = bruce.get_gyro(self._mj_model, data),
        lim        = self.params.noise_scale * bruce.GYRO_NOISE,
        curr_level = curr_level
    )
    rng, noisy_accel = self.noisy(
        rng,
        value      = bruce.get_accelerometer(self._mj_model, data),
        lim        = self.params.noise_scale * bruce.ACCEL_NOISE,
        curr_level = curr_level
    )

    raw_contacts = bruce.get_raw_contacts(
        self._np,
        self._mj_model,
        data,
        threshold=bruce.CONTACT_THRESHOLD
    )
    return rng, noisy_gyro, noisy_accel, raw_contacts

get_gait_qpos_init

get_gait_qpos_init(vdes_gaitlib, random_seed)
Source code in src/moplayground/envs/locomotion/bruce/navigait.py
def get_gait_qpos_init(
    self,
    vdes_gaitlib,
    random_seed
):
    rng = jax.random.PRNGKey(random_seed)
    gaitlib = self.set_gaitlib(
        rng          = rng,
        vdes_gaitlib = vdes_gaitlib,

    )

    ff_state = gaitlib.ff_evaluate(0)[:geo.FREE3D_POS]
    jt_state = gaitlib(0)[:bruce.NDOF]
    ff_vel = gaitlib.ff_evaluate(0)[geo.FREE3D_POS:]
    jt_vel = gaitlib(0)[bruce.NDOF:]
    return self._np.hstack((ff_state, jt_state)), self._np.hstack((ff_vel, jt_vel))

reset_ctrl

reset_ctrl(initial_vdes: ndarray, global_hzd_qpos: ndarray, gyro: ndarray, accel: ndarray, random_seed: int, policy)
Source code in src/moplayground/envs/locomotion/bruce/navigait.py
def reset_ctrl(
    self,
    initial_vdes: np.ndarray,
    global_hzd_qpos: np.ndarray,
    gyro: np.ndarray,
    accel: np.ndarray,
    random_seed: int,
    policy
):
    rng = jax.random.PRNGKey(random_seed)
    gaitlib = self.set_gaitlib(
        rng          = rng,
        vdes_gaitlib = initial_vdes[:2]
    )

    ff_state = gaitlib.ff_evaluate(0)[:geo.FREE3D_POS]
    jt_state = gaitlib(0)[:bruce.NDOF]
    desired_qpos = self._np.hstack((ff_state, jt_state))
    mj_qvel = self._np.zeros(self.mjx_model.nv)
    global_hzd_qvel = self._np.zeros(bruce.NDOF + geo.FREE3D_VEL)

    initial_ctrl = gaitlib(0)

    if self._np.linalg.norm(desired_qpos - global_hzd_qpos) < 0.1:
        # TODO: Change to warning if this is not always an error
        print('WARNING: gait initial qpos is different from actual')

    parent_state = super().reset(
        rng          = rng, 
        gaitlib      = gaitlib,
        global_qpos  = bruce.ext(self._np, bruce.crank2full, global_hzd_qpos, geo.FREE3D_POS),
        global_qvel  = mj_qvel,
        ctrl         = initial_ctrl,
        ndof         = bruce.NDOF,
        njoint       = bruce.NJOINT,
        torso_id     = bruce.TORSO_ID,
        floor_id     = bruce.GROUND_GEOM_ID,
        num_resets   = 0
    )

    his_len = self.params.history_length
    obs_delay = self.params.domain_randomization.obs_delay
    updated_info = self.update_info(
        parent_state    = parent_state,
        global_hzd_qpos = global_hzd_qpos,
        global_hzd_qvel = global_hzd_qvel,
        noisy_gyro      = gyro,
        noisy_accel     = accel,
        qpos_history_len  = his_len + obs_delay.qpos[1] + 1,
        gyro_history_len  = his_len + obs_delay.gyro[1] + 1,
        accel_history_len = his_len + obs_delay.accel[1] + 1
    )
    updated_info['obs_delay'] = 0
    updated_info['act_delay'] = 0

    initial_obs = self._get_obs(
        time         = parent_state.data.time,
        info         = updated_info,
        ndof         = bruce.NDOF
    )
    self.policy = policy

    updated_info['jt_offset'] = self._np.zeros(bruce.NDOF)
    # updated_info['jt_offset'][4] = self.params.ankle_offsets[0]
    # updated_info['jt_offset'][9] = self.params.ankle_offsets[1]
    initial_info = updated_info

    return initial_obs, initial_info        

step

step(state: State, res_action: Array) -> State
Source code in src/moplayground/envs/locomotion/bruce/navigait.py
def step(
    self, state: mjx_env.State, res_action: jax.Array
) -> mjx_env.State:
    # Check if the environment has been reset
    state = self.check_reset(state)
    state, rand_model = self.handle_env_customization(state, bruce.TORSO_ID)

    # Pre-process the action to get the motor targets
    res_jt = res_action[:bruce.NDOF]
    res_vel = res_action[bruce.NDOF:bruce.NDOF+2]
    recurrent_states = res_action[bruce.NDOF+2:]
    motor_targets, info = self.pre_process_action(
        time             = state.data.time,
        info             = state.info,
        res_joints       = res_jt,
        res_vel          = res_vel,
        recurrent_states = recurrent_states,
        ndof             = bruce.NDOF
    )
    motor_targets = motor_targets + self._np.hstack([bruce.DEFAULT_JT, self._np.zeros(bruce.NDOF)])
    # motor_targets = self._splice(info['motor_target_history'], (info['act_delay'], 0), (1, bruce.NDOF*2)).flatten()
    motor_targets_linkage = self._np.hstack([
        bruce.crank2bear(self._np, motor_targets[:bruce.NDOF]),
        bruce.crank2bear(self._np, motor_targets[bruce.NDOF:])
    ])
    # Step the simulation
    data = self._step_fn(state.data, motor_targets_linkage, model=rand_model)

    if self.animate:
        jtpos_des = bruce.crank2full(self._np, state.info['gait_history'][0, :bruce.NDOF])
        phase = state.info['gaitlib'].get_step_phase(data.time)
        des_arm_L, des_arm_R = self.get_desired_arm_swing(phase, state.info['gaitlib'].swing_leg)
        jtpos_des = self._np.hstack([jtpos_des[:18], des_arm_L, des_arm_R])
        data      = self.animate_data(state, data, jtpos_des)
    if False:
        data.qpos[2] = 1.0
        data.qvel[:geo.FREE3D_VEL] = 0.0
        data.qacc[:geo.FREE3D_VEL] = 0.0


    # Compute and update contact information
    state.info['rng'], noisy_gyro, noisy_accel, raw_contacts = self.get_sensor_values(
        state.info['rng'],
        data,
        curr_level = self.get_curriculum_level(state.info)
    )

    # Update the internal state of the environment
    updated_info = self.update_internal_state(
        time                  = data.time,
        qpos                  = bruce.ext(self._np, bruce.full2crank, data.qpos, geo.FREE3D_POS),
        qvel                  = bruce.ext(self._np, bruce.full2crank, data.qvel, geo.FREE3D_VEL),
        info                  = info,
        res_joints            = res_jt,
        right_ground_contact  = False,
        left_ground_contact   = False,
        gyro                  = noisy_gyro,
        accel                 = noisy_accel,
        ndof                  = bruce.NDOF,
        qpos_noise            = self.params.noise_scale * bruce.QPOS_NOISE,
        qvel_noise            = self.params.noise_scale * bruce.QVEL_NOISE,
        attitude_noise        = self.params.noise_scale * bruce.ATTITUDE_NOISE
    )

    # Randomize training variables
    updated_info = self._cond(
        self.params.command.enabled,
        self.randomize_velocity,
        lambda data_info: data_info[1],
        (data, updated_info.copy())
    )

    # Compute the observation
    obs = self._get_obs(
        info         = updated_info,
        time         = data.time,
        ndof         = bruce.NDOF
    )

    # Check if done (fallen over)
    done = self.get_fall_termination(
        data            = data, 
        base_height_min = bruce.MIN_BASE_HEIGHT,  
    )

    rewards = self.reward_function(
        data,
        res_action,
        updated_info,
        done
    )
    reward, metrics = self.get_reward_and_metrics(
        rewards, state.metrics
    )

    done = done.astype(self._np.float32)
    new_state = self._state_init_fn(data, obs, reward, done, metrics, updated_info)
    return new_state

get_ctrl

get_ctrl(time: float, ext_crank_pos: ndarray, ext_crank_vel: ndarray, info: dict[str | ndarray], gyro: ndarray, accel: ndarray) -> Array

Returns the control signal for the environment.

Source code in src/moplayground/envs/locomotion/bruce/navigait.py
def get_ctrl(
    self,
    time: float,
    ext_crank_pos: np.ndarray,
    ext_crank_vel: np.ndarray,
    info: dict[str | np.ndarray],
    gyro: np.ndarray,
    accel: np.ndarray,
) -> jax.Array:
    """Returns the control signal for the environment."""

    # Update the internal state of the environment        
    updated_info: dict = self.update_internal_state(
        time                 = time,
        qpos                 = ext_crank_pos,
        qvel                 = ext_crank_vel,
        info                 = info,
        res_joints           = info['act_history'][0, :bruce.NDOF],
        left_ground_contact  = False,
        right_ground_contact = False,
        gyro                 = gyro,
        accel                = accel,
        ndof                 = bruce.NDOF,
        qpos_noise           = 0.0,
        qvel_noise           = 0.0,
        attitude_noise       = 0.0
    )

    # Compute the observation
    obs = self._get_obs(
        info         = updated_info,
        time         = time,
        ndof         = bruce.NDOF
    )

    # Run an inference and preprocess the outputs
    res, _              = self.policy(obs, None)
    res_joints          = self._np.array(res[:bruce.NDOF])
    res_vel             = self._np.array(res[bruce.NDOF:bruce.NDOF+2])
    recurrent_states    = self._np.array(res[bruce.NDOF+2:])

    motor_targets, updated_info = self.pre_process_action(
        time                = time,
        info                = updated_info,
        res_joints          = res_joints,
        res_vel             = res_vel,
        ndof                = bruce.NDOF,
        recurrent_states    = recurrent_states
    )

    return motor_targets, updated_info.copy()

reward_function

reward_function(data: Data, action: Array, info: dict[str, Any], done: Array) -> tuple[dict[str, Array], dict[str, Array]]
Source code in src/moplayground/envs/locomotion/bruce/navigait.py
def reward_function(
    self,
    data: mjx.Data,
    action: jax.Array,
    info: dict[str, Any],
    done: jax.Array,
) -> tuple[dict[str, jax.Array], dict[str, jax.Array]]:
    sigmas = self.params.reward.sigmas
    base_des = info['base_history'][1]
    gait_des = info['gait_history'][1]
    global_qpos_act = bruce.ext(
        self._np,
        bruce.full2crank,
        data.qpos,
        self.qpos_free
    )
    global_base = geo.apply_transform(
        _np = self._np,
        qpos = base_des,
        offset = info['old_base2global']
    )
    rewards = {
        'gait_tracking' : self.reward_euclidean_imitation(
            qpos            = global_qpos_act[self.qpos_free:self.qpos_free+10],
            reference       = gait_des[:10],
            imitation_sigma = sigmas.gait_tracking
        ),
        'base_xyz_tracking': self.reward_euclidean_imitation(
            qpos            = global_qpos_act[:3],
            reference       = global_base[:3],
            imitation_sigma = sigmas.base_xyz_tracking
        ),
        'base_quat_tracking': self.exp_reward(
            mag2  = geo.quat_dist(
                        _np = self._np,
                        q1  = global_qpos_act[3:geo.FREE3D_POS],
                        q2  = global_base[3:geo.FREE3D_POS]
            )**2,
            sigma = sigmas.base_quat_tracking
        ),
        'minimize_energy': self.reward_energy(
            data.qfrc_actuator
        ),
        'vel_residual_size' : self.reward_vector_size(
            v          = self._vel_scale * info['act_history'][0, bruce.NDOF:],
            size_sigma = sigmas.vel_residual_size
        ),
        'vel_residual_rate' : self.reward_residual_vel_rate(
            vdes_res            = self._vel_scale * info['act_history'][0, bruce.NDOF:],
            last_vdes_res       = self._vel_scale * info['act_history'][1, bruce.NDOF:],
            vdes_res_rate_sigma = sigmas.vel_residual_rate
        ),
        'res_jt_rate': 1.0 - self.reward_action_rate(
            act           = self._jt_scale * info['act_history'][0, :bruce.NDOF],
            last_act      = self._jt_scale * info['act_history'][1, :bruce.NDOF],
            last_last_act = self._jt_scale * info['act_history'][2, :bruce.NDOF],
        ),
        'joint_rate': 0.2 - self.reward_action_rate(
            act           = info['qpos_history'][0, self.qpos_free:self.qpos_free + bruce.NDOF],
            last_act      = info['qpos_history'][1, self.qpos_free:self.qpos_free + bruce.NDOF],
            last_last_act = info['qpos_history'][2, self.qpos_free:self.qpos_free + bruce.NDOF],
        ),
        'arm_swinging': self.reward_arm_swinging(
            qpos_crank        = global_qpos_act[self.qpos_free:],
            step_phase        = info['gaitlib'].get_step_phase(data.time),
            swing_foot        = info['gaitlib'].swing_leg,
            arm_swing_sigma   = sigmas.arm_swing_sigma
        ),
        'arm_static': self.reward_euclidean_imitation(
            qpos            = global_qpos_act[self.qpos_free+10:self.qpos_free+16],
            reference       = gait_des[10:16],
            imitation_sigma = sigmas.arm_swing_sigma
        ),
    }
    return rewards

reward_energy

reward_energy(qfrc_actuator)
Source code in src/moplayground/envs/locomotion/bruce/navigait.py
def reward_energy(
    self,
    qfrc_actuator
):
    torque_limits = self.mj_model.actuator_forcerange
    energy = self._np.sum(self._np.square(qfrc_actuator))
    max_energy = self._np.sum(self._np.square(torque_limits[:, 1]))
    return self._np.max(self._np.array([0.9 * max_energy - energy, 0.0]))

get_desired_arm_swing

get_desired_arm_swing(step_phase, swing_foot)
Source code in src/moplayground/envs/locomotion/bruce/navigait.py
def get_desired_arm_swing(
    self,
    step_phase,
    swing_foot
):
    SHLDR_AMP = 0.4
    ELBW_AMP  = 0.3
    des_arm_L = self._np.array([
        -SHLDR_AMP * self._np.cos(self._np.pi * step_phase + self._np.pi * swing_foot),
        1.0,
        ELBW_AMP * (-self._np.cos(self._np.pi * step_phase + self._np.pi * swing_foot) + 1)
    ])
    des_arm_R = self._np.array([
        -SHLDR_AMP * self._np.cos(self._np.pi * step_phase + self._np.pi * swing_foot),
        -1.0,
        -ELBW_AMP * (-self._np.cos(self._np.pi * step_phase + self._np.pi * (swing_foot + 1)) + 1)
    ])
    return des_arm_L, des_arm_R

reward_arm_swinging

reward_arm_swinging(qpos_crank, step_phase, swing_foot, arm_swing_sigma)
Source code in src/moplayground/envs/locomotion/bruce/navigait.py
def reward_arm_swinging(
    self,
    qpos_crank,
    step_phase,
    swing_foot,
    arm_swing_sigma
):
    arm_swing_des = self._np.hstack(self.get_desired_arm_swing(
        step_phase, swing_foot
    ))
    return self.reward_euclidean_imitation(
        qpos_crank[10:],
        arm_swing_des,
        arm_swing_sigma
    )

reward_foot_contact

reward_foot_contact(ground_contact: Array, swing_foot: Array) -> Array

Reward for foot contact.

Source code in src/moplayground/envs/locomotion/bruce/navigait.py
def reward_foot_contact(
    self,
    ground_contact: jax.Array,
    swing_foot: jax.Array
) -> jax.Array:
    """Reward for foot contact."""
    feet_des = self._np.array([Leg.LEFT, Leg.RIGHT]) == swing_foot
    # print(f'ground contact: {ground_contact}, feet des: {feet_des}')
    contact_reward = self._np.sum(feet_des == ground_contact.astype(self._np.float32))

    return contact_reward / 2.0

cost_impact_velocity

cost_impact_velocity(ground_contact: Array, foot_velocity: Array)
Source code in src/moplayground/envs/locomotion/bruce/navigait.py
def cost_impact_velocity(
    self,
    ground_contact: jax.Array,
    foot_velocity: jax.Array
):
    fz = foot_velocity[:, -1]
    return self._np.linalg.norm(fz * ground_contact)

moplayground.envs.locomotion.control.gait

Classes:

Name Description
GaitLibrary

Functions:

Name Description
get_states

Attributes:

Name Type Description
MIN_SWING_PHASE
path
v0
num_states
num_degree
gaitlib
axs
phase
old_states

MIN_SWING_PHASE module-attribute

MIN_SWING_PHASE = 0.7

path module-attribute

path = 'control/gaits/2D_library_v6'

v0 module-attribute

v0 = np.array([0.0, 0.0])

num_states module-attribute

num_states = 12

num_degree module-attribute

num_degree = 7

gaitlib module-attribute

gaitlib = GaitLibrary.from_directory(path=path, v0=v0, num_states=num_states, num_degree=num_degree, gait_type='P2', gnp=np, fact=factorial)

axs module-attribute

axs = axs.flatten()

phase module-attribute

phase = np.linspace(0, 1, 100)

old_states module-attribute

old_states = get_states(gaitlib)

GaitLibrary dataclass

Methods:

Name Description
from_directory

Loads a gait library from a directory of yaml files. It should setup

get_1D_idx
find_nearest

Finds the nearest gaits in the gait library with respect to the desired velocity. The output will be FOUR gaits.

combine_gaits

Combines gaits.

interpolate_gait

Interpolates a gait between the current gait and the input gait.

set_gait

Defines an interpolated gait between the current gait, and the input

reset_gait
set_new_coeffs
get_phase
get_step_phase
evaluate
evaluate2
blend_gait
ff_evaluate
impact_reset

Returns a new GaitLibrary object with the swing leg switched and

tree_flatten
tree_unflatten

Attributes:

Name Type Description
num_gaits int
num_states int
num_degree int
num_vx_gaits int
bezier P1Bezier
jt_coeffs ndarray | ndarray
jt_dcoeffs ndarray | ndarray
ff_coeffs ndarray | ndarray
ff_dcoeffs ndarray | ndarray
curr_jt ndarray | ndarray
curr_djt ndarray | ndarray
curr_ff ndarray | ndarray
curr_dff ndarray | ndarray
curr_period float
step_period float
curr_vdes ndarray | ndarray
periods ndarray | ndarray
vel_xs ndarray | ndarray
vel_ys ndarray | ndarray
swing_leg int
t0 float
t0_step float
blend float
offset_pos ndarray | ndarray
offset_vel ndarray | ndarray
gnp object
side_offset ndarray | ndarray
Source code in src/moplayground/envs/locomotion/control/gait.py
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@jax.tree_util.register_pytree_node_class
@dataclass(frozen=True)
class GaitLibrary:
    num_gaits:    int
    num_states:   int
    num_degree:   int
    num_vx_gaits: int
    bezier:       P1Bezier
    jt_coeffs:    jnp.ndarray | np.ndarray
    jt_dcoeffs:   jnp.ndarray | np.ndarray
    ff_coeffs:    jnp.ndarray | np.ndarray
    ff_dcoeffs:   jnp.ndarray | np.ndarray
    curr_jt:      jnp.ndarray | np.ndarray
    curr_djt:     jnp.ndarray | np.ndarray
    curr_ff:      jnp.ndarray | np.ndarray
    curr_dff:     jnp.ndarray | np.ndarray
    curr_period:  float
    step_period:  float
    curr_vdes:    jnp.ndarray | np.ndarray
    periods:      jnp.ndarray | np.ndarray
    vel_xs:       jnp.ndarray | np.ndarray
    vel_ys:       jnp.ndarray | np.ndarray
    swing_leg:    int
    t0:           float
    t0_step:      float
    blend:        float
    offset_pos:   jnp.ndarray | np.ndarray
    offset_vel:   jnp.ndarray | np.ndarray
    gnp:          object   = field(default_factory=lambda: jnp)
    side_offset:  jnp.ndarray | np.ndarray = field(default_factory=lambda: jnp.zeros(6, dtype=jnp.float32))

    @classmethod
    def from_directory(
        cls, 
        path, 
        v0,
        num_states,
        num_degree,
        gnp: object = field(default_factory=lambda: jnp),
        fact: callable = field(default_factory=lambda: jax.scipy.special.factorial),
        swing_leg=Leg.LEFT, 
        t0=0.0, 
        blend=0.3,
        gait_type='P1'
    ):
        """Loads a gait library from a directory of yaml files. It should setup
        jt_coeffs and ff_coeffs to hold a list of coefficients for each gait in 
        the directory."""
        def open_yaml(file):
            with open(file, 'r') as f:
                contents = safe_load(f)
            return dict(contents)

        bez_files = glob(path + '/*.yaml')
        if bez_files == []:
            raise ValueError(f'No yaml files found in {path}. Please check the path.')

        def get_gait(x):
            gait = open_yaml(x)
            return [float(gait['vd_x']), float(gait['vd_y'])], gait

        vels = []
        for file in bez_files:
            vdes, gait = get_gait(file)
            vels.append(vdes)


        num_vx_gaits = len(np.unique(np.array(vels)[:,0]))

        # print(f'{num_vx_gaits} vx gaits found in {path}')

        bez_files = glob(path + '/*.yaml')
        def sort_key(x):
            x = Path(x).stem
            nums = x.split('_')
            return int(nums[1]) * num_vx_gaits + int(nums[2])

        bez_files.sort(key=sort_key)


        bezier = P1Bezier.setup(
            num_states = num_states,
            num_degree = num_degree,
            bnp        = gnp,
            fact       = fact
        )

        jt_coeffs = []
        jt_dcoeffs = []
        ff_coeffs = []
        ff_dcoeffs = []
        vel_xs = []
        vel_ys = []
        periods = []
        vel_lims = np.array([[np.inf, -np.inf], [np.inf, -np.inf]])
        for bez in bez_files:
            gait = open_yaml(bez)
            if gait_type == 'P1':
                # Reshape the bezier coefficients
                # contents['RightSS'] = contents
                jt_coeff = bezier.reshape_coeff(
                    coeff=gait['RightSS']['coeff_jt'],
                    num_states=num_states
                )
                ff_coeff = bezier.reshape_coeff(
                    coeff=gait['RightSS']['coeff_b'],
                    num_states=P1Bezier.FREE_STATES
                )
                num_degree = jt_coeff.shape[1] - 1

                # Compute relabeling...
                jt_coeff, ff_coeff = bezier.relabel(
                    jt_coeff=jt_coeff,
                    ff_coeff=ff_coeff
                )
                periods.append([gait['RightSS']['step_dur']])
            elif gait_type == 'P2':
                jt_coeff1 = bezier.reshape_coeff(
                    coeff=gait['RightSS']['coeff_jt'],
                    num_states=num_states
                )
                ff_coeff1 = bezier.reshape_coeff(
                    coeff=gait['RightSS']['coeff_b'],
                    num_states=P1Bezier.FREE_STATES
                )
                num_degree = jt_coeff1.shape[1] - 1

                # if contents['vd_y'] < 0:
                #     ff_coeff1[1, :] -= contents['LeftSS']['step_len'][1]

                # Reshape the bezier coefficients
                jt_coeff2 = bezier.reshape_coeff(
                    coeff=gait['LeftSS']['coeff_jt'],
                    num_states=num_states
                )
                ff_coeff2 = bezier.reshape_coeff(
                    coeff=gait['LeftSS']['coeff_b'],
                    num_states=P1Bezier.FREE_STATES
                )

                # if contents['vd_y'] < 0:
                #     ff_coeff2[1, :] -= contents['LeftSS']['step_len'][1]

                jt_coeff = gnp.array([jt_coeff1, jt_coeff2])
                ff_coeff = gnp.array([ff_coeff1, ff_coeff2])
                periods.append([gait['RightSS']['step_dur']])
            else:
                raise ValueError(f'Gait type {gait_type} not supported')

            # Compute derivatives...
            jt_dcoeff = bezier.compute_dcoeff(jt_coeff)
            ff_dcoeff = bezier.compute_dcoeff(ff_coeff)

            jt_coeffs.append(jt_coeff)
            jt_dcoeffs.append(jt_dcoeff)
            ff_coeffs.append(ff_coeff)
            ff_dcoeffs.append(ff_dcoeff)

            vel_lims[0, 0] = min(vel_lims[0, 0], gait['vd_x'])
            vel_lims[0, 1] = max(vel_lims[0, 1], gait['vd_x'])
            vel_lims[1, 0] = min(vel_lims[1, 0], gait['vd_y'])
            vel_lims[1, 1] = max(vel_lims[1, 1], gait['vd_y'])

        num_vy_gaits = len(bez_files) // num_vx_gaits
        vel_xs = np.linspace(*vel_lims[0, :], num=num_vx_gaits)
        vel_ys = np.linspace(*vel_lims[1, :], num=num_vy_gaits)
        # print(num_vx_gaits, num_vy_gaits)
        # quit()

        jt_coeffs  = gnp.array(jt_coeffs)
        jt_dcoeffs = gnp.array(jt_dcoeffs)
        ff_coeffs  = gnp.array(ff_coeffs)
        ff_dcoeffs = gnp.array(ff_dcoeffs)
        periods    = gnp.array(periods) 
        vel_xs     = gnp.array(vel_xs)
        vel_ys     = gnp.array(vel_ys)

        side_offset = np.zeros(6)

        # print("Variable Names and Shapes:")
        # print(f"jt_coeffs: {jt_coeffs.shape}")
        # print(f"jt_dcoeffs: {jt_dcoeffs.shape}")
        # print(f"ff_coeffs: {ff_coeffs.shape}")
        # print(f"ff_dcoeffs: {ff_dcoeffs.shape}")
        # print(f"periods: {periods.shape}")
        # print(f"vel_xs: {vel_xs.shape}")
        # print(f"vel_ys: {vel_ys.shape}")
        # quit()

        gaitlib = cls(
            num_gaits    = jt_coeffs.shape[0],
            num_states   = num_states,
            num_degree   = num_degree,
            num_vx_gaits = num_vx_gaits,
            bezier       = bezier,
            jt_coeffs    = jt_coeffs,
            jt_dcoeffs   = jt_dcoeffs,
            ff_coeffs    = ff_coeffs,
            ff_dcoeffs   = ff_dcoeffs,
            curr_jt      = jt_coeffs[0], # place holders...
            curr_djt     = jt_dcoeffs[0],
            curr_ff      = ff_coeffs[0],
            curr_dff     = ff_dcoeffs[0],
            curr_period  = periods[0, 0],
            step_period  = periods[0, 0],
            curr_vdes    = v0,
            periods      = periods,
            vel_xs       = vel_xs,
            vel_ys       = vel_ys,
            swing_leg    = swing_leg,
            t0           = 0.0,
            t0_step      = 0.0,
            blend        = blend,
            offset_pos   = gnp.zeros(num_states, dtype=gnp.float32),
            offset_vel   = gnp.zeros(num_states, dtype=gnp.float32),
            gnp          = gnp,
            side_offset  = side_offset,
        )

        neighbors, weights = gaitlib.find_nearest(v0)
        jt_coeff, ff_coeff, jt_dcoeff, ff_dcoeff, period = gaitlib.combine_gaits(
            neighbors,
            weights
        )
        return gaitlib.set_new_coeffs(
            jt_coeff=jt_coeff,
            jt_dcoeff=jt_dcoeff,
            ff_coeff=ff_coeff,
            ff_dcoeff=ff_dcoeff,
            period=period,
            step_period=period,
            t0=t0,
            t0_step=t0,
            vdes=v0,
            swing_leg=swing_leg
        )

    def get_1D_idx(self, vx_idx, vy_idx):
        num_vy_gaits = self.num_gaits // self.num_vx_gaits
        return vx_idx * num_vy_gaits + vy_idx

    def find_nearest(self, vdes):
        """Finds the nearest gaits in the gait library with respect to the\
            desired velocity. The output will be FOUR gaits.

            vdes: (np.ndarray) desired velocity (vx, vy)

            Returns: (vx_gaits, vy_gaits)
                vx_gaits: (alpha1, alpha2, weight_alpha)
                vy_gaits: (beta1, beta2, weight_beta)
            """
        # print(f'vdes {vdes}')
        num_vy_gaits = self.num_gaits // self.num_vx_gaits
        x1_idx = self.gnp.searchsorted(self.vel_xs, vdes[0])
        x1_idx = self.gnp.clip(x1_idx, 0, self.num_vx_gaits - 1)
        x2_idx = self.gnp.clip(x1_idx - 1, 0, self.num_vx_gaits - 1)
        y1_idx = self.gnp.searchsorted(self.vel_ys, vdes[1])
        y1_idx = self.gnp.clip(y1_idx, 0, num_vy_gaits - 1)
        y2_idx = self.gnp.clip(y1_idx - 1, 0, num_vy_gaits - 1)
        # print(f"x1_idx: {x1_idx}, x2_idx: {x2_idx}, y1_idx: {y1_idx}, y2_idx: {y2_idx}")
        # print(f"num_gaits: {self.num_gaits}")
        # print()

        neighbor_idxs = self.gnp.array([
            self.get_1D_idx(x1_idx, y1_idx),
            self.get_1D_idx(x2_idx, y1_idx),
            self.get_1D_idx(x1_idx, y2_idx)
        ])
        # print(f"neighbor_idxs: {neighbor_idxs}")
        # print()

        neighbors = self.gnp.array([idx for idx in neighbor_idxs])

        vx1, vy1 = self.vel_xs[x1_idx], self.vel_ys[y1_idx]
        vx2, vy2 = self.vel_xs[x2_idx], self.vel_ys[y1_idx]
        vx3, vy3 = self.vel_xs[x1_idx], self.vel_ys[y2_idx]

        def solve_convex_comb(args):
            """Solves the convex combination of two points"""
            v1, v2, vd = args
            return (vd - v2) / (v1 - v2)

        w1_zero = self.gnp.array(self.gnp.abs(vx1 - vx2) < 1e-2).astype(self.gnp.int32)
        w1 = self.gnp.array([
            solve_convex_comb([vx1, vx2 + 1 * w1_zero, vdes[0]]),
            vx1,
        ])[w1_zero]

        w2_zero = self.gnp.array(self.gnp.abs(vy1 - vy3) < 1e-2).astype(self.gnp.int32)
        w2 = self.gnp.array([
            solve_convex_comb([vy1, vy3 + 1 * w2_zero, vdes[1]]) ,
            vy1,
        ])[w2_zero]

        # print('v', vdes, neighbor_idxs, np.array([w1, w2]), x1_idx * w1 + x2_idx * (1 - w1))

        return neighbors, self.gnp.array([w1, w2])


    def combine_gaits(
            self,
            neighbors,
            weights
    ):
        """Combines gaits.

        Returns a single convex combination of the four gaits. Size will be
        (2, nstates, ndegree + 1) as it includes the relabeling.
        """
        jt_ns = self.jt_coeffs[neighbors] # joint neighbors
        jt_coeff = jt_ns[0] * weights[0] + jt_ns[1] * (1 - weights[0])
        jt_coeff = jt_coeff * weights[1] + jt_ns[2] * (1 - weights[1]) # add this back in for 2D lib

        ff_ns = self.ff_coeffs[neighbors] # flying frame neighbors
        ff_coeff = ff_ns[0] * weights[0] + ff_ns[1] * (1 - weights[0])
        ff_coeff = ff_coeff * weights[1] + ff_ns[2] * (1 - weights[1]) # add this back in for 2D lib

        jt_dcoeff = self.bezier.compute_dcoeff(jt_coeff)
        ff_dcoeff = self.bezier.compute_dcoeff(ff_coeff)

        period_ns = self.periods[neighbors]
        period = period_ns[0] * weights[0] + period_ns[1] * (1 - weights[0])
        period = period * weights[1] + period_ns[2] * (1 - weights[1])

        return jt_coeff, ff_coeff, jt_dcoeff, ff_dcoeff, period[0]

    def interpolate_gait(self, end_coeff_jt, end_coeff_ff, end_period, s, t):
        """Interpolates a gait between the current gait and the input gait.
        This method should be iteratively run to ensure smoothness.
        """
        z_transform = self.bezier.get_z_transform(s)

        split_coeff_jt = self.bezier.split(self.curr_jt, s, z_transform)
        split_coeff_ff = self.bezier.split(self.curr_ff, s, z_transform)

        end_remaining_period = self.curr_period - (self.curr_period * s)
        sprime = 1 - end_remaining_period / end_period
        # sprime = self.gnp.clip(sprime, 0.01, 0.99)

        z_transform = self.bezier.get_z_transform(sprime)
        split_end_coeff_jt = self.bezier.split(end_coeff_jt, sprime, z_transform)
        split_end_coeff_ff = self.bezier.split(end_coeff_ff, sprime, z_transform)


        interp_coeff_jt = self.bezier.interpolate(
            split_coeff_jt,
            split_end_coeff_jt,
            deg=3
        )
        interp_coeff_ff = self.bezier.interpolate(
            split_coeff_ff,
            split_end_coeff_ff,
            deg=3
        )
        # interp_period = self.curr_period - (t - self.t0)
        interp_period = end_remaining_period 
        # interp_coeff_jt, interp_coeff_ff = self.bezier.relabel(
        #     jt_coeff=interp_coeff_jt,
        #     ff_coeff=interp_coeff_ff,
        # )

        interp_jt_dcoeff = self.bezier.compute_dcoeff(interp_coeff_jt)
        interp_ff_dcoeff = self.bezier.compute_dcoeff(interp_coeff_ff)
        return (interp_coeff_jt, interp_jt_dcoeff, 
                interp_coeff_ff, interp_ff_dcoeff, 
                interp_period)

    def _set_gait(self, vdes, t):
        cond = ((vdes[1] < 0.0) & (self.swing_leg == Leg.LEFT)) | ((vdes[1] > 0.0) & (self.swing_leg == Leg.RIGHT))
        ret = jax.lax.cond(
            cond,
            lambda _: self,
            lambda _: self._set_gait(vdes, t),
            None
        )
        # if cond:
        #     ret = self
        # else:
        #     ret = self._set_gait(vdes, t)
        return ret

    def set_gait(self, vdes, t):
        """Defines an interpolated gait between the current gait, and the input
        gait. This method should be iteratively run to ensure smoothness.

        rho_desired: (np.ndarray) gait to interpolate to, shape includes relabeling (2, nstates, ndegree + 1)

        Returns rho_predicted: (np.ndarray) interpolated gait, shape includes relabeling (2, nstates, ndegree + 1)
        """
        neighbors, weights = self.find_nearest(vdes)
        # print(neighbors, vdes, weights)
        jt_coeff, ff_coeff, jt_dcoeff, ff_dcoeff, step_period = self.combine_gaits(
            neighbors,
            weights
        )
        jt_coeff, jt_dcoeff, ff_coeff, ff_dcoeff, period = self.interpolate_gait(
            jt_coeff, ff_coeff, step_period, self.get_phase(t), t
        )

        # Update the current gait
        return self.set_new_coeffs(
            jt_coeff=jt_coeff.copy(),
            jt_dcoeff=jt_dcoeff.copy(),
            ff_coeff=ff_coeff.copy(),
            ff_dcoeff=ff_dcoeff.copy(),
            period=self.gnp.copy(period),
            t0=self.gnp.copy(t),
            t0_step=self.t0_step,
            vdes=self.gnp.copy(vdes),
            step_period=self.gnp.copy(step_period),
            swing_leg=self.swing_leg
        )

    def reset_gait(self, vdes, t, swing_leg):
        neighbors, weights = self.find_nearest(vdes)
        jt_coeff, ff_coeff, jt_dcoeff, ff_dcoeff, step_period = self.combine_gaits(
            neighbors,
            weights
        )

        # Update the current gait
        return self.set_new_coeffs(
            jt_coeff=jt_coeff.copy(),
            jt_dcoeff=jt_dcoeff.copy(),
            ff_coeff=ff_coeff.copy(),
            ff_dcoeff=ff_dcoeff.copy(),
            period=self.gnp.copy(step_period),
            t0=self.gnp.copy(t),
            t0_step=self.gnp.copy(t),
            vdes=self.gnp.copy(vdes),
            step_period=self.gnp.copy(step_period),
            swing_leg=swing_leg
        )

    def set_new_coeffs(self, jt_coeff, jt_dcoeff, ff_coeff, ff_dcoeff, period, t0, vdes, step_period, t0_step, swing_leg):
        return GaitLibrary(
            num_gaits    = self.gnp.copy(self.num_gaits),
            num_states   = self.gnp.copy(self.num_states),
            num_degree   = self.gnp.copy(self.num_degree),
            num_vx_gaits = self.gnp.copy(self.num_vx_gaits),
            bezier       = self.bezier,
            jt_coeffs    = self.gnp.copy(self.jt_coeffs),
            jt_dcoeffs   = self.gnp.copy(self.jt_dcoeffs),
            ff_coeffs    = self.gnp.copy(self.ff_coeffs),
            ff_dcoeffs   = self.gnp.copy(self.ff_dcoeffs),
            curr_jt      = self.gnp.copy(jt_coeff),
            curr_djt     = self.gnp.copy(jt_dcoeff),
            curr_ff      = self.gnp.copy(ff_coeff),
            curr_dff     = self.gnp.copy(ff_dcoeff),
            curr_period  = self.gnp.copy(period),
            step_period  = self.gnp.copy(step_period),
            curr_vdes    = self.gnp.copy(vdes),
            periods      = self.gnp.copy(self.periods),
            vel_xs       = self.gnp.copy(self.vel_xs),
            vel_ys       = self.gnp.copy(self.vel_ys),
            swing_leg    = self.gnp.copy(swing_leg),
            t0           = self.gnp.copy(t0),
            t0_step      = self.gnp.copy(t0_step),
            blend        = self.gnp.copy(self.blend),
            offset_pos   = self.gnp.copy(self.offset_pos),
            offset_vel   = self.gnp.copy(self.offset_pos),
            gnp          = self.gnp,
            side_offset  = self.gnp.copy(self.side_offset)
        )


    def get_phase(self, t: float):
        phase = (t - self.t0) / self.curr_period
        return phase

    def get_step_phase(self, t: float):
        phase = (t - self.t0_step) / self.step_period
        return phase

    def evaluate(self, s: float, leg: int):
        des_pos, des_vel = self.bezier.evaluate(
            s          = s,
            coeff      = self.curr_jt[leg],
            dcoeff     = self.curr_djt[leg],
            period     = self.curr_period
        )

        return self.gnp.hstack((des_pos, des_vel))

    def evaluate2(self, s: float, leg: int, coeff, dcoeff, period):
        des_pos, des_vel = self.bezier.evaluate(
            s          = s,
            coeff      = coeff[leg],
            dcoeff     = dcoeff[leg],
            period     = period
        )
        return self.gnp.hstack((des_pos, des_vel))

    def blend_gait(self, s, pos, vel):
        # Blending
        lambda_comb = self.gnp.clip(s / self.blend, 0, 1)
        des_pos_blend = (1-lambda_comb) * self.offset_pos + pos
        des_vel_blend = (1-lambda_comb) * self.offset_vel + vel
        return self.gnp.hstack((des_pos_blend, des_vel_blend))

    def __call__(self, s: int):
        state = self.evaluate(s, self.swing_leg)        
        return state

    def ff_evaluate(self, s: float):
        des_pos, des_vel = self.bezier.evaluate(
            s          = s,
            coeff      = self.curr_ff[self.swing_leg],
            dcoeff     = self.curr_dff[self.swing_leg],
            period     = self.curr_period
        )
        des_pos = self.bezier.to_quat(des_pos)
        # des_pos[1] -= self.side_offset[1]
        # des_pos[1] -= 0.22
        return self.gnp.hstack((des_pos, des_vel))


    def impact_reset(self, t: float, cond=jax.lax.cond):
        """Returns a new GaitLibrary object with the swing leg switched and
        blending applied
        """
        neighbors, weights = self.find_nearest(self.curr_vdes)
        jt_coeff, ff_coeff, jt_dcoeff, ff_dcoeff, period = self.combine_gaits(
            neighbors,
            weights
        )
        # print(period)
        new_swing_leg = cond(
            self.swing_leg == Leg.RIGHT,
            lambda _: Leg.LEFT,
            lambda _: Leg.RIGHT,
            None
        )


        new_t0 = self.gnp.copy(t)
        return GaitLibrary(
            num_gaits    = self.num_gaits,
            num_states   = self.num_states,
            num_degree   = self.num_degree,
            num_vx_gaits = self.num_vx_gaits,
            bezier       = self.bezier,
            jt_coeffs    = self.jt_coeffs,
            jt_dcoeffs   = self.jt_dcoeffs,
            ff_coeffs    = self.ff_coeffs,
            ff_dcoeffs   = self.ff_dcoeffs,
            curr_jt      = jt_coeff,
            curr_djt     = jt_dcoeff,
            curr_ff      = ff_coeff,
            curr_dff     = ff_dcoeff,
            curr_period  = period,
            step_period  = period,
            periods      = self.periods,
            curr_vdes    = self.curr_vdes,
            vel_xs       = self.vel_xs,
            vel_ys       = self.vel_ys,
            swing_leg    = new_swing_leg,
            t0           = new_t0 - 0.005,
            t0_step      = new_t0 - 0.005,
            blend        = self.blend,
            offset_pos   = self.offset_pos,
            offset_vel   = self.offset_vel,
            gnp          = self.gnp,
            side_offset  = self.side_offset
        )

    def tree_flatten(self):
        return (self.num_gaits,
                self.num_states,
                self.num_degree,
                self.num_vx_gaits,
                self.bezier,
                self.jt_coeffs,
                self.jt_dcoeffs,
                self.ff_coeffs,
                self.ff_dcoeffs,
                self.curr_jt,
                self.curr_djt,
                self.curr_ff,
                self.curr_dff,
                self.curr_period,
                self.step_period,
                self.curr_vdes,
                self.periods,
                self.vel_xs,
                self.vel_ys,
                self.swing_leg,
                self.t0,
                self.t0_step,
                self.blend,
                self.offset_pos,
                self.offset_vel), ()

    @classmethod
    def tree_unflatten(self, aux_data, children):
        return GaitLibrary(*children)

num_gaits instance-attribute

num_gaits: int

num_states instance-attribute

num_states: int

num_degree instance-attribute

num_degree: int

num_vx_gaits instance-attribute

num_vx_gaits: int

bezier instance-attribute

bezier: P1Bezier

jt_coeffs instance-attribute

jt_coeffs: ndarray | ndarray

jt_dcoeffs instance-attribute

jt_dcoeffs: ndarray | ndarray

ff_coeffs instance-attribute

ff_coeffs: ndarray | ndarray

ff_dcoeffs instance-attribute

ff_dcoeffs: ndarray | ndarray

curr_jt instance-attribute

curr_jt: ndarray | ndarray

curr_djt instance-attribute

curr_djt: ndarray | ndarray

curr_ff instance-attribute

curr_ff: ndarray | ndarray

curr_dff instance-attribute

curr_dff: ndarray | ndarray

curr_period instance-attribute

curr_period: float

step_period instance-attribute

step_period: float

curr_vdes instance-attribute

curr_vdes: ndarray | ndarray

periods instance-attribute

periods: ndarray | ndarray

vel_xs instance-attribute

vel_xs: ndarray | ndarray

vel_ys instance-attribute

vel_ys: ndarray | ndarray

swing_leg instance-attribute

swing_leg: int

t0 instance-attribute

t0: float

t0_step instance-attribute

t0_step: float

blend instance-attribute

blend: float

offset_pos instance-attribute

offset_pos: ndarray | ndarray

offset_vel instance-attribute

offset_vel: ndarray | ndarray

gnp class-attribute instance-attribute

gnp: object = field(default_factory=lambda: jnp)

side_offset class-attribute instance-attribute

side_offset: ndarray | ndarray = field(default_factory=lambda: jnp.zeros(6, dtype=jnp.float32))

from_directory classmethod

from_directory(path, v0, num_states, num_degree, gnp: object = field(default_factory=lambda: numpy), fact: callable = field(default_factory=lambda: factorial), swing_leg=LEFT, t0=0.0, blend=0.3, gait_type='P1')

Loads a gait library from a directory of yaml files. It should setup jt_coeffs and ff_coeffs to hold a list of coefficients for each gait in the directory.

Source code in src/moplayground/envs/locomotion/control/gait.py
@classmethod
def from_directory(
    cls, 
    path, 
    v0,
    num_states,
    num_degree,
    gnp: object = field(default_factory=lambda: jnp),
    fact: callable = field(default_factory=lambda: jax.scipy.special.factorial),
    swing_leg=Leg.LEFT, 
    t0=0.0, 
    blend=0.3,
    gait_type='P1'
):
    """Loads a gait library from a directory of yaml files. It should setup
    jt_coeffs and ff_coeffs to hold a list of coefficients for each gait in 
    the directory."""
    def open_yaml(file):
        with open(file, 'r') as f:
            contents = safe_load(f)
        return dict(contents)

    bez_files = glob(path + '/*.yaml')
    if bez_files == []:
        raise ValueError(f'No yaml files found in {path}. Please check the path.')

    def get_gait(x):
        gait = open_yaml(x)
        return [float(gait['vd_x']), float(gait['vd_y'])], gait

    vels = []
    for file in bez_files:
        vdes, gait = get_gait(file)
        vels.append(vdes)


    num_vx_gaits = len(np.unique(np.array(vels)[:,0]))

    # print(f'{num_vx_gaits} vx gaits found in {path}')

    bez_files = glob(path + '/*.yaml')
    def sort_key(x):
        x = Path(x).stem
        nums = x.split('_')
        return int(nums[1]) * num_vx_gaits + int(nums[2])

    bez_files.sort(key=sort_key)


    bezier = P1Bezier.setup(
        num_states = num_states,
        num_degree = num_degree,
        bnp        = gnp,
        fact       = fact
    )

    jt_coeffs = []
    jt_dcoeffs = []
    ff_coeffs = []
    ff_dcoeffs = []
    vel_xs = []
    vel_ys = []
    periods = []
    vel_lims = np.array([[np.inf, -np.inf], [np.inf, -np.inf]])
    for bez in bez_files:
        gait = open_yaml(bez)
        if gait_type == 'P1':
            # Reshape the bezier coefficients
            # contents['RightSS'] = contents
            jt_coeff = bezier.reshape_coeff(
                coeff=gait['RightSS']['coeff_jt'],
                num_states=num_states
            )
            ff_coeff = bezier.reshape_coeff(
                coeff=gait['RightSS']['coeff_b'],
                num_states=P1Bezier.FREE_STATES
            )
            num_degree = jt_coeff.shape[1] - 1

            # Compute relabeling...
            jt_coeff, ff_coeff = bezier.relabel(
                jt_coeff=jt_coeff,
                ff_coeff=ff_coeff
            )
            periods.append([gait['RightSS']['step_dur']])
        elif gait_type == 'P2':
            jt_coeff1 = bezier.reshape_coeff(
                coeff=gait['RightSS']['coeff_jt'],
                num_states=num_states
            )
            ff_coeff1 = bezier.reshape_coeff(
                coeff=gait['RightSS']['coeff_b'],
                num_states=P1Bezier.FREE_STATES
            )
            num_degree = jt_coeff1.shape[1] - 1

            # if contents['vd_y'] < 0:
            #     ff_coeff1[1, :] -= contents['LeftSS']['step_len'][1]

            # Reshape the bezier coefficients
            jt_coeff2 = bezier.reshape_coeff(
                coeff=gait['LeftSS']['coeff_jt'],
                num_states=num_states
            )
            ff_coeff2 = bezier.reshape_coeff(
                coeff=gait['LeftSS']['coeff_b'],
                num_states=P1Bezier.FREE_STATES
            )

            # if contents['vd_y'] < 0:
            #     ff_coeff2[1, :] -= contents['LeftSS']['step_len'][1]

            jt_coeff = gnp.array([jt_coeff1, jt_coeff2])
            ff_coeff = gnp.array([ff_coeff1, ff_coeff2])
            periods.append([gait['RightSS']['step_dur']])
        else:
            raise ValueError(f'Gait type {gait_type} not supported')

        # Compute derivatives...
        jt_dcoeff = bezier.compute_dcoeff(jt_coeff)
        ff_dcoeff = bezier.compute_dcoeff(ff_coeff)

        jt_coeffs.append(jt_coeff)
        jt_dcoeffs.append(jt_dcoeff)
        ff_coeffs.append(ff_coeff)
        ff_dcoeffs.append(ff_dcoeff)

        vel_lims[0, 0] = min(vel_lims[0, 0], gait['vd_x'])
        vel_lims[0, 1] = max(vel_lims[0, 1], gait['vd_x'])
        vel_lims[1, 0] = min(vel_lims[1, 0], gait['vd_y'])
        vel_lims[1, 1] = max(vel_lims[1, 1], gait['vd_y'])

    num_vy_gaits = len(bez_files) // num_vx_gaits
    vel_xs = np.linspace(*vel_lims[0, :], num=num_vx_gaits)
    vel_ys = np.linspace(*vel_lims[1, :], num=num_vy_gaits)
    # print(num_vx_gaits, num_vy_gaits)
    # quit()

    jt_coeffs  = gnp.array(jt_coeffs)
    jt_dcoeffs = gnp.array(jt_dcoeffs)
    ff_coeffs  = gnp.array(ff_coeffs)
    ff_dcoeffs = gnp.array(ff_dcoeffs)
    periods    = gnp.array(periods) 
    vel_xs     = gnp.array(vel_xs)
    vel_ys     = gnp.array(vel_ys)

    side_offset = np.zeros(6)

    # print("Variable Names and Shapes:")
    # print(f"jt_coeffs: {jt_coeffs.shape}")
    # print(f"jt_dcoeffs: {jt_dcoeffs.shape}")
    # print(f"ff_coeffs: {ff_coeffs.shape}")
    # print(f"ff_dcoeffs: {ff_dcoeffs.shape}")
    # print(f"periods: {periods.shape}")
    # print(f"vel_xs: {vel_xs.shape}")
    # print(f"vel_ys: {vel_ys.shape}")
    # quit()

    gaitlib = cls(
        num_gaits    = jt_coeffs.shape[0],
        num_states   = num_states,
        num_degree   = num_degree,
        num_vx_gaits = num_vx_gaits,
        bezier       = bezier,
        jt_coeffs    = jt_coeffs,
        jt_dcoeffs   = jt_dcoeffs,
        ff_coeffs    = ff_coeffs,
        ff_dcoeffs   = ff_dcoeffs,
        curr_jt      = jt_coeffs[0], # place holders...
        curr_djt     = jt_dcoeffs[0],
        curr_ff      = ff_coeffs[0],
        curr_dff     = ff_dcoeffs[0],
        curr_period  = periods[0, 0],
        step_period  = periods[0, 0],
        curr_vdes    = v0,
        periods      = periods,
        vel_xs       = vel_xs,
        vel_ys       = vel_ys,
        swing_leg    = swing_leg,
        t0           = 0.0,
        t0_step      = 0.0,
        blend        = blend,
        offset_pos   = gnp.zeros(num_states, dtype=gnp.float32),
        offset_vel   = gnp.zeros(num_states, dtype=gnp.float32),
        gnp          = gnp,
        side_offset  = side_offset,
    )

    neighbors, weights = gaitlib.find_nearest(v0)
    jt_coeff, ff_coeff, jt_dcoeff, ff_dcoeff, period = gaitlib.combine_gaits(
        neighbors,
        weights
    )
    return gaitlib.set_new_coeffs(
        jt_coeff=jt_coeff,
        jt_dcoeff=jt_dcoeff,
        ff_coeff=ff_coeff,
        ff_dcoeff=ff_dcoeff,
        period=period,
        step_period=period,
        t0=t0,
        t0_step=t0,
        vdes=v0,
        swing_leg=swing_leg
    )

get_1D_idx

get_1D_idx(vx_idx, vy_idx)
Source code in src/moplayground/envs/locomotion/control/gait.py
def get_1D_idx(self, vx_idx, vy_idx):
    num_vy_gaits = self.num_gaits // self.num_vx_gaits
    return vx_idx * num_vy_gaits + vy_idx

find_nearest

find_nearest(vdes)

Finds the nearest gaits in the gait library with respect to the desired velocity. The output will be FOUR gaits.

vdes: (np.ndarray) desired velocity (vx, vy)

(vx_gaits, vy_gaits)

Name Type Description
vx_gaits

(alpha1, alpha2, weight_alpha) vy_gaits: (beta1, beta2, weight_beta)

Source code in src/moplayground/envs/locomotion/control/gait.py
def find_nearest(self, vdes):
    """Finds the nearest gaits in the gait library with respect to the\
        desired velocity. The output will be FOUR gaits.

        vdes: (np.ndarray) desired velocity (vx, vy)

        Returns: (vx_gaits, vy_gaits)
            vx_gaits: (alpha1, alpha2, weight_alpha)
            vy_gaits: (beta1, beta2, weight_beta)
        """
    # print(f'vdes {vdes}')
    num_vy_gaits = self.num_gaits // self.num_vx_gaits
    x1_idx = self.gnp.searchsorted(self.vel_xs, vdes[0])
    x1_idx = self.gnp.clip(x1_idx, 0, self.num_vx_gaits - 1)
    x2_idx = self.gnp.clip(x1_idx - 1, 0, self.num_vx_gaits - 1)
    y1_idx = self.gnp.searchsorted(self.vel_ys, vdes[1])
    y1_idx = self.gnp.clip(y1_idx, 0, num_vy_gaits - 1)
    y2_idx = self.gnp.clip(y1_idx - 1, 0, num_vy_gaits - 1)
    # print(f"x1_idx: {x1_idx}, x2_idx: {x2_idx}, y1_idx: {y1_idx}, y2_idx: {y2_idx}")
    # print(f"num_gaits: {self.num_gaits}")
    # print()

    neighbor_idxs = self.gnp.array([
        self.get_1D_idx(x1_idx, y1_idx),
        self.get_1D_idx(x2_idx, y1_idx),
        self.get_1D_idx(x1_idx, y2_idx)
    ])
    # print(f"neighbor_idxs: {neighbor_idxs}")
    # print()

    neighbors = self.gnp.array([idx for idx in neighbor_idxs])

    vx1, vy1 = self.vel_xs[x1_idx], self.vel_ys[y1_idx]
    vx2, vy2 = self.vel_xs[x2_idx], self.vel_ys[y1_idx]
    vx3, vy3 = self.vel_xs[x1_idx], self.vel_ys[y2_idx]

    def solve_convex_comb(args):
        """Solves the convex combination of two points"""
        v1, v2, vd = args
        return (vd - v2) / (v1 - v2)

    w1_zero = self.gnp.array(self.gnp.abs(vx1 - vx2) < 1e-2).astype(self.gnp.int32)
    w1 = self.gnp.array([
        solve_convex_comb([vx1, vx2 + 1 * w1_zero, vdes[0]]),
        vx1,
    ])[w1_zero]

    w2_zero = self.gnp.array(self.gnp.abs(vy1 - vy3) < 1e-2).astype(self.gnp.int32)
    w2 = self.gnp.array([
        solve_convex_comb([vy1, vy3 + 1 * w2_zero, vdes[1]]) ,
        vy1,
    ])[w2_zero]

    # print('v', vdes, neighbor_idxs, np.array([w1, w2]), x1_idx * w1 + x2_idx * (1 - w1))

    return neighbors, self.gnp.array([w1, w2])

combine_gaits

combine_gaits(neighbors, weights)

Combines gaits.

Returns a single convex combination of the four gaits. Size will be (2, nstates, ndegree + 1) as it includes the relabeling.

Source code in src/moplayground/envs/locomotion/control/gait.py
def combine_gaits(
        self,
        neighbors,
        weights
):
    """Combines gaits.

    Returns a single convex combination of the four gaits. Size will be
    (2, nstates, ndegree + 1) as it includes the relabeling.
    """
    jt_ns = self.jt_coeffs[neighbors] # joint neighbors
    jt_coeff = jt_ns[0] * weights[0] + jt_ns[1] * (1 - weights[0])
    jt_coeff = jt_coeff * weights[1] + jt_ns[2] * (1 - weights[1]) # add this back in for 2D lib

    ff_ns = self.ff_coeffs[neighbors] # flying frame neighbors
    ff_coeff = ff_ns[0] * weights[0] + ff_ns[1] * (1 - weights[0])
    ff_coeff = ff_coeff * weights[1] + ff_ns[2] * (1 - weights[1]) # add this back in for 2D lib

    jt_dcoeff = self.bezier.compute_dcoeff(jt_coeff)
    ff_dcoeff = self.bezier.compute_dcoeff(ff_coeff)

    period_ns = self.periods[neighbors]
    period = period_ns[0] * weights[0] + period_ns[1] * (1 - weights[0])
    period = period * weights[1] + period_ns[2] * (1 - weights[1])

    return jt_coeff, ff_coeff, jt_dcoeff, ff_dcoeff, period[0]

interpolate_gait

interpolate_gait(end_coeff_jt, end_coeff_ff, end_period, s, t)

Interpolates a gait between the current gait and the input gait. This method should be iteratively run to ensure smoothness.

Source code in src/moplayground/envs/locomotion/control/gait.py
def interpolate_gait(self, end_coeff_jt, end_coeff_ff, end_period, s, t):
    """Interpolates a gait between the current gait and the input gait.
    This method should be iteratively run to ensure smoothness.
    """
    z_transform = self.bezier.get_z_transform(s)

    split_coeff_jt = self.bezier.split(self.curr_jt, s, z_transform)
    split_coeff_ff = self.bezier.split(self.curr_ff, s, z_transform)

    end_remaining_period = self.curr_period - (self.curr_period * s)
    sprime = 1 - end_remaining_period / end_period
    # sprime = self.gnp.clip(sprime, 0.01, 0.99)

    z_transform = self.bezier.get_z_transform(sprime)
    split_end_coeff_jt = self.bezier.split(end_coeff_jt, sprime, z_transform)
    split_end_coeff_ff = self.bezier.split(end_coeff_ff, sprime, z_transform)


    interp_coeff_jt = self.bezier.interpolate(
        split_coeff_jt,
        split_end_coeff_jt,
        deg=3
    )
    interp_coeff_ff = self.bezier.interpolate(
        split_coeff_ff,
        split_end_coeff_ff,
        deg=3
    )
    # interp_period = self.curr_period - (t - self.t0)
    interp_period = end_remaining_period 
    # interp_coeff_jt, interp_coeff_ff = self.bezier.relabel(
    #     jt_coeff=interp_coeff_jt,
    #     ff_coeff=interp_coeff_ff,
    # )

    interp_jt_dcoeff = self.bezier.compute_dcoeff(interp_coeff_jt)
    interp_ff_dcoeff = self.bezier.compute_dcoeff(interp_coeff_ff)
    return (interp_coeff_jt, interp_jt_dcoeff, 
            interp_coeff_ff, interp_ff_dcoeff, 
            interp_period)

set_gait

set_gait(vdes, t)

Defines an interpolated gait between the current gait, and the input gait. This method should be iteratively run to ensure smoothness.

rho_desired: (np.ndarray) gait to interpolate to, shape includes relabeling (2, nstates, ndegree + 1)

Returns rho_predicted: (np.ndarray) interpolated gait, shape includes relabeling (2, nstates, ndegree + 1)

Source code in src/moplayground/envs/locomotion/control/gait.py
def set_gait(self, vdes, t):
    """Defines an interpolated gait between the current gait, and the input
    gait. This method should be iteratively run to ensure smoothness.

    rho_desired: (np.ndarray) gait to interpolate to, shape includes relabeling (2, nstates, ndegree + 1)

    Returns rho_predicted: (np.ndarray) interpolated gait, shape includes relabeling (2, nstates, ndegree + 1)
    """
    neighbors, weights = self.find_nearest(vdes)
    # print(neighbors, vdes, weights)
    jt_coeff, ff_coeff, jt_dcoeff, ff_dcoeff, step_period = self.combine_gaits(
        neighbors,
        weights
    )
    jt_coeff, jt_dcoeff, ff_coeff, ff_dcoeff, period = self.interpolate_gait(
        jt_coeff, ff_coeff, step_period, self.get_phase(t), t
    )

    # Update the current gait
    return self.set_new_coeffs(
        jt_coeff=jt_coeff.copy(),
        jt_dcoeff=jt_dcoeff.copy(),
        ff_coeff=ff_coeff.copy(),
        ff_dcoeff=ff_dcoeff.copy(),
        period=self.gnp.copy(period),
        t0=self.gnp.copy(t),
        t0_step=self.t0_step,
        vdes=self.gnp.copy(vdes),
        step_period=self.gnp.copy(step_period),
        swing_leg=self.swing_leg
    )

reset_gait

reset_gait(vdes, t, swing_leg)
Source code in src/moplayground/envs/locomotion/control/gait.py
def reset_gait(self, vdes, t, swing_leg):
    neighbors, weights = self.find_nearest(vdes)
    jt_coeff, ff_coeff, jt_dcoeff, ff_dcoeff, step_period = self.combine_gaits(
        neighbors,
        weights
    )

    # Update the current gait
    return self.set_new_coeffs(
        jt_coeff=jt_coeff.copy(),
        jt_dcoeff=jt_dcoeff.copy(),
        ff_coeff=ff_coeff.copy(),
        ff_dcoeff=ff_dcoeff.copy(),
        period=self.gnp.copy(step_period),
        t0=self.gnp.copy(t),
        t0_step=self.gnp.copy(t),
        vdes=self.gnp.copy(vdes),
        step_period=self.gnp.copy(step_period),
        swing_leg=swing_leg
    )

set_new_coeffs

set_new_coeffs(jt_coeff, jt_dcoeff, ff_coeff, ff_dcoeff, period, t0, vdes, step_period, t0_step, swing_leg)
Source code in src/moplayground/envs/locomotion/control/gait.py
def set_new_coeffs(self, jt_coeff, jt_dcoeff, ff_coeff, ff_dcoeff, period, t0, vdes, step_period, t0_step, swing_leg):
    return GaitLibrary(
        num_gaits    = self.gnp.copy(self.num_gaits),
        num_states   = self.gnp.copy(self.num_states),
        num_degree   = self.gnp.copy(self.num_degree),
        num_vx_gaits = self.gnp.copy(self.num_vx_gaits),
        bezier       = self.bezier,
        jt_coeffs    = self.gnp.copy(self.jt_coeffs),
        jt_dcoeffs   = self.gnp.copy(self.jt_dcoeffs),
        ff_coeffs    = self.gnp.copy(self.ff_coeffs),
        ff_dcoeffs   = self.gnp.copy(self.ff_dcoeffs),
        curr_jt      = self.gnp.copy(jt_coeff),
        curr_djt     = self.gnp.copy(jt_dcoeff),
        curr_ff      = self.gnp.copy(ff_coeff),
        curr_dff     = self.gnp.copy(ff_dcoeff),
        curr_period  = self.gnp.copy(period),
        step_period  = self.gnp.copy(step_period),
        curr_vdes    = self.gnp.copy(vdes),
        periods      = self.gnp.copy(self.periods),
        vel_xs       = self.gnp.copy(self.vel_xs),
        vel_ys       = self.gnp.copy(self.vel_ys),
        swing_leg    = self.gnp.copy(swing_leg),
        t0           = self.gnp.copy(t0),
        t0_step      = self.gnp.copy(t0_step),
        blend        = self.gnp.copy(self.blend),
        offset_pos   = self.gnp.copy(self.offset_pos),
        offset_vel   = self.gnp.copy(self.offset_pos),
        gnp          = self.gnp,
        side_offset  = self.gnp.copy(self.side_offset)
    )

get_phase

get_phase(t: float)
Source code in src/moplayground/envs/locomotion/control/gait.py
def get_phase(self, t: float):
    phase = (t - self.t0) / self.curr_period
    return phase

get_step_phase

get_step_phase(t: float)
Source code in src/moplayground/envs/locomotion/control/gait.py
def get_step_phase(self, t: float):
    phase = (t - self.t0_step) / self.step_period
    return phase

evaluate

evaluate(s: float, leg: int)
Source code in src/moplayground/envs/locomotion/control/gait.py
def evaluate(self, s: float, leg: int):
    des_pos, des_vel = self.bezier.evaluate(
        s          = s,
        coeff      = self.curr_jt[leg],
        dcoeff     = self.curr_djt[leg],
        period     = self.curr_period
    )

    return self.gnp.hstack((des_pos, des_vel))

evaluate2

evaluate2(s: float, leg: int, coeff, dcoeff, period)
Source code in src/moplayground/envs/locomotion/control/gait.py
def evaluate2(self, s: float, leg: int, coeff, dcoeff, period):
    des_pos, des_vel = self.bezier.evaluate(
        s          = s,
        coeff      = coeff[leg],
        dcoeff     = dcoeff[leg],
        period     = period
    )
    return self.gnp.hstack((des_pos, des_vel))

blend_gait

blend_gait(s, pos, vel)
Source code in src/moplayground/envs/locomotion/control/gait.py
def blend_gait(self, s, pos, vel):
    # Blending
    lambda_comb = self.gnp.clip(s / self.blend, 0, 1)
    des_pos_blend = (1-lambda_comb) * self.offset_pos + pos
    des_vel_blend = (1-lambda_comb) * self.offset_vel + vel
    return self.gnp.hstack((des_pos_blend, des_vel_blend))

ff_evaluate

ff_evaluate(s: float)
Source code in src/moplayground/envs/locomotion/control/gait.py
def ff_evaluate(self, s: float):
    des_pos, des_vel = self.bezier.evaluate(
        s          = s,
        coeff      = self.curr_ff[self.swing_leg],
        dcoeff     = self.curr_dff[self.swing_leg],
        period     = self.curr_period
    )
    des_pos = self.bezier.to_quat(des_pos)
    # des_pos[1] -= self.side_offset[1]
    # des_pos[1] -= 0.22
    return self.gnp.hstack((des_pos, des_vel))

impact_reset

impact_reset(t: float, cond=cond)

Returns a new GaitLibrary object with the swing leg switched and blending applied

Source code in src/moplayground/envs/locomotion/control/gait.py
def impact_reset(self, t: float, cond=jax.lax.cond):
    """Returns a new GaitLibrary object with the swing leg switched and
    blending applied
    """
    neighbors, weights = self.find_nearest(self.curr_vdes)
    jt_coeff, ff_coeff, jt_dcoeff, ff_dcoeff, period = self.combine_gaits(
        neighbors,
        weights
    )
    # print(period)
    new_swing_leg = cond(
        self.swing_leg == Leg.RIGHT,
        lambda _: Leg.LEFT,
        lambda _: Leg.RIGHT,
        None
    )


    new_t0 = self.gnp.copy(t)
    return GaitLibrary(
        num_gaits    = self.num_gaits,
        num_states   = self.num_states,
        num_degree   = self.num_degree,
        num_vx_gaits = self.num_vx_gaits,
        bezier       = self.bezier,
        jt_coeffs    = self.jt_coeffs,
        jt_dcoeffs   = self.jt_dcoeffs,
        ff_coeffs    = self.ff_coeffs,
        ff_dcoeffs   = self.ff_dcoeffs,
        curr_jt      = jt_coeff,
        curr_djt     = jt_dcoeff,
        curr_ff      = ff_coeff,
        curr_dff     = ff_dcoeff,
        curr_period  = period,
        step_period  = period,
        periods      = self.periods,
        curr_vdes    = self.curr_vdes,
        vel_xs       = self.vel_xs,
        vel_ys       = self.vel_ys,
        swing_leg    = new_swing_leg,
        t0           = new_t0 - 0.005,
        t0_step      = new_t0 - 0.005,
        blend        = self.blend,
        offset_pos   = self.offset_pos,
        offset_vel   = self.offset_vel,
        gnp          = self.gnp,
        side_offset  = self.side_offset
    )

tree_flatten

tree_flatten()
Source code in src/moplayground/envs/locomotion/control/gait.py
def tree_flatten(self):
    return (self.num_gaits,
            self.num_states,
            self.num_degree,
            self.num_vx_gaits,
            self.bezier,
            self.jt_coeffs,
            self.jt_dcoeffs,
            self.ff_coeffs,
            self.ff_dcoeffs,
            self.curr_jt,
            self.curr_djt,
            self.curr_ff,
            self.curr_dff,
            self.curr_period,
            self.step_period,
            self.curr_vdes,
            self.periods,
            self.vel_xs,
            self.vel_ys,
            self.swing_leg,
            self.t0,
            self.t0_step,
            self.blend,
            self.offset_pos,
            self.offset_vel), ()

tree_unflatten classmethod

tree_unflatten(aux_data, children)
Source code in src/moplayground/envs/locomotion/control/gait.py
@classmethod
def tree_unflatten(self, aux_data, children):
    return GaitLibrary(*children)

get_states

get_states(gaitlib, low=0, high=1)
Source code in src/moplayground/envs/locomotion/control/gait.py
def get_states(gaitlib, low=0, high=1):
    states = []
    phase = np.linspace(low, high, 100)
    for s in phase:
        state = gaitlib.evaluate(s, Leg.RIGHT)
        states.append(state)
    return np.array(states)

moplayground.envs.locomotion.control.bezier

Classes:

Name Description
Leg
P1Bezier

Functions:

Name Description
bezier_basis_matrix

Returns the Bézier basis matrix M for degree n such that:

Attributes:

Name Type Description
bezier
BEZ1
BEZ2
bez1_contents
bez2_contents
bez1_coeff
bez1_dcoeff
bez1_period
bez2_coeff
bez2_dcoeff
bez2_period
N
SPLIT1
SPLIT2
t
bez1_pos
bez2_pos
bez1_vel
bez2_vel
start
K
axs

bezier module-attribute

bezier = P1Bezier.setup(num_states=12, num_degree=7, bnp=np, fact=factorial)

BEZ1 module-attribute

BEZ1 = 'control/gaits/2D_library_v4/v_7_2.yaml'

BEZ2 module-attribute

BEZ2 = 'control/gaits/2D_library_v4/v_7_4.yaml'

bez1_contents module-attribute

bez1_contents = safe_load(f)

bez2_contents module-attribute

bez2_contents = safe_load(f)

bez1_coeff module-attribute

bez1_coeff = bezier.reshape_coeff(bezier.bnp.array(bez1_contents['RightSS']['coeff_b']), 6)

bez1_dcoeff module-attribute

bez1_dcoeff = bezier.compute_dcoeff(bez1_coeff)

bez1_period module-attribute

bez1_period = bez1_contents['RightSS']['step_dur']

bez2_coeff module-attribute

bez2_coeff = bezier.reshape_coeff(bezier.bnp.array(bez2_contents['LeftSS']['coeff_b']), 6)

bez2_dcoeff module-attribute

bez2_dcoeff = bezier.compute_dcoeff(bez2_coeff)

bez2_period module-attribute

bez2_period = bez2_contents['RightSS']['step_dur']

N module-attribute

N = 1000

SPLIT1 module-attribute

SPLIT1 = 0.5

SPLIT2 module-attribute

SPLIT2 = 0.5

t module-attribute

t = np.linspace(0, 1, N)

bez1_pos module-attribute

bez1_pos = []

bez2_pos module-attribute

bez2_pos = []

bez1_vel module-attribute

bez1_vel = []

bez2_vel module-attribute

bez2_vel = []

start module-attribute

start = time.time()

K module-attribute

K = 4

axs module-attribute

axs = axs.flatten()

Leg

Bases: IntEnum

Attributes:

Name Type Description
LEFT
RIGHT
Source code in src/moplayground/envs/locomotion/control/bezier.py
class Leg(IntEnum):
    LEFT = 0
    RIGHT = 1

LEFT class-attribute instance-attribute

LEFT = 0

RIGHT class-attribute instance-attribute

RIGHT = 1

P1Bezier dataclass

Methods:

Name Description
setup
reshape_coeff

Reshapes the coefficients to be of the correct size

relabel

Relabels the bezier polynomial according to the class strategy and

get_dcoeff_transform
compute_dcoeff

Computes the derivative coefficients for the bezier polynomial and

get_binomial_coeffs

Returns the binomial coefficients for a given n

get_z_transform
evaluate

Evaluates the bezier polynomial described by coeffs for all states at

split

Returns a 'split' Bezier coefficients at z, where z in [0, 1] is the

interpolate

Returns Bezier coefficients that start at start_coeff and end at

to_quat

Converts a flying frame position from RPY to quaternion for mujoco

tree_flatten
tree_unflatten

Attributes:

Name Type Description
num_states int
num_degree int
COMBINATION ndarray | ndarray
COMBO_MAT ndarray | ndarray
COMBO_MAT_INV ndarray | ndarray
DCOMBO_MAT ndarray | ndarray
DCOEFF_T ndarray | ndarray
POWER ndarray | ndarray
bnp object
fact callable
FREE_STATES int
Source code in src/moplayground/envs/locomotion/control/bezier.py
@jax.tree_util.register_static
@dataclass(frozen=True)
class P1Bezier:
    num_states:     int
    num_degree:     int
    COMBINATION:    jnp.ndarray | np.ndarray
    COMBO_MAT:      jnp.ndarray | np.ndarray
    COMBO_MAT_INV:  jnp.ndarray | np.ndarray
    DCOMBO_MAT:     jnp.ndarray | np.ndarray
    DCOEFF_T:       jnp.ndarray | np.ndarray
    POWER:          jnp.ndarray | np.ndarray    
    bnp:            object = field(default_factory=lambda: jnp)
    fact:           callable = field(default_factory=lambda: jax.scipy.special.factorial)
    FREE_STATES:    int = 6

    @classmethod 
    def setup(
        cls,
        num_states: int,
        num_degree: int,
        bnp,
        fact
    ):
        DCOEFF_T = cls.get_dcoeff_transform(num_degree, bnp)
        POWER = bnp.arange(num_degree + 1)
        M     = bnp.array(bezier_basis_matrix(num_degree))
        DM    = bnp.array(bezier_basis_matrix(num_degree - 1))
        COMBINATION = np.zeros((num_degree + 1, num_degree + 1))
        for n in range(num_degree + 1):
            for r in range(num_degree + 1):
                if r > n:
                    continue
                COMBINATION[n, r] = comb(n, r)

        return cls(
            num_states    = num_states,
            num_degree    = num_degree,
            bnp           = bnp,
            fact          = fact,
            COMBINATION   = bnp.array(COMBINATION),
            COMBO_MAT     = M,
            COMBO_MAT_INV = bnp.linalg.inv(M),
            DCOMBO_MAT    = DM,
            DCOEFF_T      = DCOEFF_T,
            POWER         = POWER
        )

    def reshape_coeff(self, coeff, num_states):
        """Reshapes the coefficients to be of the correct size"""
        return np.array(
            coeff
        ).reshape(-1, num_states).T

    def relabel(self, jt_coeff, ff_coeff):
        """Relabels the bezier polynomial according to the class strategy and 
        returns the corresponding ctrl_points and dcoeff"""

        jt_coeff_rlbl = self.bnp.vstack([
            jt_coeff[6:, :] * self.bnp.array([-1, -1, 1, 1, 1, -1]).reshape((-1, 1)),
            jt_coeff[:6, :] * self.bnp.array([-1, -1, 1, 1, 1, -1]).reshape((-1, 1))
        ])
        ff_coeff_rlbl = self.bnp.vstack([
            ff_coeff * self.bnp.array([1, -1, 1, -1, 1, -1]).reshape((-1, 1))
        ])
        jt_coeff = self.bnp.array([
            self.bnp.copy(jt_coeff), jt_coeff_rlbl
        ])
        ff_coeff = self.bnp.array([
            self.bnp.copy(ff_coeff), ff_coeff_rlbl
        ])
        return jt_coeff, ff_coeff

    @classmethod
    def get_dcoeff_transform(cls, num_degree, bnp):
        M = num_degree
        dcoeff_transform = np.zeros((M, M+1))

        for i in range(M):
            dcoeff_transform[i, i] = -(M - i) * comb(M,i) / comb(M-1,i)
            dcoeff_transform[i,i+1] = (i+1) * comb(M,i+1) / comb(M-1,i)
        dcoeff_transform[M-1, M] = M * comb(M, M)
        return dcoeff_transform

    def compute_dcoeff(self, coeff):
        """Computes the derivative coefficients for the bezier polynomial and
        returns the corresponding dcoeff for jt and ff in a tuple"""
        dcoeff = self.bnp.array([
            coeff[0] @ self.DCOEFF_T.T,
            coeff[1] @ self.DCOEFF_T.T
        ])
        return dcoeff

    def get_binomial_coeffs(self, n, z):
        """Returns the binomial coefficients for a given n"""
        # assert(z != 0)
        # assert(z != 1)
        # z = np.clip(z, 0.01, 0.99)
        coeff_part = self.bnp.array(
            self.COMBINATION[n, :] * self.bnp.power(z, n - self.POWER) * self.bnp.power(1 - z, self.POWER)
        )
        return coeff_part

    def get_z_transform(self, z):
        z_transform = self.bnp.vstack([
            self.get_binomial_coeffs(n, z) for n in range(self.num_degree + 1)
        ])

        return z_transform.T


    def evaluate(self, s, coeff, dcoeff, period):
        """Evaluates the bezier polynomial described by coeffs for all states at
        parameter s. s is clipped to [0,1] and is ideally monotonic."""
        s = self.bnp.clip(s, 0, 1)
        ts = self.bnp.power(s, self.POWER).reshape(1, -1)
        pos = ts @ self.COMBO_MAT @ coeff.T
        pos = pos[0]

        vel = ts[:, :-1] @ self.DCOMBO_MAT @ dcoeff.T
        vel = 1 / period * vel[0]

        return pos, vel

    def split(self, coeffs, z, z_transform):
        """Returns a 'split' Bezier coefficients at z, where z in [0, 1] is the
        point in the Bezier phase you wish to split at."""
        Z = z_transform
        M = self.COMBO_MAT
        new_coeffs = self.COMBO_MAT_INV @ Z @ M @ coeffs.transpose(0, 2, 1)
        return new_coeffs.transpose(0, 2, 1)

    def interpolate(self, start_coeffs, end_coeffs, deg=3):
        """Returns Bezier coefficients that start at start_coeff and end at
        end_coeff."""
        # print(start_coeffs.shape)
        # print(start_coeffs[0, 0, :])
        # print('---')
        # print(end_coeffs[0, 0, :])
        new_jt_coeffs = self.bnp.concatenate([
            start_coeffs[:, :, :deg],
            0.5 * (start_coeffs[:, :, deg:-deg] + end_coeffs[:, :, deg:-deg]),
            end_coeffs[:, :, -deg:]
        ], axis=2)
        # print(new_jt_coeffs[0, 0, :])
        # quit()
        return new_jt_coeffs

    def to_quat(self, ff_pos):
        """Converts a flying frame position from RPY to quaternion for mujoco
        """
        ff_pos = self.bnp.hstack([ff_pos[:3], euler2quat(self.bnp, ff_pos[3:])])
        return ff_pos

    def tree_flatten(self):
        return (self.num_states, 
                self.num_degree, 
                self.COMBO_MAT, 
                self.DCOMBO_MAT, 
                self.DCOEFF_T, 
                self.POWER), None

    @classmethod
    def tree_unflatten(cls, aux_data, children):
        return cls(*children)

num_states instance-attribute

num_states: int

num_degree instance-attribute

num_degree: int

COMBINATION instance-attribute

COMBINATION: ndarray | ndarray

COMBO_MAT instance-attribute

COMBO_MAT: ndarray | ndarray

COMBO_MAT_INV instance-attribute

COMBO_MAT_INV: ndarray | ndarray

DCOMBO_MAT instance-attribute

DCOMBO_MAT: ndarray | ndarray

DCOEFF_T instance-attribute

DCOEFF_T: ndarray | ndarray

POWER instance-attribute

POWER: ndarray | ndarray

bnp class-attribute instance-attribute

bnp: object = field(default_factory=lambda: jnp)

fact class-attribute instance-attribute

fact: callable = field(default_factory=lambda: jax.scipy.special.factorial)

FREE_STATES class-attribute instance-attribute

FREE_STATES: int = 6

setup classmethod

setup(num_states: int, num_degree: int, bnp, fact)
Source code in src/moplayground/envs/locomotion/control/bezier.py
@classmethod 
def setup(
    cls,
    num_states: int,
    num_degree: int,
    bnp,
    fact
):
    DCOEFF_T = cls.get_dcoeff_transform(num_degree, bnp)
    POWER = bnp.arange(num_degree + 1)
    M     = bnp.array(bezier_basis_matrix(num_degree))
    DM    = bnp.array(bezier_basis_matrix(num_degree - 1))
    COMBINATION = np.zeros((num_degree + 1, num_degree + 1))
    for n in range(num_degree + 1):
        for r in range(num_degree + 1):
            if r > n:
                continue
            COMBINATION[n, r] = comb(n, r)

    return cls(
        num_states    = num_states,
        num_degree    = num_degree,
        bnp           = bnp,
        fact          = fact,
        COMBINATION   = bnp.array(COMBINATION),
        COMBO_MAT     = M,
        COMBO_MAT_INV = bnp.linalg.inv(M),
        DCOMBO_MAT    = DM,
        DCOEFF_T      = DCOEFF_T,
        POWER         = POWER
    )

reshape_coeff

reshape_coeff(coeff, num_states)

Reshapes the coefficients to be of the correct size

Source code in src/moplayground/envs/locomotion/control/bezier.py
def reshape_coeff(self, coeff, num_states):
    """Reshapes the coefficients to be of the correct size"""
    return np.array(
        coeff
    ).reshape(-1, num_states).T

relabel

relabel(jt_coeff, ff_coeff)

Relabels the bezier polynomial according to the class strategy and returns the corresponding ctrl_points and dcoeff

Source code in src/moplayground/envs/locomotion/control/bezier.py
def relabel(self, jt_coeff, ff_coeff):
    """Relabels the bezier polynomial according to the class strategy and 
    returns the corresponding ctrl_points and dcoeff"""

    jt_coeff_rlbl = self.bnp.vstack([
        jt_coeff[6:, :] * self.bnp.array([-1, -1, 1, 1, 1, -1]).reshape((-1, 1)),
        jt_coeff[:6, :] * self.bnp.array([-1, -1, 1, 1, 1, -1]).reshape((-1, 1))
    ])
    ff_coeff_rlbl = self.bnp.vstack([
        ff_coeff * self.bnp.array([1, -1, 1, -1, 1, -1]).reshape((-1, 1))
    ])
    jt_coeff = self.bnp.array([
        self.bnp.copy(jt_coeff), jt_coeff_rlbl
    ])
    ff_coeff = self.bnp.array([
        self.bnp.copy(ff_coeff), ff_coeff_rlbl
    ])
    return jt_coeff, ff_coeff

get_dcoeff_transform classmethod

get_dcoeff_transform(num_degree, bnp)
Source code in src/moplayground/envs/locomotion/control/bezier.py
@classmethod
def get_dcoeff_transform(cls, num_degree, bnp):
    M = num_degree
    dcoeff_transform = np.zeros((M, M+1))

    for i in range(M):
        dcoeff_transform[i, i] = -(M - i) * comb(M,i) / comb(M-1,i)
        dcoeff_transform[i,i+1] = (i+1) * comb(M,i+1) / comb(M-1,i)
    dcoeff_transform[M-1, M] = M * comb(M, M)
    return dcoeff_transform

compute_dcoeff

compute_dcoeff(coeff)

Computes the derivative coefficients for the bezier polynomial and returns the corresponding dcoeff for jt and ff in a tuple

Source code in src/moplayground/envs/locomotion/control/bezier.py
def compute_dcoeff(self, coeff):
    """Computes the derivative coefficients for the bezier polynomial and
    returns the corresponding dcoeff for jt and ff in a tuple"""
    dcoeff = self.bnp.array([
        coeff[0] @ self.DCOEFF_T.T,
        coeff[1] @ self.DCOEFF_T.T
    ])
    return dcoeff

get_binomial_coeffs

get_binomial_coeffs(n, z)

Returns the binomial coefficients for a given n

Source code in src/moplayground/envs/locomotion/control/bezier.py
def get_binomial_coeffs(self, n, z):
    """Returns the binomial coefficients for a given n"""
    # assert(z != 0)
    # assert(z != 1)
    # z = np.clip(z, 0.01, 0.99)
    coeff_part = self.bnp.array(
        self.COMBINATION[n, :] * self.bnp.power(z, n - self.POWER) * self.bnp.power(1 - z, self.POWER)
    )
    return coeff_part

get_z_transform

get_z_transform(z)
Source code in src/moplayground/envs/locomotion/control/bezier.py
def get_z_transform(self, z):
    z_transform = self.bnp.vstack([
        self.get_binomial_coeffs(n, z) for n in range(self.num_degree + 1)
    ])

    return z_transform.T

evaluate

evaluate(s, coeff, dcoeff, period)

Evaluates the bezier polynomial described by coeffs for all states at parameter s. s is clipped to [0,1] and is ideally monotonic.

Source code in src/moplayground/envs/locomotion/control/bezier.py
def evaluate(self, s, coeff, dcoeff, period):
    """Evaluates the bezier polynomial described by coeffs for all states at
    parameter s. s is clipped to [0,1] and is ideally monotonic."""
    s = self.bnp.clip(s, 0, 1)
    ts = self.bnp.power(s, self.POWER).reshape(1, -1)
    pos = ts @ self.COMBO_MAT @ coeff.T
    pos = pos[0]

    vel = ts[:, :-1] @ self.DCOMBO_MAT @ dcoeff.T
    vel = 1 / period * vel[0]

    return pos, vel

split

split(coeffs, z, z_transform)

Returns a 'split' Bezier coefficients at z, where z in [0, 1] is the point in the Bezier phase you wish to split at.

Source code in src/moplayground/envs/locomotion/control/bezier.py
def split(self, coeffs, z, z_transform):
    """Returns a 'split' Bezier coefficients at z, where z in [0, 1] is the
    point in the Bezier phase you wish to split at."""
    Z = z_transform
    M = self.COMBO_MAT
    new_coeffs = self.COMBO_MAT_INV @ Z @ M @ coeffs.transpose(0, 2, 1)
    return new_coeffs.transpose(0, 2, 1)

interpolate

interpolate(start_coeffs, end_coeffs, deg=3)

Returns Bezier coefficients that start at start_coeff and end at end_coeff.

Source code in src/moplayground/envs/locomotion/control/bezier.py
def interpolate(self, start_coeffs, end_coeffs, deg=3):
    """Returns Bezier coefficients that start at start_coeff and end at
    end_coeff."""
    # print(start_coeffs.shape)
    # print(start_coeffs[0, 0, :])
    # print('---')
    # print(end_coeffs[0, 0, :])
    new_jt_coeffs = self.bnp.concatenate([
        start_coeffs[:, :, :deg],
        0.5 * (start_coeffs[:, :, deg:-deg] + end_coeffs[:, :, deg:-deg]),
        end_coeffs[:, :, -deg:]
    ], axis=2)
    # print(new_jt_coeffs[0, 0, :])
    # quit()
    return new_jt_coeffs

to_quat

to_quat(ff_pos)

Converts a flying frame position from RPY to quaternion for mujoco

Source code in src/moplayground/envs/locomotion/control/bezier.py
def to_quat(self, ff_pos):
    """Converts a flying frame position from RPY to quaternion for mujoco
    """
    ff_pos = self.bnp.hstack([ff_pos[:3], euler2quat(self.bnp, ff_pos[3:])])
    return ff_pos

tree_flatten

tree_flatten()
Source code in src/moplayground/envs/locomotion/control/bezier.py
def tree_flatten(self):
    return (self.num_states, 
            self.num_degree, 
            self.COMBO_MAT, 
            self.DCOMBO_MAT, 
            self.DCOEFF_T, 
            self.POWER), None

tree_unflatten classmethod

tree_unflatten(aux_data, children)
Source code in src/moplayground/envs/locomotion/control/bezier.py
@classmethod
def tree_unflatten(cls, aux_data, children):
    return cls(*children)

bezier_basis_matrix

bezier_basis_matrix(n)
Returns the Bézier basis matrix M for degree n such that

B(t) = [t^n, t^{n-1}, ..., 1] @ M @ [b_0, ..., b_n]^T

Source code in src/moplayground/envs/locomotion/control/bezier.py
def bezier_basis_matrix(n):
    """
    Returns the Bézier basis matrix M for degree n such that:
        B(t) = [t^n, t^{n-1}, ..., 1] @ M @ [b_0, ..., b_n]^T
    """
    M = np.zeros((n + 1, n + 1))
    for i in range(n + 1):
        for j in range(i + 1):
            coeff = ((-1) ** (i - j)) * comb(n, i) * comb(i, j)
            M[j, i] += coeff
    return M.T