2022-05-13 13:58:19 +01:00
|
|
|
"""Wrapper for transforming the reward."""
|
|
|
|
from typing import Callable
|
|
|
|
|
2022-09-08 10:10:07 +01:00
|
|
|
import gymnasium
|
|
|
|
from gymnasium import RewardWrapper
|
2019-08-10 00:19:52 +02:00
|
|
|
|
|
|
|
|
|
|
|
class TransformReward(RewardWrapper):
|
2022-05-13 13:58:19 +01:00
|
|
|
"""Transform the reward via an arbitrary function.
|
2019-08-10 00:19:52 +02:00
|
|
|
|
2022-05-13 13:58:19 +01:00
|
|
|
Warning:
|
|
|
|
If the base environment specifies a reward range which is not invariant under :attr:`f`, the :attr:`reward_range` of the wrapped environment will be incorrect.
|
2019-08-10 00:19:52 +02:00
|
|
|
|
2022-05-13 13:58:19 +01:00
|
|
|
Example:
|
2022-09-08 10:10:07 +01:00
|
|
|
>>> import gymnasium
|
|
|
|
>>> env = gymnasium.make('CartPole-v1')
|
2019-08-10 00:19:52 +02:00
|
|
|
>>> env = TransformReward(env, lambda r: 0.01*r)
|
|
|
|
>>> env.reset()
|
2022-07-10 02:18:06 +05:30
|
|
|
>>> observation, reward, terminated, truncated, info = env.step(env.action_space.sample())
|
2019-08-10 00:19:52 +02:00
|
|
|
>>> reward
|
|
|
|
0.01
|
|
|
|
"""
|
2021-07-29 02:26:34 +02:00
|
|
|
|
2022-09-08 10:10:07 +01:00
|
|
|
def __init__(self, env: gymnasium.Env, f: Callable[[float], float]):
|
2022-05-13 13:58:19 +01:00
|
|
|
"""Initialize the :class:`TransformReward` wrapper with an environment and reward transform function :param:`f`.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
env: The environment to apply the wrapper
|
|
|
|
f: A function that transforms the reward
|
|
|
|
"""
|
2022-08-30 19:41:59 +05:30
|
|
|
super().__init__(env)
|
2019-08-10 00:19:52 +02:00
|
|
|
assert callable(f)
|
|
|
|
self.f = f
|
|
|
|
|
|
|
|
def reward(self, reward):
|
2022-05-13 13:58:19 +01:00
|
|
|
"""Transforms the reward using callable :attr:`f`.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
reward: The reward to transform
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The transformed reward
|
|
|
|
"""
|
2019-08-10 00:19:52 +02:00
|
|
|
return self.f(reward)
|