diff --git a/PyFlyt/gym_envs/fixedwing_envs/fixedwing_base_env.py b/PyFlyt/gym_envs/fixedwing_envs/fixedwing_base_env.py index 55bf2ba2..a3359a3c 100644 --- a/PyFlyt/gym_envs/fixedwing_envs/fixedwing_base_env.py +++ b/PyFlyt/gym_envs/fixedwing_envs/fixedwing_base_env.py @@ -275,7 +275,13 @@ def step(self, action: np.ndarray) -> tuple[Any, float, bool, bool, dict]: # increment step count self.step_count += 1 - return self.state, self.reward, self.termination, self.truncation, self.info + return ( + self.state, + self.reward, + self.termination, + self.truncation, + self.info.copy(), + ) def render(self) -> np.ndarray: """Render.""" diff --git a/PyFlyt/gym_envs/fixedwing_envs/fixedwing_waypoints_env.py b/PyFlyt/gym_envs/fixedwing_envs/fixedwing_waypoints_env.py index dc97c9b2..63a1814b 100644 --- a/PyFlyt/gym_envs/fixedwing_envs/fixedwing_waypoints_env.py +++ b/PyFlyt/gym_envs/fixedwing_envs/fixedwing_waypoints_env.py @@ -116,7 +116,7 @@ def reset( self.info["num_targets_reached"] = 0 super().end_reset() - return self.state, self.info + return self.state, self.info.copy() def compute_state(self) -> None: """Computes the state of the current timestep. diff --git a/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_ball_in_cup_env.py b/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_ball_in_cup_env.py new file mode 100644 index 00000000..b39c0303 --- /dev/null +++ b/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_ball_in_cup_env.py @@ -0,0 +1,314 @@ +"""QuadX Ball-in-Cup Environment.""" + +from __future__ import annotations + +import os +from typing import Any, Literal + +import numpy as np +from gymnasium import spaces + +from PyFlyt.gym_envs.quadx_envs.quadx_base_env import QuadXBaseEnv + + +class QuadXBallInCupEnv(QuadXBaseEnv): + """QuadX Ball-in-Cup Environment. + + Actions are vp, vq, vr, T, ie: angular rates and thrust. + The goal is to swing up a suspended ball onto the drone, and then bring it to the starting position. + + Args: + sparse_reward (bool): whether to use sparse rewards or not. + goal_reach_distance (float): minimum distance from the ending position that the UAV must reach for success. + goal_reach_velocity (float): maximum velocity that the UAV must maintain at the ending position for success. + flight_mode (int): the flight mode of the UAV. + flight_dome_size (float): size of the allowable flying area. + max_duration_seconds (float): maximum simulation time of the environment. + angle_representation (Literal["euler", "quaternion"]): can be "euler" or "quaternion". + agent_hz (int): looprate of the agent to environment interaction. + render_mode (None | Literal["human", "rgb_array"]): render_mode + render_resolution (tuple[int, int]): render_resolution. + + """ + + def __init__( + self, + sparse_reward: bool = False, + goal_reach_distance: float = 1.0, + goal_reach_velocity: float = 1.0, + flight_mode: int = 0, + flight_dome_size: float = 30.0, + max_duration_seconds: float = 10.0, + angle_representation: Literal["euler", "quaternion"] = "quaternion", + agent_hz: int = 30, + render_mode: None | Literal["human", "rgb_array"] = None, + render_resolution: tuple[int, int] = (480, 480), + ): + """__init__. + + Args: + sparse_reward (bool): whether to use sparse rewards or not. + goal_reach_distance (float): minimum distance from the ending position that the UAV must reach for success. + goal_reach_velocity (float): maximum velocity that the UAV must maintain at the ending position for success. + flight_mode (int): the flight mode of the UAV. + flight_dome_size (float): size of the allowable flying area. + max_duration_seconds (float): maximum simulation time of the environment. + angle_representation (Literal["euler", "quaternion"]): can be "euler" or "quaternion". + agent_hz (int): looprate of the agent to environment interaction. + render_mode (None | Literal["human", "rgb_array"]): render_mode + render_resolution (tuple[int, int]): render_resolution. + + """ + super().__init__( + start_pos=np.array([[0.0, 0.0, 4.0]]), + flight_mode=flight_mode, + flight_dome_size=flight_dome_size, + max_duration_seconds=max_duration_seconds, + angle_representation=angle_representation, + agent_hz=agent_hz, + render_mode=render_mode, + render_resolution=render_resolution, + ) + + # Define observation space + self.observation_space = spaces.Box( + low=-np.inf, + high=np.inf, + shape=(self.combined_space.shape[0] + 6,), + dtype=np.float64, + ) + + """ ENVIRONMENT CONSTANTS """ + self.sparse_reward = sparse_reward + self.goal_reach_distance = goal_reach_distance + self.goal_reach_velocity = goal_reach_velocity + file_dir = os.path.dirname(os.path.realpath(__file__)) + self.pendulum_filepath = os.path.join( + file_dir, "./../../models/ball_and_string.urdf" + ) + self.cup_filepath = os.path.join(file_dir, "./../../models/cup.urdf") + + def add_ball_and_string_and_cup(self) -> None: + """Spawns in the ball and string and cup.""" + # spawn in the cup + self.cup_id = self.env.loadURDF( + self.cup_filepath, + basePosition=self.env.state(0)[-1] + np.array([0.0, 0.0, 0.035]), + baseOrientation=np.array([0.0, 0.0, 0.0, 1.0]), + useFixedBase=False, + globalScaling=1.0, + ) + # spawn in the pendulum + self.pendulum_id = self.env.loadURDF( + self.pendulum_filepath, + # permanently attach the ball to the drone + basePosition=self.env.state(0)[-1] - np.array([0, 0, 0.5]), + # randomly angle the ball + baseOrientation=np.array( + [ + (self.np_random.random() * 2.0) - 1.0, + (self.np_random.random() * 2.0) - 1.0, + (self.np_random.random() * 2.0) - 1.0, + 1.0, + ] + ), + useFixedBase=False, + globalScaling=1.0, + ) + + # register all new bodies with Aviary + self.env.register_all_new_bodies() + + # create a constraint between the base of the cup object and the drone + _zeros = np.zeros((3,), dtype=np.float32) + self.env.createConstraint( + parentBodyUniqueId=self.env.drones[0].Id, + parentLinkIndex=-1, + childBodyUniqueId=self.cup_id, + childLinkIndex=-1, + jointType=self.env.JOINT_FIXED, + jointAxis=_zeros, + parentFramePosition=_zeros, + childFramePosition=np.array([0.0, 0.0, -0.035]), + ) + # create a constraint between the base of the pendulum object and the drone + self.env.createConstraint( + parentBodyUniqueId=self.env.drones[0].Id, + parentLinkIndex=-1, + childBodyUniqueId=self.pendulum_id, + childLinkIndex=0, + jointType=self.env.JOINT_POINT2POINT, + jointAxis=_zeros, + parentFramePosition=_zeros, + childFramePosition=_zeros, + ) + + # disable motor on the prismatic joint + self.env.setJointMotorControl2( + self.pendulum_id, + 0, + self.env.VELOCITY_CONTROL, + force=0, + ) + + def reset( + self, *, seed: None | int = None, options: None | dict[str, Any] = dict() + ) -> tuple[np.ndarray, dict]: + """Resets the environment. + + Args: + seed: seed to pass to the base environment. + options: None + + """ + options = dict( + drone_model="primitive_drone", + use_camera=True, + camera_fps=30, + camera_angle_degrees=-90, + camera_FOV_degrees=140, + ) + super().begin_reset(seed, drone_options=options) + + # add the ball + self.add_ball_and_string_and_cup() + + # stateful params with history for the ball + self.drone_state_error = np.zeros((4,), dtype=np.float32) + self.drone_state_prev_error = np.zeros((4,), dtype=np.float32) + + super().end_reset() + self.compute_state() + return self.state, self.info.copy() + + def compute_state(self) -> None: + """Computes the state of the current timestep. + + This returns the current vehicle attitude as well as the state of the ball. + - ang_vel (vector of 3 values) + - ang_pos (vector of 3/4 values) + - lin_vel (vector of 3 values) + - lin_pos (vector of 3 values) + - previous_action (vector of 4 values) + - auxiliary information (vector of 4 values) + - ball state (vector of 3 values) + """ + ang_vel, ang_pos, lin_vel, lin_pos, quaternion = super().compute_attitude() + rotation = ( + np.array(self.env.getMatrixFromQuaternion(quaternion)).reshape(3, 3).T + ) + aux_state = super().compute_auxiliary() + + # combine everything + if self.angle_representation == 0: + attitude = np.concatenate( + [ + ang_vel, + ang_pos, + lin_vel, + lin_pos, + self.action, + aux_state, + ], + axis=-1, + ) + elif self.angle_representation == 1: + attitude = np.concatenate( + [ + ang_vel, + quaternion, + lin_vel, + lin_pos, + self.action, + aux_state, + ], + axis=-1, + ) + else: + raise NotImplementedError + + # compute ball state + self.ball_lin_pos, _ = self.env.getBasePositionAndOrientation(self.pendulum_id) + self.ball_lin_vel, _ = self.env.getBaseVelocity(self.pendulum_id) + + # compute ball state relative to self + self.ball_rel_lin_pos = np.matmul(rotation, self.ball_lin_pos - lin_pos) + self.ball_rel_lin_vel = np.matmul(rotation, self.ball_lin_vel) + + # drone_state: [4, 3] + # drone_state_error: [4,] + self.drone_state_prev_error = self.drone_state_error.copy() + self.drone_state_error = self.env.state(0).copy() + self.drone_state_error[-1] -= np.array([0.0, 0.0, 1.0]) + self.drone_state_error = np.linalg.norm(self.drone_state_error, axis=-1) ** 2 + + # concat the attitude and ball state + self.state = np.concatenate( + [ + attitude, + self.ball_rel_lin_pos, + self.ball_rel_lin_vel, + ], + axis=0, + ) + + def compute_term_trunc_reward(self) -> None: + """Computes the termination, truncation, and reward of the current timestep.""" + super().compute_base_term_trunc_reward() + # compute some parameters of the ball + # lin_pos: [3,], height: [1,], abs_dist: [1,] + ball_rel_lin_pos = self.ball_lin_pos - self.env.state(0)[-1] + ball_rel_height = ball_rel_lin_pos[2] + ball_rel_abs_dist = np.linalg.norm(ball_rel_lin_pos) + + # bonus reward if we are not sparse + if not self.sparse_reward: + # Negative Reward For High Yaw rate, To prevent high yaw while training + yaw_rate = abs( + self.env.state(0)[0][2] + ) # Assuming z-axis is the last component + yaw_rate_penalty = 0.01 * yaw_rate**2 # Add penalty for high yaw rate + self.reward -= ( + yaw_rate_penalty # You can adjust the coefficient (0.01) as needed + ) + + # reward for staying alive + self.reward += 0.4 + + # penalty for aggressive maneuvres, and try to stay close to origin + self.reward -= 0.01 * np.sum(self.drone_state_error) + + if ball_rel_height > 0.0: + # reward for bringing the ball close to self + self.reward -= 4.0 * np.log(0.45 * ball_rel_abs_dist + 1e-2) + else: + # penalty when ball below drone + self.reward += ball_rel_height + + # when the ball hit the drone, either success or failure + if self.env.contact_array[self.pendulum_id, self.env.drones[0].Id]: + # hitting self is bad + if ball_rel_height < 0.0: + self.reward = -500.0 + self.termination = True + self.info["self_collision"] = True + return + + # if the ball is above us, we need to check the success criteria + if ( + self.drone_state_error[-1] < self.goal_reach_distance + and self.drone_state_error[-2] < self.goal_reach_velocity + ): + # hack: use truncation here, otherwise we need a HUGE reward to end + self.reward += 1000.0 + self.truncation = True + self.info["env_complete"] = True + return + + # if it's up, but we're not at the winning criteria yet, + # reward for approaching goal position + if not self.sparse_reward: + self.reward += 50.0 * ( + self.drone_state_prev_error[-1] - self.drone_state_error[-1] + ) + self.reward += 10.0 / (self.drone_state_error[-1] + 0.1) diff --git a/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_base_env.py b/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_base_env.py new file mode 100644 index 00000000..87a62a9d --- /dev/null +++ b/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_base_env.py @@ -0,0 +1,344 @@ +"""Base PyFlyt Environment for the QuadX model using the Gymnasim API.""" + +from __future__ import annotations + +from typing import Any, Literal + +import gymnasium +import numpy as np +import pybullet as p +from gymnasium import spaces + +from PyFlyt.core.aviary import Aviary +from PyFlyt.core.utils.compile_helpers import check_numpy + + +class QuadXBaseEnv(gymnasium.Env): + """Base PyFlyt Environment for the QuadX model using the Gymnasium API.""" + + metadata = {"render_modes": ["human", "rgb_array"], "render_fps": 30} + + def __init__( + self, + start_pos: np.ndarray = np.array([[0.0, 0.0, 1.0]]), + start_orn: np.ndarray = np.array([[0.0, 0.0, 0.0]]), + flight_mode: int = 0, + flight_dome_size: float = np.inf, + max_duration_seconds: float = 10.0, + angle_representation: Literal["euler", "quaternion"] = "quaternion", + agent_hz: int = 30, + render_mode: None | Literal["human", "rgb_array"] = None, + render_resolution: tuple[int, int] = (480, 480), + world_scale: int = 1, + ): + """__init__. + + Args: + start_pos (np.ndarray): start_pos + start_orn (np.ndarray): start_orn + flight_mode (int): flight_mode + flight_dome_size (float): flight_dome_size + max_duration_seconds (float): max_duration_seconds + angle_representation (Literal["euler", "quaternion"]): angle_representation + agent_hz (int): agent_hz + render_mode (None | Literal["human", "rgb_array"]): render_mode + render_resolution (tuple[int, int]): render_resolution + + """ + if 120 % agent_hz != 0: + lowest = int(120 / (int(120 / agent_hz) + 1)) + highest = int(120 / int(120 / agent_hz)) + raise ValueError( + f"`agent_hz` must be round denominator of 120, try {lowest} or {highest}." + ) + + if render_mode and render_mode not in self.metadata["render_modes"]: + raise ValueError( + f"Invalid render mode {render_mode}, only {self.metadata['render_modes']} allowed." + ) + self.render_mode = render_mode + self.render_resolution = render_resolution + + """GYMNASIUM STUFF""" + # attitude size increases by 1 for quaternion + if angle_representation == "euler": + attitude_shape = 12 + elif angle_representation == "quaternion": + attitude_shape = 13 + else: + raise ValueError( + f"angle_representation must be either `euler` or `quaternion`, not {angle_representation}" + ) + + self.attitude_space = spaces.Box( + low=-np.inf, high=np.inf, shape=(attitude_shape,), dtype=np.float64 + ) + self.auxiliary_space = spaces.Box( + low=-np.inf, high=np.inf, shape=(4,), dtype=np.float64 + ) + + # define the action space + xyz_limit = np.pi + thrust_limit = 0.8 + if flight_mode == -1: + high = np.ones((4,)) * thrust_limit + low = np.zeros((4,)) + else: + high = np.array( + [ + xyz_limit, + xyz_limit, + xyz_limit, + thrust_limit, + ] + ) + low = np.array( + [ + -xyz_limit, + -xyz_limit, + -xyz_limit, + 0.0, + ] + ) + self.action_space = spaces.Box(low=low, high=high, dtype=np.float64) + + # the whole implicit state space = attitude + previous action + auxiliary information + self.combined_space = spaces.Box( + low=-np.inf, + high=np.inf, + shape=( + attitude_shape + + self.action_space.shape[0] + + self.auxiliary_space.shape[0], + ), + dtype=np.float64, + ) + + """ ENVIRONMENT CONSTANTS """ + self.start_pos = start_pos + self.start_orn = start_orn + self.flight_mode = flight_mode + self.flight_dome_size = flight_dome_size + self.max_steps = int(agent_hz * max_duration_seconds) + self.env_step_ratio = int(120 / agent_hz) + if angle_representation == "euler": + self.angle_representation = 0 + elif angle_representation == "quaternion": + self.angle_representation = 1 + + self.world_scale = world_scale + + def close(self) -> None: + """Disconnects the internal Aviary.""" + # if we already have an env, disconnect from it + if hasattr(self, "env"): + self.env.disconnect() + + def reset( + self, *, seed: None | int = None, options: dict[str, Any] | None = dict() + ) -> tuple[Any, dict[str, Any]]: + """reset. + + Args: + seed (None | int): seed + options (dict[str, Any]): options + + Returns: + tuple[Any, dict[str, Any]]: + + """ + raise NotImplementedError + + def begin_reset( + self, + seed: None | int = None, + options: None | dict[str, Any] = dict(), + drone_options: None | dict[str, Any] = dict(), + ) -> None: + """The first half of the reset function.""" + super().reset(seed=seed) + + # if we already have an env, disconnect from it + if hasattr(self, "env"): + self.env.disconnect() + + self.step_count = 0 + self.termination = False + self.truncation = False + self.state = None + self.action = np.zeros((4,)) + self.reward = 0.0 + self.info = {} + self.info["out_of_bounds"] = False + self.info["collision"] = False + self.info["env_complete"] = False + + # need to handle Nones + if options is None: + options = dict() + if drone_options is None: + drone_options = dict() + + # camera handling + drone_options["use_camera"] = drone_options.get("use_camera", False) or bool( + self.render_mode + ) + drone_options["camera_fps"] = int(120 / self.env_step_ratio) + + # init env + self.env = Aviary( + start_pos=self.start_pos, + start_orn=self.start_orn, + drone_type="quadx", + render=self.render_mode == "human", + drone_options=drone_options, + world_scale=self.world_scale, + np_random=self.np_random, + ) + + if self.render_mode == "human": + self.camera_parameters = self.env.getDebugVisualizerCamera() + + def end_reset( + self, seed: None | int = None, options: None | dict[str, Any] = dict() + ) -> None: + """The tailing half of the reset function.""" + # register all new collision bodies + self.env.register_all_new_bodies() + + # set flight mode + self.env.set_mode(self.flight_mode) + + # wait for env to stabilize + for _ in range(10): + self.env.step() + + self.compute_state() + + def compute_state(self) -> None: + """Computes the state of the QuadX.""" + raise NotImplementedError + + def compute_auxiliary(self) -> np.ndarray: + """This returns the auxiliary state form the drone.""" + return self.env.aux_state(0) + + def compute_attitude( + self, + ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """state. + + This returns the base attitude for the drone. + - ang_vel (vector of 3 values) + - ang_pos (vector of 3 values) + - lin_vel (vector of 3 values) + - lin_pos (vector of 3 values) + - quaternion (vector of 4 values) + """ + raw_state = self.env.state(0) + + # state breakdown + ang_vel = raw_state[0] + ang_pos = raw_state[1] + lin_vel = raw_state[2] + lin_pos = raw_state[3] + + # quaternion angles + quaternion = p.getQuaternionFromEuler(ang_pos) + + return ang_vel, ang_pos, lin_vel, lin_pos, quaternion + + def compute_term_trunc_reward(self) -> None: + """compute_term_trunc_reward.""" + raise NotImplementedError + + def compute_base_term_trunc_reward(self) -> None: + """compute_base_term_trunc_reward.""" + # exceed step count + if self.step_count > self.max_steps: + self.truncation |= True + + # if anything hits the floor, basically game over + if np.any(self.env.contact_array[self.env.planeId]): + self.reward = -100.0 + self.info["collision"] = True + self.termination |= True + + # exceed flight dome + if np.linalg.norm(self.env.state(0)[-1]) > self.flight_dome_size: + self.reward = -100.0 + self.info["out_of_bounds"] = True + self.termination |= True + + def step(self, action: np.ndarray) -> tuple[Any, float, bool, bool, dict[str, Any]]: + """Steps the environment. + + Args: + action (np.ndarray): action + + Returns: + state, reward, termination, truncation, info + + """ + # unsqueeze the action to be usable in aviary + self.action = action.copy() + + # reset the reward and set the action + self.reward = -0.1 + self.env.set_setpoint(0, action) + + # step through env, the internal env updates a few steps before the outer env + for _ in range(self.env_step_ratio): + # if we've already ended, don't continue + if self.termination or self.truncation: + break + + self.env.step() + + # compute state and done + self.compute_state() + self.compute_term_trunc_reward() + + # increment step count + self.step_count += 1 + + return ( + self.state, + self.reward, + self.termination, + self.truncation, + self.info.copy(), + ) + + def render(self) -> np.ndarray: + """Render.""" + check_numpy() + if self.render_mode is None: + raise ValueError( + "Please set `render_mode='human'` or `render_mode='rgb_array'` in init to use this function." + ) + + if self.render_mode == "human": + _, _, rgbaImg, _, _ = self.env.getCameraImage( + width=self.render_resolution[1], + height=self.render_resolution[0], + viewMatrix=self.camera_parameters[2], + projectionMatrix=self.camera_parameters[3], + ) + elif self.render_mode == "rgb_array": + _, _, rgbaImg, _, _ = self.env.getCameraImage( + width=self.render_resolution[1], + height=self.render_resolution[0], + viewMatrix=self.env.drones[0].camera.view_mat, + projectionMatrix=self.env.drones[0].camera.proj_mat, + ) + else: + raise ValueError( + f"Unknown render mode {self.render_mode}, should not have ended up here" + ) + + rgbaImg = np.asarray(rgbaImg, dtype=np.uint8).reshape( + self.render_resolution[0], self.render_resolution[1], -1 + ) + + return rgbaImg diff --git a/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_gates_env.py b/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_gates_env.py new file mode 100644 index 00000000..40fc4698 --- /dev/null +++ b/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_gates_env.py @@ -0,0 +1,319 @@ +"""QuadX Gates Environment.""" + +from __future__ import annotations + +import copy +import math +import os +from typing import Any, Literal + +import numpy as np +import pybullet as p +from gymnasium import spaces + +from PyFlyt.gym_envs.quadx_envs.quadx_base_env import QuadXBaseEnv + + +class QuadXGatesEnv(QuadXBaseEnv): + """QuadX Gates Environment. + + Actions are vp, vq, vr, T, ie: angular rates and thrust + + The target is a set of `[x, y, z, yaw]` targets in space + + Reward is -(distance from waypoint + angle error) for each timestep, and -100.0 for hitting the ground. + + Args: + flight_mode (int): the flight mode of the UAV + num_targets (int): num_targets + goal_reach_distance (float): goal_reach_distance + min_gate_height (float): min_gate_height + max_gate_angles (list[float]): max_gate_angles + min_gate_distance (float): min_gate_distance + max_gate_distance (float): max_gate_distance + camera_resolution (tuple[int, int]): camera_resolution + max_duration_seconds (float): max_duration_seconds + angle_representation (Literal["euler", "quaternion"]): can be "euler" or "quaternion". + agent_hz (int): looprate of the agent to environment interaction. + render_mode (None | Literal["human", "rgb_array"]): render_mode + render_resolution (tuple[int, int]): render_resolution + + """ + + def __init__( + self, + num_targets: int = 5, + flight_mode: int = 0, + goal_reach_distance: float = 0.21, + min_gate_height: float = 1.0, + max_gate_angles: list[float] = [0.0, 0.3, 1.0], + min_gate_distance: float = 1.0, + max_gate_distance: float = 4.0, + camera_resolution: tuple[int, int] = (128, 128), + max_duration_seconds: float = 10.0, + angle_representation: Literal["euler", "quaternion"] = "quaternion", + agent_hz: int = 40, + render_mode: None | Literal["human", "rgb_array"] = None, + render_resolution: tuple[int, int] = (480, 480), + ): + """__init__. + + Args: + flight_mode (int): the flight mode of the UAV + num_targets (int): num_targets + goal_reach_distance (float): goal_reach_distance + min_gate_height (float): min_gate_height + max_gate_angles (list[float]): max_gate_angles + min_gate_distance (float): min_gate_distance + max_gate_distance (float): max_gate_distance + camera_resolution (tuple[int, int]): camera_resolution + max_duration_seconds (float): max_duration_seconds + angle_representation (Literal["euler", "quaternion"]): can be "euler" or "quaternion". + agent_hz (int): looprate of the agent to environment interaction. + render_mode (None | Literal["human", "rgb_array"]): render_mode + render_resolution (tuple[int, int]): render_resolution + + """ + super().__init__( + flight_mode=flight_mode, + max_duration_seconds=max_duration_seconds, + angle_representation=angle_representation, + agent_hz=agent_hz, + render_mode=render_mode, + render_resolution=render_resolution, + ) + + """GYMNASIUM STUFF""" + self.observation_space = spaces.Dict( + { + "attitude": self.combined_space, + "rgba_cam": spaces.Box( + low=0.0, high=255.0, shape=(4, *camera_resolution), dtype=np.uint8 + ), + "target_deltas": spaces.Sequence( + space=spaces.Box( + low=-np.inf, + high=np.inf, + shape=(3,), + dtype=np.float64, + ), + ), + } + ) + + """ ENVIRONMENT CONSTANTS """ + self.min_gate_height = min_gate_height + self.min_gate_distance = min_gate_distance + self.max_gate_distance = max_gate_distance + self.max_gate_angles = np.array([max_gate_angles]) + self.goal_reach_distance = goal_reach_distance + + file_dir = os.path.dirname(os.path.realpath(__file__)) + self.gate_obj_dir = os.path.join(file_dir, "../models/race_gate.urdf") + self.camera_resolution = camera_resolution + self.num_targets = num_targets + + def reset( + self, *, seed: None | int = None, options: None | dict[str, Any] = dict() + ) -> tuple[ + dict[Literal["attitude", "rgba_cam", "target_deltas"], np.ndarray], dict + ]: + """Resets the environment. + + Args: + seed: seed to pass to the base environment. + options: None + + """ + aviary_options = dict() + aviary_options["use_camera"] = True + aviary_options["use_gimbal"] = False + aviary_options["camera_resolution"] = self.camera_resolution + aviary_options["camera_angle_degrees"] = 15.0 + super().begin_reset(seed, options, aviary_options) + + """GATES GENERATION""" + self.gates = [] + self.targets = [] + self.generate_gates() + + super().end_reset(seed, options) + + return self.state, self.info.copy() + + def generate_gates(self) -> None: + """Generates the gates.""" + # sample a bunch of distances for gate distances + distances = self.np_random.uniform( + self.min_gate_distance, self.max_gate_distance, size=(self.num_targets,) + ) + angles = self.np_random.uniform(-1.0, 1.0, size=(self.num_targets, 3)) + angles *= self.max_gate_angles + + # starting position and angle + gate_pos = np.array([0.0, 0.0, 1.0]) + gate_ang = np.array([0.0, 0.0, 0.0]) + + for new_distance, new_angle in zip(distances, angles): + # check that the gate we're about to make doesn't go below the minimum height + vertical_offset = 0.0 + if ( + gate_pos[2] + + self.max_gate_distance * math.cos(self.max_gate_angles[0, 1]) + < self.min_gate_height + ): + vertical_offset = gate_pos[2] + self.max_gate_distance * math.cos( + self.max_gate_angles[0, 1] + ) + + # old rotation matrix and quat + old_quat = p.getQuaternionFromEuler(gate_ang) + old_mat = np.array(p.getMatrixFromQuaternion(old_quat)).reshape(3, 3) + + # new rotation matrix and quat + new_quat = p.getQuaternionFromEuler(new_angle) + new_mat = np.array(p.getMatrixFromQuaternion(new_quat)).reshape(3, 3) + + # rotate new distance by old angle and then new angle + new_distance = np.array([0.0, new_distance, vertical_offset]) + new_distance = new_mat @ old_mat @ new_distance + + # new position + gate_pos += new_distance + gate_ang += new_angle + + # get new gate quaternion + gate_quat = p.getQuaternionFromEuler(gate_ang) + + # store the new target and gates + self.targets.append(copy.copy(gate_pos)) + self.gates.append( + self.env.loadURDF( + self.gate_obj_dir, + basePosition=gate_pos, + baseOrientation=gate_quat, + useFixedBase=True, + ) + ) + + # colour the first gate + self.colour_first_gate() + self.colour_other_gate() + + def colour_dead_gate(self, gate: int) -> None: + """Colours the gates that are done. + + Args: + gate (int): body ID of the gate + + """ + # colour the dead gates red + for i in range(p.getNumJoints(gate)): + p.changeVisualShape( + gate, + linkIndex=i, + rgbaColor=(1, 0, 0, 1), + ) + + def colour_first_gate(self) -> None: + """Colours the immediate target gate.""" + # colour the first gate green + for i in range(p.getNumJoints(self.gates[0])): + p.changeVisualShape( + self.gates[0], + linkIndex=i, + rgbaColor=(0, 1, 0, 1), + ) + + def colour_other_gate(self) -> None: + """Colours gates that are neither targets nor dead.""" + # colour all other gates yellow + for gate in self.gates[1:]: + for i in range(p.getNumJoints(gate)): + p.changeVisualShape( + gate, + linkIndex=i, + rgbaColor=(1, 1, 0, 1), + ) + + def compute_state(self) -> None: + """This returns the observation as well as the distances to target. + + - "attitude" (Box) + - ang_vel (vector of 3 values) + - ang_pos (vector of 3/4 values) + - lin_vel (vector of 3 values) + - lin_pos (vector of 3 values) + - previous_action (vector of 4 values) + - auxiliary information (vector of 4 values) + - "target_deltas" (Graph) + - list of body_frame distances to target (vector of 3/4 values) + """ + ang_vel, ang_pos, lin_vel, lin_pos, quaternion = super().compute_attitude() + aux_state = super().compute_auxiliary() + + # rotation matrix + rotation = np.array(p.getMatrixFromQuaternion(quaternion)).reshape(3, 3).T + + # drone to target + target_deltas = np.matmul(rotation, (self.targets - lin_pos).T).T + self.dis_error_scalar = np.linalg.norm(target_deltas[0]) + + # combine everything + new_state: dict[ + Literal["attitude", "rgba_cam", "target_deltas"], np.ndarray + ] = dict() + if self.angle_representation == 0: + new_state["attitude"] = np.concatenate( + [ang_vel, ang_pos, lin_vel, lin_pos, self.action, aux_state], axis=-1 + ) + elif self.angle_representation == 1: + new_state["attitude"] = np.concatenate( + [ang_vel, quaternion, lin_vel, lin_pos, self.action, aux_state], axis=-1 + ) + + # grab the image + img = self.env.drones[0].rgbaImg.astype(np.uint8) + new_state["rgba_cam"] = np.moveaxis(img, -1, 0) + + # distances to targets + new_state["target_deltas"] = target_deltas + + self.state: dict[ + Literal["attitude", "rgba_cam", "target_deltas"], np.ndarray + ] = new_state + + @property + def target_reached(self) -> bool: + """Checks if the immediate target has been reached.""" + if self.dis_error_scalar < self.goal_reach_distance: + return True + else: + return False + + def compute_term_trunc_reward(self) -> None: + """Computes the termination, truncation, and reward of the current step.""" + super().compute_base_term_trunc_reward() + + # out of range of next gate + if self.dis_error_scalar > 2 * self.max_gate_distance: + self.reward += -100.0 + self.info["out_of_bounds"] = True + self.termination = self.termination or True + + # target reached + if self.target_reached: + self.reward += 100.0 + if len(self.targets) > 1: + # still have targets to go + self.targets = self.targets[1:] + else: + self.info["env_complete"] = True + self.termination = self.termination or True + + # shift the gates and recolour the reached one + self.colour_dead_gate(self.gates[0]) + self.gates = self.gates[1:] + + # colour the new target + self.colour_first_gate() diff --git a/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_hover_env.py b/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_hover_env.py new file mode 100644 index 00000000..67afdcf2 --- /dev/null +++ b/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_hover_env.py @@ -0,0 +1,138 @@ +"""QuadX Hover Environment.""" + +from __future__ import annotations + +from typing import Any, Literal + +import numpy as np + +from PyFlyt.gym_envs.quadx_envs.quadx_base_env import QuadXBaseEnv + + +class QuadXHoverEnv(QuadXBaseEnv): + """Simple Hover Environment. + + Actions are vp, vq, vr, T, ie: angular rates and thrust. + The target is to not crash for the longest time possible. + + Args: + sparse_reward (bool): whether to use sparse rewards or not. + flight_mode (int): the flight mode of the UAV + flight_dome_size (float): size of the allowable flying area. + max_duration_seconds (float): maximum simulation time of the environment. + angle_representation (Literal["euler", "quaternion"]): can be "euler" or "quaternion". + agent_hz (int): looprate of the agent to environment interaction. + render_mode (None | Literal["human", "rgb_array"]): render_mode + render_resolution (tuple[int, int]): render_resolution. + + """ + + def __init__( + self, + sparse_reward: bool = False, + flight_mode: int = 0, + flight_dome_size: float = 3.0, + max_duration_seconds: float = 10.0, + angle_representation: Literal["euler", "quaternion"] = "quaternion", + agent_hz: int = 40, + render_mode: None | Literal["human", "rgb_array"] = None, + render_resolution: tuple[int, int] = (480, 480), + ): + """__init__. + + Args: + sparse_reward (bool): whether to use sparse rewards or not. + flight_mode (int): the flight mode of the UAV + flight_dome_size (float): size of the allowable flying area. + max_duration_seconds (float): maximum simulation time of the environment. + angle_representation (Literal["euler", "quaternion"]): can be "euler" or "quaternion". + agent_hz (int): looprate of the agent to environment interaction. + render_mode (None | Literal["human", "rgb_array"]): render_mode + render_resolution (tuple[int, int]): render_resolution. + + """ + super().__init__( + flight_mode=flight_mode, + flight_dome_size=flight_dome_size, + max_duration_seconds=max_duration_seconds, + angle_representation=angle_representation, + agent_hz=agent_hz, + render_mode=render_mode, + render_resolution=render_resolution, + ) + + """GYMNASIUM STUFF""" + self.observation_space = self.combined_space + + """ ENVIRONMENT CONSTANTS """ + self.sparse_reward = sparse_reward + + def reset( + self, *, seed: None | int = None, options: None | dict[str, Any] = dict() + ) -> tuple[np.ndarray, dict[str, Any]]: + """reset. + + Args: + seed: seed to pass to the base environment. + options: None + + """ + super().begin_reset(seed, options) + super().end_reset(seed, options) + + return self.state, self.info.copy() + + def compute_state(self) -> None: + """Computes the state of the current timestep. + + This returns the observation. + - ang_vel (vector of 3 values) + - ang_pos (vector of 3/4 values) + - lin_vel (vector of 3 values) + - lin_pos (vector of 3 values) + - previous_action (vector of 4 values) + - auxiliary information (vector of 4 values) + """ + ang_vel, ang_pos, lin_vel, lin_pos, quaternion = super().compute_attitude() + aux_state = super().compute_auxiliary() + + # combine everything + if self.angle_representation == 0: + self.state = np.concatenate( + [ + ang_vel, + ang_pos, + lin_vel, + lin_pos, + self.action, + aux_state, + ], + axis=-1, + ) + elif self.angle_representation == 1: + self.state = np.concatenate( + [ang_vel, quaternion, lin_vel, lin_pos, self.action, aux_state], axis=-1 + ) + + def compute_term_trunc_reward(self) -> None: + """Computes the termination, truncation, and reward of the current timestep.""" + super().compute_base_term_trunc_reward() + if not self.sparse_reward: + # distance from 0, 0, 1 hover point + linear_distance = np.linalg.norm( + self.env.state(0)[-1] - np.array([0.0, 0.0, 1.0]) + ) + # Negative Reward For High Yaw rate, To prevent high yaw while training + yaw_rate = abs( + self.env.state(0)[0][2] + ) # Assuming z-axis is the last component + yaw_rate_penalty = 0.01 * yaw_rate**2 # Add penalty for high yaw rate + self.reward -= ( + yaw_rate_penalty # You can adjust the coefficient (0.01) as needed + ) + + # how far are we from 0 roll pitch + angular_distance = np.linalg.norm(self.env.state(0)[1][:2]) + + self.reward -= linear_distance + angular_distance + self.reward += 1.0 diff --git a/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_pole_balance_env.py b/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_pole_balance_env.py new file mode 100644 index 00000000..df28fc9d --- /dev/null +++ b/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_pole_balance_env.py @@ -0,0 +1,198 @@ +"""QuadX Pole Balance Environment.""" + +from __future__ import annotations + +from typing import Any, Literal + +import numpy as np +from gymnasium import spaces + +from PyFlyt.gym_envs.quadx_envs.quadx_base_env import QuadXBaseEnv +from PyFlyt.gym_envs.utils.pole_handler import PoleHandler + + +class QuadXPoleBalanceEnv(QuadXBaseEnv): + """Simple Hover Environment with the additional goal of keeping a pole upright. + + Actions are direct motor PWM commands because any underlying controller introduces too much control latency. + The target is to not crash and not let the pole hit the ground for the longest time possible. + + Args: + sparse_reward (bool): whether to use sparse rewards or not. + flight_mode (int): the flight mode of the UAV + flight_dome_size (float): size of the allowable flying area. + max_duration_seconds (float): maximum simulation time of the environment. + angle_representation (Literal["euler", "quaternion"]): can be "euler" or "quaternion". + agent_hz (int): looprate of the agent to environment interaction. + render_mode (None | Literal["human", "rgb_array"]): render_mode + render_resolution (tuple[int, int]): render_resolution. + + """ + + def __init__( + self, + sparse_reward: bool = False, + flight_mode: int = -1, + flight_dome_size: float = 3.0, + max_duration_seconds: float = 20.0, + angle_representation: Literal["euler", "quaternion"] = "quaternion", + agent_hz: int = 40, + render_mode: None | Literal["human", "rgb_array"] = None, + render_resolution: tuple[int, int] = (480, 480), + ): + """__init__. + + Args: + sparse_reward (bool): whether to use sparse rewards or not. + flight_mode (int): the flight mode of the UAV. + flight_dome_size (float): size of the allowable flying area. + max_duration_seconds (float): maximum simulation time of the environment. + angle_representation (Literal["euler", "quaternion"]): can be "euler" or "quaternion". + agent_hz (int): looprate of the agent to environment interaction. + render_mode (None | Literal["human", "rgb_array"]): render_mode. + render_resolution (tuple[int, int]): render_resolution. + + """ + super().__init__( + flight_mode=flight_mode, + flight_dome_size=flight_dome_size, + max_duration_seconds=max_duration_seconds, + angle_representation=angle_representation, + agent_hz=agent_hz, + render_mode=render_mode, + render_resolution=render_resolution, + ) + # init the pole + self.pole = PoleHandler() + + """GYMNASIUM STUFF""" + # Define observation space + self.observation_space = spaces.Box( + low=-np.inf, + high=np.inf, + shape=( + self.combined_space.shape[0] + self.pole.observation_space.shape[0], + ), + dtype=np.float64, + ) + + """ ENVIRONMENT CONSTANTS """ + self.sparse_reward = sparse_reward + + def reset( + self, *, seed: None | int = None, options: None | dict[str, Any] = dict() + ) -> tuple[np.ndarray, dict[str, Any]]: + """reset. + + Args: + seed: seed to pass to the base environment. + options: None + + """ + super().begin_reset( + seed, + options, + drone_options={ + "drone_model": "primitive_drone", + "camera_position_offset": np.array([-3.0, 0.0, 1.0]), + }, + ) + self.pole.reset(p=self.env, start_location=np.array([0.0, 0.0, 1.55])) + super().end_reset(seed, options) + + return self.state, self.info.copy() + + def compute_state(self) -> None: + """Computes the state of the current timestep. + + This returns the observation. + - ang_vel (vector of 3 values) + - ang_pos (vector of 3/4 values) + - lin_vel (vector of 3 values) + - lin_pos (vector of 3 values) + - previous_action (vector of 4 values) + - auxiliary information (vector of 4 values) + - 12 values for the pole's positions relative to self: + ------ top position XYZ + ------ bottom position XYZ + ------ top velocity XYZ + ------ bottom velocity XYZ + - auxiliary information (vector of 4 values) + """ + # compute attitude of self + ang_vel, ang_pos, lin_vel, lin_pos, quaternion = super().compute_attitude() + aux_state = super().compute_auxiliary() + rotation = ( + np.array(self.env.getMatrixFromQuaternion(quaternion)).reshape(3, 3).T + ) + + # compute the pole's states + ( + pole_top_pos, + pole_top_vel, + pole_bot_pos, + pole_bot_vel, + ) = self.pole.compute_state( + rotation=rotation, + uav_lin_pos=lin_pos, + uav_lin_vel=lin_vel, + ) + + # combine everything + if self.angle_representation == 0: + self.state = np.concatenate( + [ + ang_vel, + ang_pos, + lin_vel, + lin_pos, + self.action, + aux_state, + pole_top_pos, + pole_bot_pos, + pole_top_vel, + pole_bot_vel, + ], + axis=-1, + ) + elif self.angle_representation == 1: + self.state = np.concatenate( + [ + ang_vel, + quaternion, + lin_vel, + lin_pos, + self.action, + aux_state, + pole_top_pos, + pole_bot_pos, + pole_top_vel, + pole_bot_vel, + ], + axis=-1, + ) + + def compute_term_trunc_reward(self) -> None: + """Computes the termination, truncation, and reward of the current timestep.""" + super().compute_base_term_trunc_reward() + + if not self.sparse_reward: + # distance from 0, 0, 1 hover point + linear_distance = np.linalg.norm( + self.env.state(0)[-1] - np.array([0.0, 0.0, 1.0]) + ) + + # how far are we from 0 roll pitch + angular_distance = np.linalg.norm(self.env.state(0)[1][:2]) + self.reward -= linear_distance + angular_distance + self.reward -= self.pole.leaningness + self.reward += 1.0 + + # Negative Reward For High Yaw rate, To prevent high yaw while training + yaw_rate = abs( + self.env.state(0)[0][2] + ) # Assuming z-axis is the last component + yaw_rate_penalty = 0.01 * yaw_rate**2 # Add penalty for high yaw rate + self.reward -= ( + yaw_rate_penalty # You can adjust the coefficient (0.01) as needed + ) diff --git a/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_pole_waypoints_env.py b/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_pole_waypoints_env.py new file mode 100644 index 00000000..9ae6c3de --- /dev/null +++ b/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_pole_waypoints_env.py @@ -0,0 +1,251 @@ +"""QuadX Pole Waypoints Environment.""" + +from __future__ import annotations + +from typing import Any, Literal + +import numpy as np +from gymnasium import spaces + +from PyFlyt.gym_envs.quadx_envs.quadx_base_env import QuadXBaseEnv +from PyFlyt.gym_envs.utils.pole_handler import PoleHandler +from PyFlyt.gym_envs.utils.waypoint_handler import WaypointHandler + + +class QuadXPoleWaypointsEnv(QuadXBaseEnv): + """QuadX Pole Waypoints Environment. + + Actions are direct motor PWM commands because any underlying controller introduces too much control latency. + The target is to get to a set of `[x, y, z]` waypoints in space without dropping the pole. + + Args: + sparse_reward (bool): whether to use sparse rewards or not. + num_targets (int): number of waypoints in the environment. + goal_reach_distance (float): distance to the waypoints for it to be considered reached. + flight_mode (int): the flight mode of the UAV. + flight_dome_size (float): size of the allowable flying area. + max_duration_seconds (float): maximum simulation time of the environment. + angle_representation (Literal["euler", "quaternion"]): can be "euler" or "quaternion". + agent_hz (int): looprate of the agent to environment interaction. + render_mode (None | Literal["human", "rgb_array"]): render_mode + render_resolution (tuple[int, int]): render_resolution. + + """ + + def __init__( + self, + sparse_reward: bool = False, + num_targets: int = 4, + goal_reach_distance: float = 0.2, + flight_mode: int = -1, + flight_dome_size: float = 10.0, + max_duration_seconds: float = 20.0, + angle_representation: Literal["euler", "quaternion"] = "quaternion", + agent_hz: int = 40, + render_mode: None | Literal["human", "rgb_array"] = None, + render_resolution: tuple[int, int] = (480, 480), + ): + """__init__. + + Args: + sparse_reward (bool): whether to use sparse rewards or not. + num_targets (int): number of waypoints in the environment. + goal_reach_distance (float): distance to the waypoints for it to be considered reached. + flight_mode (int): the flight mode of the UAV. + flight_dome_size (float): size of the allowable flying area. + max_duration_seconds (float): maximum simulation time of the environment. + angle_representation (Literal["euler", "quaternion"]): can be "euler" or "quaternion". + agent_hz (int): looprate of the agent to environment interaction. + render_mode (None | Literal["human", "rgb_array"]): render_mode. + render_resolution (tuple[int, int]): render_resolution. + + """ + super().__init__( + flight_mode=flight_mode, + flight_dome_size=flight_dome_size, + max_duration_seconds=max_duration_seconds, + angle_representation=angle_representation, + agent_hz=agent_hz, + render_mode=render_mode, + render_resolution=render_resolution, + ) + + # define waypoints + self.waypoints = WaypointHandler( + enable_render=self.render_mode is not None, + num_targets=num_targets, + use_yaw_targets=False, + goal_reach_distance=goal_reach_distance, + goal_reach_angle=np.inf, + flight_dome_size=flight_dome_size, + min_height=1.3, + np_random=self.np_random, + ) + + # init the pole + self.pole = PoleHandler() + combined_plus_pole_space = spaces.Box( + low=-np.inf, + high=np.inf, + shape=( + self.combined_space.shape[0] + self.pole.observation_space.shape[0], + ), + dtype=np.float64, + ) + + # Define observation space + self.observation_space = spaces.Dict( + { + "attitude": combined_plus_pole_space, + "target_deltas": spaces.Sequence( + space=spaces.Box( + low=-2 * flight_dome_size, + high=2 * flight_dome_size, + shape=(3,), + dtype=np.float64, + ), + stack=True, + ), + } + ) + + """ ENVIRONMENT CONSTANTS """ + self.sparse_reward = sparse_reward + + def reset( + self, *, seed: None | int = None, options: None | dict[str, Any] = dict() + ) -> tuple[dict[Literal["attitude", "target_deltas"], np.ndarray], dict]: + """Resets the environment. + + Args: + seed: seed to pass to the base environment. + options: None + + """ + super().begin_reset( + seed, + options, + drone_options={ + "drone_model": "primitive_drone", + "camera_position_offset": np.array([-3.0, 0.0, 1.0]), + }, + ) + + # spawn in a pole + self.pole.reset(p=self.env, start_location=np.array([0.0, 0.0, 1.55])) + + # init some other metadata + self.waypoints.reset(self.env, self.np_random) + self.info["num_targets_reached"] = 0 + + super().end_reset() + + return self.state, self.info.copy() + + def compute_state(self) -> None: + """Computes the state of the current timestep. + + This returns the observation as well as the distances to target. + - "attitude" (Box) + ----- ang_vel (vector of 3 values) + ----- ang_pos (vector of 3/4 values) + ----- lin_vel (vector of 3 values) + ----- lin_pos (vector of 3 values) + ----- previous_action (vector of 4 values) + ----- auxiliary information (vector of 4 values) + ----- 12 values for the pole's positions relative to self: + ---------- top position XYZ + ---------- bottom position XYZ + ---------- top velocity XYZ + ---------- bottom velocity XYZ + - "target_deltas" (Sequence) + ----- list of body_frame distances to target (vector of 3/4 values) + """ + # compute attitude of self + ang_vel, ang_pos, lin_vel, lin_pos, quaternion = super().compute_attitude() + aux_state = super().compute_auxiliary() + rotation = ( + np.array(self.env.getMatrixFromQuaternion(quaternion)).reshape(3, 3).T + ) + + # compute the pole's states + ( + pole_top_pos, + pole_top_vel, + pole_bot_pos, + pole_bot_vel, + ) = self.pole.compute_state( + rotation=rotation, + uav_lin_pos=lin_pos, + uav_lin_vel=lin_vel, + ) + + # combine everything + new_state: dict[Literal["attitude", "target_deltas"], np.ndarray] = dict() + if self.angle_representation == 0: + new_state["attitude"] = np.concatenate( + [ + ang_vel, + ang_pos, + lin_vel, + lin_pos, + self.action, + aux_state, + pole_top_pos, + pole_bot_pos, + pole_top_vel, + pole_bot_vel, + ], + axis=-1, + ) + elif self.angle_representation == 1: + new_state["attitude"] = np.concatenate( + [ + ang_vel, + quaternion, + lin_vel, + lin_pos, + self.action, + aux_state, + pole_top_pos, + pole_bot_pos, + pole_top_vel, + pole_bot_vel, + ], + axis=-1, + ) + + new_state["target_deltas"] = self.waypoints.distance_to_targets( + ang_pos, lin_pos, quaternion + ) + + self.state: dict[Literal["attitude", "target_deltas"], np.ndarray] = new_state + + def compute_term_trunc_reward(self) -> None: + """Computes the termination, truncation, and reward of the current timestep.""" + super().compute_base_term_trunc_reward() + # bonus reward if we are not sparse + if not self.sparse_reward: + self.reward += max(15.0 * self.waypoints.progress_to_next_target, 0.0) + self.reward += 0.5 / self.waypoints.distance_to_next_target + self.reward += 0.5 - self.pole.leaningness + # Negative Reward For High Yaw rate, To prevent high yaw while training + yaw_rate = abs( + self.env.state(0)[0][2] + ) # Assuming z-axis is the last component + yaw_rate_penalty = 0.01 * yaw_rate**2 # Add penalty for high yaw rate + self.reward -= ( + yaw_rate_penalty # You can adjust the coefficient (0.01) as needed + ) + + # target reached + if self.waypoints.target_reached: + self.reward = 300.0 + + # advance the targets + self.waypoints.advance_targets() + + # update infos and dones + self.truncation |= self.waypoints.all_targets_reached + self.info["env_complete"] = self.waypoints.all_targets_reached + self.info["num_targets_reached"] = self.waypoints.num_targets_reached diff --git a/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_waypoints_env.py b/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_waypoints_env.py new file mode 100644 index 00000000..e9001b4d --- /dev/null +++ b/PyFlyt/gym_envs/quadx_envs/quadx_envs/quadx_waypoints_env.py @@ -0,0 +1,204 @@ +"""QuadX Waypoints Environment.""" + +from __future__ import annotations + +from typing import Any, Literal + +import numpy as np +from gymnasium import spaces + +from PyFlyt.gym_envs.quadx_envs.quadx_base_env import QuadXBaseEnv +from PyFlyt.gym_envs.utils.waypoint_handler import WaypointHandler + + +class QuadXWaypointsEnv(QuadXBaseEnv): + """QuadX Waypoints Environment. + + Actions are vp, vq, vr, T, ie: angular rates and thrust. + The target is a set of `[x, y, z, (optional) yaw]` waypoints in space. + + Args: + sparse_reward (bool): whether to use sparse rewards or not. + num_targets (int): number of waypoints in the environment. + use_yaw_targets (bool): whether to match yaw targets before a waypoint is considered reached. + goal_reach_distance (float): distance to the waypoints for it to be considered reached. + goal_reach_angle (float): angle in radians to the waypoints for it to be considered reached, only in effect if `use_yaw_targets` is used. + flight_mode (int): the flight mode of the UAV. + flight_dome_size (float): size of the allowable flying area. + max_duration_seconds (float): maximum simulation time of the environment. + angle_representation (Literal["euler", "quaternion"]): can be "euler" or "quaternion". + agent_hz (int): looprate of the agent to environment interaction. + render_mode (None | Literal["human", "rgb_array"]): render_mode + render_resolution (tuple[int, int]): render_resolution. + + """ + + def __init__( + self, + sparse_reward: bool = False, + num_targets: int = 4, + use_yaw_targets: bool = False, + goal_reach_distance: float = 0.2, + goal_reach_angle: float = 0.1, + flight_mode: int = 0, + flight_dome_size: float = 5.0, + max_duration_seconds: float = 10.0, + angle_representation: Literal["euler", "quaternion"] = "quaternion", + agent_hz: int = 30, + render_mode: None | Literal["human", "rgb_array"] = None, + render_resolution: tuple[int, int] = (480, 480), + ): + """__init__. + + Args: + sparse_reward (bool): whether to use sparse rewards or not. + num_targets (int): number of waypoints in the environment. + use_yaw_targets (bool): whether to match yaw targets before a waypoint is considered reached. + goal_reach_distance (float): distance to the waypoints for it to be considered reached. + goal_reach_angle (float): angle in radians to the waypoints for it to be considered reached, only in effect if `use_yaw_targets` is used. + flight_mode (int): the flight mode of the UAV. + flight_dome_size (float): size of the allowable flying area. + max_duration_seconds (float): maximum simulation time of the environment. + angle_representation (Literal["euler", "quaternion"]): can be "euler" or "quaternion". + agent_hz (int): looprate of the agent to environment interaction. + render_mode (None | Literal["human", "rgb_array"]): render_mode + render_resolution (tuple[int, int]): render_resolution. + + """ + super().__init__( + start_pos=np.array([[0.0, 0.0, 1.0]]), + flight_mode=flight_mode, + flight_dome_size=flight_dome_size, + max_duration_seconds=max_duration_seconds, + angle_representation=angle_representation, + agent_hz=agent_hz, + render_mode=render_mode, + render_resolution=render_resolution, + ) + + # define waypoints + self.waypoints = WaypointHandler( + enable_render=self.render_mode is not None, + num_targets=num_targets, + use_yaw_targets=use_yaw_targets, + goal_reach_distance=goal_reach_distance, + goal_reach_angle=goal_reach_angle, + flight_dome_size=flight_dome_size, + min_height=0.1, + np_random=self.np_random, + ) + + # Define observation space + self.observation_space = spaces.Dict( + { + "attitude": self.combined_space, + "target_deltas": spaces.Sequence( + space=spaces.Box( + low=-2 * flight_dome_size, + high=2 * flight_dome_size, + shape=(4,) if use_yaw_targets else (3,), + dtype=np.float64, + ), + stack=True, + ), + } + ) + + """ ENVIRONMENT CONSTANTS """ + self.sparse_reward = sparse_reward + + def reset( + self, *, seed: None | int = None, options: None | dict[str, Any] = dict() + ) -> tuple[dict[Literal["attitude", "target_deltas"], np.ndarray], dict]: + """Resets the environment. + + Args: + seed: seed to pass to the base environment. + options: None + + """ + super().begin_reset(seed, options) + self.waypoints.reset(self.env, self.np_random) + self.info["num_targets_reached"] = 0 + super().end_reset() + + return self.state, self.info.copy() + + def compute_state(self) -> None: + """Computes the state of the current timestep. + + This returns the observation as well as the distances to target. + - "attitude" (Box) + ----- ang_vel (vector of 3 values) + ----- ang_pos (vector of 3/4 values) + ----- lin_vel (vector of 3 values) + ----- lin_pos (vector of 3 values) + ----- previous_action (vector of 4 values) + ----- auxiliary information (vector of 4 values) + - "target_deltas" (Sequence) + ----- list of body_frame distances to target (vector of 3/4 values) + """ + ang_vel, ang_pos, lin_vel, lin_pos, quaternion = super().compute_attitude() + aux_state = super().compute_auxiliary() + + # combine everything + new_state: dict[Literal["attitude", "target_deltas"], np.ndarray] = dict() + if self.angle_representation == 0: + new_state["attitude"] = np.concatenate( + [ + ang_vel, + ang_pos, + lin_vel, + lin_pos, + self.action, + aux_state, + ], + axis=-1, + ) + elif self.angle_representation == 1: + new_state["attitude"] = np.concatenate( + [ + ang_vel, + quaternion, + lin_vel, + lin_pos, + self.action, + aux_state, + ], + axis=-1, + ) + + new_state["target_deltas"] = self.waypoints.distance_to_targets( + ang_pos, lin_pos, quaternion + ) + + self.state: dict[Literal["attitude", "target_deltas"], np.ndarray] = new_state + + def compute_term_trunc_reward(self) -> None: + """Computes the termination, truncation, and reward of the current timestep.""" + super().compute_base_term_trunc_reward() + + # bonus reward if we are not sparse + if not self.sparse_reward: + self.reward += max(3.0 * self.waypoints.progress_to_next_target, 0.0) + self.reward += 0.1 / self.waypoints.distance_to_next_target + # Negative Reward For High Yaw rate, To prevent high yaw while training + yaw_rate = abs( + self.env.state(0)[0][2] + ) # Assuming z-axis is the last component + yaw_rate_penalty = 0.01 * yaw_rate**2 # Add penalty for high yaw rate + self.reward -= ( + yaw_rate_penalty # You can adjust the coefficient (0.01) as needed + ) + + # target reached + if self.waypoints.target_reached: + self.reward = 100.0 + + # advance the targets + self.waypoints.advance_targets() + + # update infos and dones + self.truncation |= self.waypoints.all_targets_reached + self.info["env_complete"] = self.waypoints.all_targets_reached + self.info["num_targets_reached"] = self.waypoints.num_targets_reached diff --git a/PyFlyt/gym_envs/rocket_envs/rocket_base_env.py b/PyFlyt/gym_envs/rocket_envs/rocket_base_env.py index 5a0f7c06..e26785a2 100644 --- a/PyFlyt/gym_envs/rocket_envs/rocket_base_env.py +++ b/PyFlyt/gym_envs/rocket_envs/rocket_base_env.py @@ -367,7 +367,13 @@ def step(self, action: np.ndarray): rgbaColor=self.ignition_color, ) - return self.state, self.reward, self.termination, self.truncation, self.info + return ( + self.state, + self.reward, + self.termination, + self.truncation, + self.info.copy(), + ) def render(self): """Render.""" diff --git a/PyFlyt/gym_envs/rocket_envs/rocket_landing_env.py b/PyFlyt/gym_envs/rocket_envs/rocket_landing_env.py index d701cb81..ba42ea56 100644 --- a/PyFlyt/gym_envs/rocket_envs/rocket_landing_env.py +++ b/PyFlyt/gym_envs/rocket_envs/rocket_landing_env.py @@ -124,7 +124,7 @@ def reset( super().end_reset(seed, options) - return self.state, self.info + return self.state, self.info.copy() def compute_state(self) -> None: """Computes the state of the current timestep. diff --git a/tests/test_gym_envs.py b/tests/test_gym_envs.py index 3d3eb3b5..a467514d 100644 --- a/tests/test_gym_envs.py +++ b/tests/test_gym_envs.py @@ -112,6 +112,27 @@ def test_seeding(env_config): env_2.close() +@pytest.mark.parametrize("env_config", _ALL_ENV_CONFIGS) +def test_infos_not_shared(env_config): + """Test that each reset and step returns its own info dict, so kept infos don't change.""" + env = gym.make(env_config[0], **env_config[1]) + + _, info = env.reset(seed=42) + infos = [info] + snapshots = [dict(info)] + for _ in range(100): + _, _, term, trunc, info = env.step(env.action_space.sample()) + infos.append(info) + snapshots.append(dict(info)) + if term or trunc: + break + + assert len({id(info) for info in infos}) == len(infos) + assert infos == snapshots + + env.close() + + @pytest.mark.parametrize("env_config", _WAYPOINT_ENV_CONFIGS) @pytest.mark.parametrize("context_length", [2, 8]) def test_flatten_env(env_config, context_length):