|
| 1 | +"""The Acrobot environment from gymnasium: |
| 2 | +for more information check: https://gymnasium.farama.org/environments/classic_control/acrobot/ |
| 3 | +
|
| 4 | +""" |
| 5 | +import gymnasium as gym |
| 6 | +from typing import Any |
| 7 | +from loguru import logger |
| 8 | +from fastapi import APIRouter, Body, status |
| 9 | +from fastapi.responses import JSONResponse |
| 10 | +from fastapi import HTTPException |
| 11 | +from time_step_response import TimeStep, TimeStepType |
| 12 | + |
| 13 | +lunar_lander_discrete_router = APIRouter(prefix="/gymnasium/lunar-lander-discrete-env", |
| 14 | + tags=["Lunar Lander Discrete API"]) |
| 15 | + |
| 16 | +ENV_NAME = "LunarLander" |
| 17 | + |
| 18 | +# the environments to create |
| 19 | +envs = { |
| 20 | + 0: None |
| 21 | +} |
| 22 | + |
| 23 | +# actions that the environment accepts |
| 24 | +ACTIONS_SPACE = {0: "do nothing", |
| 25 | + 1: "fire left orientation engine", |
| 26 | + 2: "fire main engine", |
| 27 | + 3: "fire right orientation engine" |
| 28 | + } |
| 29 | + |
| 30 | + |
| 31 | +@lunar_lander_discrete_router.get("/action-space") |
| 32 | +async def get_action_space() -> JSONResponse: |
| 33 | + return JSONResponse(status_code=status.HTTP_200_OK, |
| 34 | + content={"action_space": ACTIONS_SPACE}) |
| 35 | + |
| 36 | + |
| 37 | +@lunar_lander_discrete_router.get("/is-alive") |
| 38 | +async def get_is_alive(cidx: int) -> JSONResponse: |
| 39 | + global envs |
| 40 | + if cidx in envs: |
| 41 | + env = envs[cidx] |
| 42 | + |
| 43 | + if env is None: |
| 44 | + return JSONResponse(status_code=status.HTTP_200_OK, |
| 45 | + content={"result": False}) |
| 46 | + else: |
| 47 | + return JSONResponse(status_code=status.HTTP_200_OK, |
| 48 | + content={"result": True}) |
| 49 | + else: |
| 50 | + return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST, |
| 51 | + content={"message": f"Environment {ENV_NAME} and index {cidx} has not been created"}) |
| 52 | + |
| 53 | + |
| 54 | +@lunar_lander_discrete_router.post("/close") |
| 55 | +async def close(cidx: int) -> JSONResponse: |
| 56 | + global envs |
| 57 | + if cidx in envs: |
| 58 | + env = envs[cidx] |
| 59 | + if env is not None: |
| 60 | + envs[cidx].close() |
| 61 | + envs[cidx] = None |
| 62 | + logger.info(f'Closed environment {ENV_NAME} and index {cidx}') |
| 63 | + return JSONResponse(status_code=status.HTTP_202_ACCEPTED, |
| 64 | + content={"message": f"Environment {ENV_NAME} and index {cidx} is closed"}) |
| 65 | + |
| 66 | + return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST, |
| 67 | + content={"message": f"Environment {ENV_NAME} and index {cidx} has not been created"}) |
| 68 | + |
| 69 | + |
| 70 | +@lunar_lander_discrete_router.post("/make") |
| 71 | +async def make(version: str = Body(default="v3"), cidx: int = Body(...), |
| 72 | + options: dict[str, Any] = Body(default={'gravity': -10.0, 'enable_wind': False, |
| 73 | + 'wind_power': 15.0, 'turbulence_power': 1.5})) -> JSONResponse: |
| 74 | + if version == 'v1' or version == 'v2': |
| 75 | + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, |
| 76 | + detail='Environment version v1 for `LunarLander` ' |
| 77 | + 'is deprecated. Please use `LunarLander-v3` instead.') |
| 78 | + |
| 79 | + global envs |
| 80 | + env_type = f"{ENV_NAME}-{version}" |
| 81 | + if cidx in envs: |
| 82 | + env = envs[cidx] |
| 83 | + |
| 84 | + if env is not None: |
| 85 | + envs[cidx].close() |
| 86 | + |
| 87 | + try: |
| 88 | + env = gym.make(env_type, continuous=False, **options) |
| 89 | + envs[cidx] = env |
| 90 | + except Exception as e: |
| 91 | + logger.error('An exception was raised') |
| 92 | + logger.opt(exception=e).info("Logging exception traceback") |
| 93 | + raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, |
| 94 | + detail=str(e)) |
| 95 | + else: |
| 96 | + try: |
| 97 | + env = gym.make(env_type) |
| 98 | + envs[cidx] = env |
| 99 | + except Exception as e: |
| 100 | + logger.error('An exception was raised') |
| 101 | + logger.opt(exception=e).info("Logging exception traceback") |
| 102 | + raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, |
| 103 | + detail=str(e)) |
| 104 | + |
| 105 | + logger.info(f'Created environment {ENV_NAME} and index {cidx}') |
| 106 | + return JSONResponse(status_code=status.HTTP_201_CREATED, |
| 107 | + content={"result": True}) |
| 108 | + |
| 109 | + |
| 110 | +@lunar_lander_discrete_router.post("/reset") |
| 111 | +async def reset(seed: int = Body(default=42), cidx: int = Body(...), |
| 112 | + options: dict[str, Any] = Body(default={})) -> JSONResponse: |
| 113 | + """Reset the environment |
| 114 | +
|
| 115 | + :return: |
| 116 | + """ |
| 117 | + |
| 118 | + global envs |
| 119 | + if cidx in envs: |
| 120 | + env = envs[cidx] |
| 121 | + |
| 122 | + if env is not None: |
| 123 | + |
| 124 | + if len(options) != 0: |
| 125 | + observation, info = env.reset(seed=seed, options=options) |
| 126 | + else: |
| 127 | + observation, info = env.reset(seed=seed) |
| 128 | + observation = [float(val) for val in observation] |
| 129 | + step = TimeStep(observation=observation, |
| 130 | + reward=0.0, |
| 131 | + step_type=TimeStepType.FIRST, |
| 132 | + info=info, |
| 133 | + discount=1.0) |
| 134 | + logger.info(f'Reset environment {ENV_NAME} and index {cidx}') |
| 135 | + return JSONResponse(status_code=status.HTTP_202_ACCEPTED, |
| 136 | + content={"time_step": step.model_dump()}) |
| 137 | + |
| 138 | + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, |
| 139 | + detail={"message": f"Environment {ENV_NAME} is not initialized." |
| 140 | + " Have you called make()?"}) |
| 141 | + |
| 142 | + |
| 143 | +@lunar_lander_discrete_router.post("/step") |
| 144 | +async def step(action: int = Body(...), cidx: int = Body(...)) -> JSONResponse: |
| 145 | + if action not in ACTIONS_SPACE: |
| 146 | + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, |
| 147 | + detail=f"Action {action} not in {list(ACTIONS_SPACE.keys())}") |
| 148 | + |
| 149 | + global envs |
| 150 | + if cidx in envs: |
| 151 | + env = envs[cidx] |
| 152 | + |
| 153 | + if env is not None: |
| 154 | + logger.info(f"Stepping in environment {ENV_NAME} with action={action}") |
| 155 | + observation, reward, terminated, truncated, info = env.step(action) |
| 156 | + observation = [float(val) for val in observation] |
| 157 | + |
| 158 | + step_type = TimeStepType.MID |
| 159 | + if terminated: |
| 160 | + step_type = TimeStepType.LAST |
| 161 | + |
| 162 | + if info is not None: |
| 163 | + info['truncated'] = truncated |
| 164 | + |
| 165 | + step = TimeStep(observation=observation, |
| 166 | + reward=reward, |
| 167 | + step_type=step_type, |
| 168 | + info=info, |
| 169 | + discount=1.0) |
| 170 | + |
| 171 | + logger.info(f'Step in environment {ENV_NAME} and index {cidx}') |
| 172 | + return JSONResponse(status_code=status.HTTP_202_ACCEPTED, |
| 173 | + content={"time_step": step.model_dump()}) |
| 174 | + |
| 175 | + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, |
| 176 | + detail=f"Environment {ENV_NAME} is not initialized. Have you called make()?") |
| 177 | + |
| 178 | + |
| 179 | +@lunar_lander_discrete_router.post("/sync") |
| 180 | +async def sync(cidx: int = Body(...), options: dict[str, Any] = Body(default={})) -> JSONResponse: |
| 181 | + return JSONResponse(status_code=status.HTTP_202_ACCEPTED, |
| 182 | + content={"message": "OK"}) |
0 commit comments