mirror of
https://github.com/saymrwulf/stable-baselines3.git
synced 2026-06-26 03:01:19 +00:00
* Fix failing set_env test * Fix test failiing due to deprectation of env.seed * Adjust mean reward threshold in failing test * Fix her test failing due to rng * Change seed and revert reward threshold to 90 * Pin gym version * Make VecEnv compatible with gym seeding change * Revert change to VecEnv reset signature * Change subprocenv seed cmd to call reset instead * Fix type check * Add backward compat * Add `compat_gym_seed` helper * Add goal env checks in env_checker * Add docs on HER requirements for envs * Capture user warning in test with inverted box space * Update ale-py version * Fix randint * Allow noop_max to be zero * Update changelog * Update docker image * Update doc conda env and dockerfile * Custom envs should not have any warnings * Fix test for numpy >= 1.21 * Add check for vectorized compute reward * Bump to gym 0.24 * Fix gym default step docstring * Test downgrading gym * Revert "Test downgrading gym" This reverts commit 0072b77156c006ada8a1d6e26ce347ed85a83eeb. * Fix protobuf error * Fix in dependencies * Fix protobuf dep * Use newest version of cartpole * Update gym * Fix warning * Loosen required scipy version * Scipy no longer needed * Try gym 0.25 * Silence warnings from gym * Filter warnings during tests * Update doc * Update requirements * Add gym 26 compat in vec env * Fixes in envs and tests for gym 0.26+ * Enforce gym 0.26 api * format * Fix formatting * Fix dependencies * Fix syntax * Cleanup doc and warnings * Faster tests * Higher budget for HER perf test (revert prev change) * Fixes and update doc * Fix doc build * Fix breaking change * Fixes for rendering * Rename variables in monitor * update render method for gym 0.26 API backwards compatible (mode argument is allowed) while using the gym 0.26 API (render mode is determined at environment creation) * update tests and docs to new gym render API * undo removal of render modes metatadata check * set rgb_array as default render mode for gym.make * undo changes & raise warning if not 'rgb_array' * Fix type check * Remove recursion and fix type checking * Remove hacks for protobuf and gym 0.24 * Fix type annotations * reuse existing render_mode attribute * return tiled images for 'human' render mode * Allow to use opencv for human render, fix typos * Add warning when using non-zero start with Discrete (fixes #1197) * Fix type checking * Bug fixes and handle more cases * Throw proper warnings * Update test * Fix new metadata name * Ignore numpy warnings * Fixes in vec recorder * Global ignore * Filter local warning too * Monkey patch not needed for gym 26 * Add doc of VecEnv vs Gym API * Add render test * Fix return type * Update VecEnv vs Gym API doc * Fix for custom render mode * Fix return type * Fix type checking * check test env test_buffer * skip render check * check env test_dict_env * test_env test_gae * check envs in remaining tests * Update tests * Add warning for Discrete action space with non-zero (#1295) * Fix atari annotation * ignore get_action_meanings [attr-defined] * Fix mypy issues * Add patch for gym/gymnasium transition * Switch to gymnasium * Rely on signature instead of version * More patches * Type ignore because of https://github.com/Farama-Foundation/Gymnasium/pull/39 * Fix doc build * Fix pytype errors * Fix atari requirement * Update env checker due to change in dtype for Discrete * Fix type hint * Convert spaces for saved models * Ignore pytype * Remove gitlab CI * Disable pytype for convert space * Fix undefined info * Fix undefined info * Upgrade shimmy * Fix wrappers type annotation (need PR from Gymnasium) * Fix gymnasium dependency * Fix dependency declaration * Cap pygame version for python 3.7 * Point to master branch (v0.28.0) * Fix: use main not master branch * Rename done to terminated * Fix pygame dependency for python 3.7 * Rename gym to gymnasium * Update Gymnasium * Fix test * Fix tests * Forks don't have access to private variables * Fix linter warnings * Update read the doc env * Fix env checker for GoalEnv * Fix import * Update env checker (more info) and fix dtype * Use micromamab for Docker * Update dependencies * Clarify VecEnv doc * Fix Gymnasium version * Copy file only after mamba install * [ci skip] Update docker doc * Polish code * Reformat * Remove deprecated features * Ignore warning * Update doc * Update examples and changelog * Fix type annotation bundle (SAC, TD3, A2C, PPO, base class) (#1436) * Fix SAC type hints, improve DQN ones * Fix A2C and TD3 type hints * Fix PPO type hints * Fix on-policy type hints * Fix base class type annotation, do not use defaults * Update version * Disable mypy for python 3.7 * Rename Gym26StepReturn * Update continuous critic type annotation * Fix pytype complain --------- Co-authored-by: Carlos Luis <carlos.luisgonc@gmail.com> Co-authored-by: Quentin Gallouédec <45557362+qgallouedec@users.noreply.github.com> Co-authored-by: Thomas Lips <37955681+tlpss@users.noreply.github.com> Co-authored-by: tlips <thomas.lips@ugent.be> Co-authored-by: tlpss <thomas17.lips@gmail.com> Co-authored-by: Quentin GALLOUÉDEC <gallouedec.quentin@gmail.com>
185 lines
6.3 KiB
Python
185 lines
6.3 KiB
Python
from typing import Dict, Optional, Tuple, Union
|
|
|
|
import gymnasium as gym
|
|
import numpy as np
|
|
from gymnasium import spaces
|
|
|
|
from stable_baselines3.common.type_aliases import GymStepReturn
|
|
|
|
|
|
class SimpleMultiObsEnv(gym.Env):
|
|
"""
|
|
Base class for GridWorld-based MultiObs Environments 4x4 grid world.
|
|
|
|
.. code-block:: text
|
|
|
|
____________
|
|
| 0 1 2 3|
|
|
| 4|¯5¯¯6¯| 7|
|
|
| 8|_9_10_|11|
|
|
|12 13 14 15|
|
|
¯¯¯¯¯¯¯¯¯¯¯¯¯¯
|
|
|
|
start is 0
|
|
states 5, 6, 9, and 10 are blocked
|
|
goal is 15
|
|
actions are = [left, down, right, up]
|
|
|
|
simple linear state env of 15 states but encoded with a vector and an image observation:
|
|
each column is represented by a random vector and each row is
|
|
represented by a random image, both sampled once at creation time.
|
|
|
|
:param num_col: Number of columns in the grid
|
|
:param num_row: Number of rows in the grid
|
|
:param random_start: If true, agent starts in random position
|
|
:param channel_last: If true, the image will be channel last, else it will be channel first
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
num_col: int = 4,
|
|
num_row: int = 4,
|
|
random_start: bool = True,
|
|
discrete_actions: bool = True,
|
|
channel_last: bool = True,
|
|
):
|
|
super().__init__()
|
|
|
|
self.vector_size = 5
|
|
if channel_last:
|
|
self.img_size = [64, 64, 1]
|
|
else:
|
|
self.img_size = [1, 64, 64]
|
|
|
|
self.random_start = random_start
|
|
self.discrete_actions = discrete_actions
|
|
if discrete_actions:
|
|
self.action_space = spaces.Discrete(4)
|
|
else:
|
|
self.action_space = spaces.Box(0, 1, (4,))
|
|
|
|
self.observation_space = spaces.Dict(
|
|
spaces={
|
|
"vec": spaces.Box(0, 1, (self.vector_size,), dtype=np.float64),
|
|
"img": spaces.Box(0, 255, self.img_size, dtype=np.uint8),
|
|
}
|
|
)
|
|
self.count = 0
|
|
# Timeout
|
|
self.max_count = 100
|
|
self.log = ""
|
|
self.state = 0
|
|
self.action2str = ["left", "down", "right", "up"]
|
|
self.init_possible_transitions()
|
|
|
|
self.num_col = num_col
|
|
self.state_mapping = []
|
|
self.init_state_mapping(num_col, num_row)
|
|
|
|
self.max_state = len(self.state_mapping) - 1
|
|
|
|
def init_state_mapping(self, num_col: int, num_row: int) -> None:
|
|
"""
|
|
Initializes the state_mapping array which holds the observation values for each state
|
|
|
|
:param num_col: Number of columns.
|
|
:param num_row: Number of rows.
|
|
"""
|
|
# Each column is represented by a random vector
|
|
col_vecs = np.random.random((num_col, self.vector_size))
|
|
# Each row is represented by a random image
|
|
row_imgs = np.random.randint(0, 255, (num_row, 64, 64), dtype=np.uint8)
|
|
|
|
for i in range(num_col):
|
|
for j in range(num_row):
|
|
self.state_mapping.append({"vec": col_vecs[i], "img": row_imgs[j].reshape(self.img_size)})
|
|
|
|
def get_state_mapping(self) -> Dict[str, np.ndarray]:
|
|
"""
|
|
Uses the state to get the observation mapping.
|
|
|
|
:return: observation dict {'vec': ..., 'img': ...}
|
|
"""
|
|
return self.state_mapping[self.state]
|
|
|
|
def init_possible_transitions(self) -> None:
|
|
"""
|
|
Initializes the transitions of the environment
|
|
The environment exploits the cardinal directions of the grid by noting that
|
|
they correspond to simple addition and subtraction from the cell id within the grid
|
|
|
|
- up => means moving up a row => means subtracting the length of a column
|
|
- down => means moving down a row => means adding the length of a column
|
|
- left => means moving left by one => means subtracting 1
|
|
- right => means moving right by one => means adding 1
|
|
|
|
Thus one only needs to specify in which states each action is possible
|
|
in order to define the transitions of the environment
|
|
"""
|
|
self.left_possible = [1, 2, 3, 13, 14, 15]
|
|
self.down_possible = [0, 4, 8, 3, 7, 11]
|
|
self.right_possible = [0, 1, 2, 12, 13, 14]
|
|
self.up_possible = [4, 8, 12, 7, 11, 15]
|
|
|
|
def step(self, action: Union[float, np.ndarray]) -> GymStepReturn:
|
|
"""
|
|
Run one timestep of the environment's dynamics. When end of
|
|
episode is reached, you are responsible for calling `reset()`
|
|
to reset this environment's state.
|
|
Accepts an action and returns a tuple (observation, reward, done, info).
|
|
|
|
:param action:
|
|
:return: tuple (observation, reward, done, info).
|
|
"""
|
|
if not self.discrete_actions:
|
|
action = np.argmax(action)
|
|
else:
|
|
action = int(action)
|
|
|
|
self.count += 1
|
|
|
|
prev_state = self.state
|
|
|
|
reward = -0.1
|
|
# define state transition
|
|
if self.state in self.left_possible and action == 0: # left
|
|
self.state -= 1
|
|
elif self.state in self.down_possible and action == 1: # down
|
|
self.state += self.num_col
|
|
elif self.state in self.right_possible and action == 2: # right
|
|
self.state += 1
|
|
elif self.state in self.up_possible and action == 3: # up
|
|
self.state -= self.num_col
|
|
|
|
got_to_end = self.state == self.max_state
|
|
reward = 1 if got_to_end else reward
|
|
truncated = self.count > self.max_count
|
|
terminated = got_to_end
|
|
|
|
self.log = f"Went {self.action2str[action]} in state {prev_state}, got to state {self.state}"
|
|
|
|
return self.get_state_mapping(), reward, terminated, truncated, {"got_to_end": got_to_end}
|
|
|
|
def render(self, mode: str = "human") -> None:
|
|
"""
|
|
Prints the log of the environment.
|
|
|
|
:param mode:
|
|
"""
|
|
print(self.log)
|
|
|
|
def reset(self, *, seed: Optional[int] = None, options: Optional[Dict] = None) -> Tuple[Dict[str, np.ndarray], Dict]:
|
|
"""
|
|
Resets the environment state and step count and returns reset observation.
|
|
|
|
:param seed:
|
|
:return: observation dict {'vec': ..., 'img': ...}
|
|
"""
|
|
if seed is not None:
|
|
super().reset(seed=seed)
|
|
self.count = 0
|
|
if not self.random_start:
|
|
self.state = 0
|
|
else:
|
|
self.state = np.random.randint(0, self.max_state)
|
|
return self.state_mapping[self.state], {}
|