Skip to content

Core Wrappers

API Reference

masa.common.wrappers.TimeLimit

TimeLimit(env: Env, max_episode_steps: int)

Bases: ConstraintPersistentWrapper

Episode time-limit wrapper compatible with constraint persistence.

This is a minimal time-limit wrapper similar in spirit to Gymnasium's time-limit handling. It sets the truncated flag to True once the number of elapsed steps reaches _max_episode_steps.

Parameters:

Name Type Description Default
env Env

Base environment to wrap.

required
max_episode_steps int

Maximum number of steps per episode.

required

Attributes:

Name Type Description
_max_episode_steps

Configured time limit in steps.

_elapsed_steps

Counter of steps elapsed in the current episode.

Source code in masa/common/wrappers.py
def __init__(self, env: gym.Env, max_episode_steps: int):
    super().__init__(env)

    self._max_episode_steps = max_episode_steps
    self._elapsed_steps = None

_max_episode_steps instance-attribute

_max_episode_steps = max_episode_steps

_elapsed_steps instance-attribute

_elapsed_steps = None

step

step(action)

Step the environment and apply time-limit truncation.

Parameters:

Name Type Description Default
action

Action forwarded to the underlying environment.

required

Returns:

Type Description

A 5-tuple (observation, reward, terminated, truncated, info). If

the time limit is reached, truncated is forced to True.

Source code in masa/common/wrappers.py
def step(self, action):
    """
    Step the environment and apply time-limit truncation.

    Args:
        action: Action forwarded to the underlying environment.

    Returns:
        A 5-tuple ``(observation, reward, terminated, truncated, info)``. If
        the time limit is reached, ``truncated`` is forced to ``True``.
    """
    observation, reward, terminated, truncated, info = self.env.step(action)
    self._elapsed_steps += 1

    if self._elapsed_steps >= self._max_episode_steps:
        truncated = True

    return observation, reward, terminated, truncated, info

reset

reset(**kwargs)

Reset the environment and the elapsed step counter.

Parameters:

Name Type Description Default
**kwargs

Forwarded to the underlying environment's reset.

{}

Returns:

Type Description

The underlying environment's reset return value.

Source code in masa/common/wrappers.py
def reset(self, **kwargs):
    """
    Reset the environment and the elapsed step counter.

    Args:
        **kwargs: Forwarded to the underlying environment's ``reset``.

    Returns:
        The underlying environment's ``reset`` return value.
    """
    self._elapsed_steps = 0
    return self.env.reset(**kwargs)

masa.common.wrappers.ConstraintMonitor

ConstraintMonitor(env: Env)

Bases: ConstraintPersistentWrapper

Monitor that injects constraint metadata and metrics into info.

This wrapper requires the wrapped environment to be a masa.common.constraints.base.BaseConstraintEnv, so it can query:

  • masa.common.constraints.base.BaseConstraintEnv.constraint_type
  • masa.common.constraints.base.BaseConstraintEnv.constraint_step_metrics
  • masa.common.constraints.base.BaseConstraintEnv.constraint_episode_metrics

On each step, the wrapper writes:

  • info["constraint"]["type"]: the constraint type string
  • info["constraint"]["step"]: step-level metrics (cheap, safe)
  • info["constraint"]["episode"]: episode-level metrics (when available)

Parameters:

Name Type Description Default
env Env

Constraint environment to wrap.

required

Raises:

Type Description
TypeError

If env is not a BaseConstraintEnv.

Source code in masa/common/wrappers.py
def __init__(self, env: gym.Env):
    super().__init__(env)
    if not isinstance(env, BaseConstraintEnv):  # type: ignore[arg-type]
        raise TypeError(
            "ConstraintMonitor requires env to implement BaseConstraintEnv "
            "(wrap your env with CumulativeCostEnv/StepWiseProbabilisticEnv/...)."
        )
    self._constraint_env: BaseConstraintEnv = env  # type: ignore[assignment]

_constraint_env instance-attribute

_constraint_env: BaseConstraintEnv = env

reset

reset(*, seed: int | None = None, options: Dict[str, Any] | None = None)

Reset and populate initial constraint metadata in info.

Parameters:

Name Type Description Default
seed int | None

Random seed forwarded to the underlying environment.

None
options Dict[str, Any] | None

Reset options forwarded to the underlying environment.

None

Returns:

Type Description

A tuple (obs, info). The returned info includes

info["constraint"]["type"] and info["constraint"]["step"].

Source code in masa/common/wrappers.py
def reset(self, *, seed: int | None = None, options: Dict[str, Any] | None = None):
    """
    Reset and populate initial constraint metadata in ``info``.

    Args:
        seed: Random seed forwarded to the underlying environment.
        options: Reset options forwarded to the underlying environment.

    Returns:
        A tuple ``(obs, info)``. The returned ``info`` includes
        ``info["constraint"]["type"]`` and ``info["constraint"]["step"]``.
    """
    obs, info = self.env.reset(seed=seed, options=options)
    info = dict(info or {})
    info.setdefault("constraint", {})["type"] = self._constraint_env.constraint_type
    info["constraint"]["step"] = self._step_metrics()
    return obs, info

step

step(action)

Step and populate constraint metrics in info.

Parameters:

Name Type Description Default
action

Action forwarded to the underlying environment.

required

Returns:

Type Description

A 5-tuple (observation, reward, terminated, truncated, info).

The returned info includes constraint fields described in the

class docstring.

Source code in masa/common/wrappers.py
def step(self, action):
    """
    Step and populate constraint metrics in ``info``.

    Args:
        action: Action forwarded to the underlying environment.

    Returns:
        A 5-tuple ``(observation, reward, terminated, truncated, info)``.
        The returned ``info`` includes ``constraint`` fields described in the
        class docstring.
    """
    observation, reward, terminated, truncated, info = self.env.step(action)
    info = dict(info or {})
    info.setdefault("constraint", {})["type"] = self._constraint_env.constraint_type
    info["constraint"]["step"] = self._step_metrics()
    if terminated or truncated:
        info["constraint"]["episode"] = self._episode_metrics()
    return observation, reward, terminated, truncated, info

_step_metrics

_step_metrics() -> Dict[str, float]

Read step-level constraint metrics.

Returns:

Type Description
Dict[str, float]

A dictionary of step-level metrics. If the underlying constraint raises

Dict[str, float]

an exception, returns an empty dictionary.

Source code in masa/common/wrappers.py
def _step_metrics(self) -> Dict[str, float]:
    """
    Read step-level constraint metrics.

    Returns:
        A dictionary of step-level metrics. If the underlying constraint raises
        an exception, returns an empty dictionary.
    """
    try:
        return dict(self._constraint_env.constraint_step_metrics())
    except Exception:
        return {}

_episode_metrics

_episode_metrics() -> Dict[str, float]

Read episode-level constraint metrics.

Returns:

Type Description
Dict[str, float]

A dictionary of episode-level metrics. If the underlying constraint raises

Dict[str, float]

an exception, returns an empty dictionary.

Source code in masa/common/wrappers.py
def _episode_metrics(self) -> Dict[str, float]:
    """
    Read episode-level constraint metrics.

    Returns:
        A dictionary of episode-level metrics. If the underlying constraint raises
        an exception, returns an empty dictionary.
    """
    try:
        return dict(self._constraint_env.constraint_episode_metrics())
    except Exception:
        return {}

masa.common.wrappers.RewardMonitor

RewardMonitor(env: Env)

Bases: ConstraintPersistentWrapper

Monitor that injects reward/length metrics into info.

This wrapper tracks:

  • per-step immediate reward in info["metrics"]["step"]["reward"]
  • episode return/length at episode end in info["metrics"]["episode"]

Parameters:

Name Type Description Default
env Env

Base environment to wrap.

required

Attributes:

Name Type Description
total_reward

Accumulated episode reward since last reset.

total_steps

Number of steps taken since last reset.

Source code in masa/common/wrappers.py
def __init__(self, env: gym.Env):
    super().__init__(env)

reset

reset(*, seed: int | None = None, options: Dict[str, Any] | None = None)

Reset reward counters and forward reset to the underlying env.

Parameters:

Name Type Description Default
seed int | None

Random seed forwarded to the underlying environment.

None
options Dict[str, Any] | None

Reset options forwarded to the underlying environment.

None

Returns:

Type Description

A tuple (obs, info) from the underlying environment.

Source code in masa/common/wrappers.py
def reset(self, *, seed: int | None = None, options: Dict[str, Any] | None = None):
    """
    Reset reward counters and forward ``reset`` to the underlying env.

    Args:
        seed: Random seed forwarded to the underlying environment.
        options: Reset options forwarded to the underlying environment.

    Returns:
        A tuple ``(obs, info)`` from the underlying environment.
    """
    obs, info = self.env.reset(seed=seed, options=options)
    self.total_reward = 0.0
    self.total_steps = 0
    return obs, info

step

step(action)

Step the environment and update reward metrics.

Parameters:

Name Type Description Default
action

Action forwarded to the underlying environment.

required

Returns:

Type Description

A 5-tuple (observation, reward, terminated, truncated, info).

On episode end, info["metrics"]["episode"] is populated with

episode return and length.

Source code in masa/common/wrappers.py
def step(self, action):
    """
    Step the environment and update reward metrics.

    Args:
        action: Action forwarded to the underlying environment.

    Returns:
        A 5-tuple ``(observation, reward, terminated, truncated, info)``.
        On episode end, ``info["metrics"]["episode"]`` is populated with
        episode return and length.
    """
    observation, reward, terminated, truncated, info = self.env.step(action)
    self.total_reward += reward
    self.total_steps += 1
    info = dict(info or {})
    info.setdefault("metrics", {})
    info["metrics"]["step"] = {"reward": reward}
    if terminated or truncated:
        info["metrics"]["episode"] = self._episode_metrics()
    return observation, reward, terminated, truncated, info

_episode_metrics

_episode_metrics()

Compute episode-level reward metrics.

Returns:

Type Description

A dictionary with keys:

  • "ep_reward": total episode reward.
  • "ep_length": episode length in steps.
Source code in masa/common/wrappers.py
def _episode_metrics(self):
    """
    Compute episode-level reward metrics.

    Returns:
        A dictionary with keys:

        * ``"ep_reward"``: total episode reward.
        * ``"ep_length"``: episode length in steps.
    """
    return {"ep_reward": self.total_reward, "ep_length": self.total_steps}