2022-12-10 22:04:14 +00:00
|
|
|
"""``StickyAction`` wrapper - There is a probability that the action is taken again."""
|
2022-12-05 19:14:56 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2022-12-10 22:04:14 +00:00
|
|
|
from typing import Any
|
2022-12-05 19:14:56 +00:00
|
|
|
|
|
|
|
import gymnasium as gym
|
2023-02-22 13:58:29 +00:00
|
|
|
from gymnasium.core import ActionWrapper, ActType, ObsType
|
2022-12-05 19:14:56 +00:00
|
|
|
from gymnasium.error import InvalidProbability
|
|
|
|
|
|
|
|
|
2023-02-22 13:58:29 +00:00
|
|
|
class StickyActionV0(ActionWrapper[ObsType, ActType, ActType]):
|
2022-12-05 19:14:56 +00:00
|
|
|
"""Wrapper which adds a probability of repeating the previous action.
|
|
|
|
|
|
|
|
This wrapper follows the implementation proposed by `Machado et al., 2018 <https://arxiv.org/pdf/1709.06009.pdf>`_
|
|
|
|
in Section 5.2 on page 12.
|
|
|
|
"""
|
|
|
|
|
2023-02-22 13:58:29 +00:00
|
|
|
def __init__(
|
|
|
|
self, env: gym.Env[ObsType, ActType], repeat_action_probability: float
|
|
|
|
):
|
2022-12-05 19:14:56 +00:00
|
|
|
"""Initialize StickyAction wrapper.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
env (Env): the wrapped environment
|
|
|
|
repeat_action_probability (int | float): a probability of repeating the old action.
|
|
|
|
"""
|
|
|
|
if not 0 <= repeat_action_probability < 1:
|
|
|
|
raise InvalidProbability(
|
|
|
|
f"repeat_action_probability should be in the interval [0,1). Received {repeat_action_probability}"
|
|
|
|
)
|
|
|
|
|
|
|
|
super().__init__(env)
|
|
|
|
self.repeat_action_probability = repeat_action_probability
|
2023-02-22 13:58:29 +00:00
|
|
|
self.last_action: ActType | None = None
|
2022-12-05 19:14:56 +00:00
|
|
|
|
|
|
|
def reset(
|
|
|
|
self, *, seed: int | None = None, options: dict[str, Any] | None = None
|
2023-02-22 13:58:29 +00:00
|
|
|
) -> tuple[ObsType, dict[str, Any]]:
|
2022-12-05 19:14:56 +00:00
|
|
|
"""Reset the environment."""
|
|
|
|
self.last_action = None
|
|
|
|
|
|
|
|
return super().reset(seed=seed, options=options)
|
|
|
|
|
2023-02-22 13:58:29 +00:00
|
|
|
def action(self, action: ActType) -> ActType:
|
2022-12-05 19:14:56 +00:00
|
|
|
"""Execute the action."""
|
|
|
|
if (
|
|
|
|
self.last_action is not None
|
|
|
|
and self.np_random.uniform() < self.repeat_action_probability
|
|
|
|
):
|
|
|
|
action = self.last_action
|
|
|
|
|
|
|
|
self.last_action = action
|
|
|
|
return action
|