|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +# Copyright 2023 The OpenRL Authors. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +"""""" |
| 18 | + |
| 19 | +from typing import Any, Dict, Optional |
| 20 | + |
| 21 | +import gymnasium as gym |
| 22 | +from gymnasium import spaces |
| 23 | +from gymnasium.envs.registration import EnvSpec, register |
| 24 | +from gymnasium.utils import seeding |
| 25 | +from train_and_test import train_and_test |
| 26 | + |
| 27 | +from openrl.envs.common import make |
| 28 | + |
| 29 | + |
| 30 | +class IdentityEnv(gym.Env): |
| 31 | + spec = EnvSpec("IdentityEnv") |
| 32 | + |
| 33 | + def __init__(self, **kwargs): |
| 34 | + self.dim = 2 |
| 35 | + self.observation_space = spaces.Discrete(1) |
| 36 | + self.action_space = spaces.Discrete(self.dim) |
| 37 | + self.ep_length = 5 |
| 38 | + self.current_step = 0 |
| 39 | + |
| 40 | + def reset( |
| 41 | + self, |
| 42 | + *, |
| 43 | + seed: Optional[int] = None, |
| 44 | + options: Optional[Dict[str, Any]] = None, |
| 45 | + ): |
| 46 | + if seed is not None: |
| 47 | + self.seed(seed) |
| 48 | + self.current_step = 0 |
| 49 | + self.generate_state() |
| 50 | + return self.state, {} |
| 51 | + |
| 52 | + def step(self, action): |
| 53 | + reward = 1 |
| 54 | + self.generate_state() |
| 55 | + self.current_step += 1 |
| 56 | + done = self.current_step >= self.ep_length |
| 57 | + return self.state, reward, done, {} |
| 58 | + |
| 59 | + def generate_state(self) -> None: |
| 60 | + self.state = [self._np_random.integers(0, self.dim)] |
| 61 | + |
| 62 | + def render(self, mode: str = "human") -> None: |
| 63 | + pass |
| 64 | + |
| 65 | + def seed(self, seed: Optional[int] = None) -> None: |
| 66 | + if seed is not None: |
| 67 | + self._np_random, seed = seeding.np_random(seed) |
| 68 | + |
| 69 | + def close(self): |
| 70 | + pass |
| 71 | + |
| 72 | + |
| 73 | +register( |
| 74 | + id="Custom_Env/IdentityEnv", |
| 75 | + entry_point="gymnasium_env:IdentityEnv", |
| 76 | +) |
| 77 | + |
| 78 | +env = make("Custom_Env/IdentityEnv", env_num=10) |
| 79 | + |
| 80 | +train_and_test(env) |
0 commit comments