### MAQuadXHoverEnvV2 - Usage Example Source: https://github.com/jjshoots/pyflyt/blob/master/docs/documentation/pz_envs/ma_quadx_hover_env.html Demonstrates how to initialize and use the MAQuadXHoverEnvV2 environment, including resetting and stepping through the environment. ```APIDOC ## Usage ### Method ```python from PyFlyt.pz_envs import MAQuadXHoverEnvV2 env = MAQuadXHoverEnvV2(render_mode="human") observations, infos = env.reset() while env.agents: # This is where you would insert your policy actions = {agent: env.action_space(agent).sample() for agent in env.agents} observations, rewards, terminations, truncations, infos = env.step(actions) env.close() ``` ``` -------------------------------- ### Install Git hooks Source: https://github.com/jjshoots/pyflyt/blob/master/CONTRIBUTING.md Initialize pre-commit hooks in the local repository. ```shell pre-commit install ``` -------------------------------- ### Initialize PettingZoo Environment Source: https://github.com/jjshoots/pyflyt/blob/master/readme.md Standard setup for a multi-agent PettingZoo environment. ```python from PyFlyt.pz_envs import MAFixedwingDogfightEnv env = MAFixedwingDogfightEnv(render_mode="human") observations, infos = env.reset() while env.agents: # this is where you would insert your policy actions = {agent: env.action_space(agent).sample() for agent in env.agents} observations, rewards, terminations, truncations, infos = env.step(actions) env.close() ``` -------------------------------- ### Install project dependencies Source: https://github.com/jjshoots/pyflyt/blob/master/docs_source/readme.md Use pip to install all required packages listed in the requirements file. ```sh pip3 install -r requirements.txt ``` -------------------------------- ### Multi-Drone Setup with Aviary Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation/core/aviary.md.txt Spawn multiple drones with different types and options by providing lists for 'drone_type' and 'drone_options'. This example sets up three drones with distinct configurations and control modes. ```python # the starting position and orientations start_pos = np.array([[0.0, 5.0, 5.0], [3.0, 3.0, 1.0], [5.0, 0.0, 1.0]]) start_orn = np.zeros_like(start_pos) # spawn different types of drones drone_type = ["rocket", "quadx", "fixedwing"] # individual spawn options for each drone rocket_options = dict() quadx_options = dict(use_camera=True, drone_model="primitive_drone") fixedwing_options = dict(starting_velocity=np.array([0.0, 0.0, 0.0])) drone_options = [rocket_options, quadx_options, fixedwing_options] # environment setup env = Aviary( start_pos=start_pos, start_orn=start_orn, render=True, drone_type=drone_type, drone_options=drone_options, ) # set quadx to position control, rocket and fixedwing as nothing env.set_mode([0, 7, 0]) # simulate for 1000 steps (1000/120 ~= 8 seconds) for i in range(1000): env.step() ``` -------------------------------- ### QuadX-Pole-Balance-v3 Usage Source: https://github.com/jjshoots/pyflyt/blob/master/docs_source/documentation/gym_envs/quadx_pole_balance_env.md Example of how to initialize and use the QuadX-Pole-Balance-v3 environment with Gymnasium. ```APIDOC ## PyFlyt/QuadX-Pole-Balance-v3 Usage ### Description This section provides a Python code example demonstrating how to import, initialize, and interact with the `QuadX-Pole-Balance-v3` environment using the Gymnasium library. ### Code Example ```python import gymnasium import PyFlyt.gym_envs env = gymnasium.make("PyFlyt/QuadX-Pole-Balance-v3", render_mode="human") term, trunc = False, False obs, _ = env.reset() while not (term or trunc): obs, rew, term, trunc, _ = env.step(env.action_space.sample()) ``` ``` -------------------------------- ### Install documentation requirements Source: https://github.com/jjshoots/pyflyt/blob/master/CONTRIBUTING.md Install dependencies required for building the project documentation. ```shell cd docs_source pip install -r requirements.txt ``` -------------------------------- ### MAQuadXHoverEnvV2 Environment Setup and Usage Source: https://github.com/jjshoots/pyflyt/blob/master/docs_source/documentation/pz_envs/ma_quadx_hover_env.md Demonstrates how to initialize and use the MAQuadXHoverEnvV2 environment for multi-agent hovering simulations. ```APIDOC ## MAQuadXHoverEnvV2 Environment ### Description The MAQuadXHoverEnvV2 environment is designed for multi-agent drone simulations where the objective is for all agents to hover at their initial positions for an extended duration. ### Usage Example ```python from PyFlyt.pz_envs import MAQuadXHoverEnvV2 env = MAQuadXHoverEnvV2(render_mode="human") observations, infos = env.reset() while env.agents: # Replace with your agent's policy actions = {agent: env.action_space(agent).sample() for agent in env.agents} observations, rewards, terminations, truncations, infos = env.step(actions) env.close() ``` ### Environment Options * class `PyFlyt.pz_envs.quadx_envs.ma_quadx_hover_env.MAQuadXHoverEnv` Simple Multiagent Hover Environment. Actions are vp, vq, vr, T, ie: angular rates and thrust. The target is for each agent to not crash for the longest time possible. #### Parameters - **start_pos** (np.ndarray) - Optional - An (num_drones x 3) numpy array specifying the starting positions of each agent. - **start_orn** (np.ndarray) - Optional - An (num_drones x 3) numpy array specifying the starting orientations of each agent. - **sparse_reward** (bool) - Optional - Whether to use sparse rewards or not. - **flight_mode** (int) - Optional - The flight mode of all UAVs. - **flight_dome_size** (float) - Optional - Size of the allowable flying area. - **max_duration_seconds** (float) - Optional - Maximum simulation time of the environment. - **angle_representation** (Literal['euler', 'quaternion']) - Optional - Can be “euler” or “quaternion”. Defaults to 'quaternion'. - **agent_hz** (int) - Optional - Looprate of the agent to environment interaction. - **render_mode** (None | str) - Optional - Can be “human” or None. Defaults to None. ``` -------------------------------- ### Basic Environment Usage Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation/gym_envs/quadx_pole_waypoints_env.md.txt Demonstrates how to initialize and interact with the QuadX-Pole-Waypoints-v3 environment using Gymnasium. This is the standard way to start using the environment for training or simulation. ```python import gymnasium import PyFlyt.gym_envs env = gymnasium.make("PyFlyt/QuadX-Pole-Waypoints-v3", render_mode="human") term, trunc = False, False obs, _ = env.reset() while not (term or trunc): obs, rew, term, trunc, _ = env.step(env.action_space.sample()) ``` -------------------------------- ### Install development dependencies Source: https://github.com/jjshoots/pyflyt/blob/master/CONTRIBUTING.md Install the project in editable mode with development dependencies. ```shell pip3 install -e .[dev] ``` -------------------------------- ### Install PyFlyt via pip Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation.md.txt Standard installation command for Linux, MacOS, and Windows. Ensure numpy and wheel are installed first to support pybullet build requirements. ```sh pip3 install wheel numpy pip3 install pyflyt ``` -------------------------------- ### Configure Multi-Drone Looprates Source: https://github.com/jjshoots/pyflyt/blob/master/docs/documentation/core/aviary.html Examples of valid and invalid looprate configurations for multi-drone setups. Each subsequent looprate must be a round multiple of the previous one when sorted. ```python drone_options = [] drone_options.append(dict(control_hz=60)) drone_options.append(dict(control_hz=30)) drone_options.append(dict(control_hz=120)) ``` ```python drone_options = [] drone_options.append(dict(control_hz=40)) drone_options.append(dict(control_hz=30)) drone_options.append(dict(control_hz=120)) ``` -------------------------------- ### Interact with QuadX-Hover Environment Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation/gym_envs/quadx_hover_env.md.txt Example of how to initialize and step through the QuadX-Hover-v2 environment using Gymnasium. Ensure PyFlyt.gym_envs is imported. ```python import gymnasium import PyFlyt.gym_envs env = gymnasium.make("PyFlyt/QuadX-Hover-v2", render_mode="human") term, trunc = False, False obs, _ = env.reset() while not (term or trunc): obs, rew, term, trunc, _ = env.step(env.action_space.sample()) ``` -------------------------------- ### Implement a Custom Drone Class Source: https://github.com/jjshoots/pyflyt/blob/master/docs_source/documentation/core/abstractions/base_drone.md Example of how to initialize a custom drone by inheriting from DroneClass and loading parameters from a YAML file. ```pycon >>> def __init__( >>> self, >>> p: bullet_client.BulletClient, >>> start_pos: np.ndarray, >>> start_orn: np.ndarray, >>> control_hz: int = 120, >>> physics_hz: int = 240, >>> drone_model: str = "rocket_brick", >>> model_dir: None | str = os.path.dirname(os.path.realpath(__file__)), >>> np_random: None | np.random.Generator = None, >>> use_camera: bool = False, >>> use_gimbal: bool = False, >>> camera_angle_degrees: int = 0, >>> camera_FOV_degrees: int = 90, >>> camera_resolution: tuple[int, int] = (128, 128), >>> ): >>> super().__init__( >>> p=p, >>> start_pos=start_pos, >>> start_orn=start_orn, >>> control_hz=control_hz, >>> physics_hz=physics_hz, >>> model_dir=model_dir, >>> drone_model=drone_model, >>> np_random=np_random, >>> ) >>> with open(self.param_path, "rb") as f: >>> # load all params from yaml into components >>> all_params = yaml.safe_load(f) >>> >>> self.lifting_surfaces = LiftingSurfaces(...) >>> self.boosters = Boosters(...) >>> >>> self.use_camera = use_camera >>> if self.use_camera: >>> self.camera = Camera(...) ``` -------------------------------- ### Rocket Landing Environment Usage Source: https://github.com/jjshoots/pyflyt/blob/master/docs_source/documentation/gym_envs/rocket_landing_env.md Example of how to initialize and use the Rocket Landing environment in Gymnasium. ```APIDOC ## Usage ```python import gymnasium import PyFlyt.gym_envs env = gymnasium.make("PyFlyt/Rocket-Landing-v4", render_mode="human") term, trunc = False, False obs, _ = env.reset() while not (term or trunc): obs, rew, term, trunc, _ = env.step(env.action_space.sample()) ``` ``` -------------------------------- ### Core Aviary API Example Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation/core/aviary.md.txt Instantiate the Aviary environment, set a drone's mode and setpoint, step the simulation, and gracefully close the environment. Requires numpy and Aviary import. ```python import numpy as np from PyFlyt.core import Aviary # Step 2: define starting positions and orientations start_pos = np.array([[0.0, 0.0, 1.0]]) start_orn = np.array([[0.0, 0.0, 0.0]]) # Step 3: instantiate aviary env = Aviary(start_pos=start_pos, start_orn=start_orn, render=True, drone_type="quadx") # Step 4: (Optional) define control mode to use for drone env.set_mode(7) # Step 5: (Optional) define a setpoint for the first drone (at index 0) in the aviary setpoint = np.array([1.0, 0.0, 0.0, 1.0]) env.set_setpoint(0, setpoint) # Step 6: step the physics for i in range(1000): env.step() # Gracefully close env.close() ``` -------------------------------- ### Initialize Custom Drone Class Source: https://github.com/jjshoots/pyflyt/blob/master/docs/documentation/core/abstractions/base_drone.html Example constructor signature for a class inheriting from the base DroneClass, demonstrating the required parameters for physics and model configuration. ```python >>> def __init__( >>> self, >>> p: bullet_client.BulletClient, >>> start_pos: np.ndarray, >>> start_orn: np.ndarray, >>> control_hz: int = 120, >>> physics_hz: int = 240, >>> drone_model: str = "rocket_brick", >>> model_dir: None | str = os.path.dirname(os.path.realpath(__file__)), >>> np_random: None | np.random.Generator = None, >>> use_camera: bool = False, ``` -------------------------------- ### Setup Multi-Drone Environment Source: https://github.com/jjshoots/pyflyt/blob/master/docs_source/documentation/core/aviary.md Spawns multiple drones with unique types and configurations by passing lists to the Aviary constructor. ```python ... # the starting position and orientations start_pos = np.array([[0.0, 5.0, 5.0], [3.0, 3.0, 1.0], [5.0, 0.0, 1.0]]) start_orn = np.zeros_like(start_pos) # spawn different types of drones drone_type = ["rocket", "quadx", "fixedwing"] # individual spawn options for each drone rocket_options = dict() quadx_options = dict(use_camera=True, drone_model="primitive_drone") fixedwing_options = dict(starting_velocity=np.array([0.0, 0.0, 0.0])) drone_options = [rocket_options, quadx_options, fixedwing_options] # environment setup env = Aviary( start_pos=start_pos, start_orn=start_orn, render=True, drone_type=drone_type, drone_options=drone_options, ) # set quadx to position control, rocket and fixedwing as nothing env.set_mode([0, 7, 0]) # simulate for 1000 steps (1000/120 ~= 8 seconds) for i in range(1000): env.step() ``` -------------------------------- ### Initialize Fixedwing Aircraft Simulation Source: https://context7.com/jjshoots/pyflyt/llms.txt Initializes a fixed-wing aircraft simulation with a specified starting position, orientation, and drone options including a chase camera. Use this to set up a new fixed-wing flight simulation. ```python import numpy as np from PyFlyt.core import Aviary # Create fixed-wing aircraft simulation env = Aviary( start_pos=np.array([[0.0, 0.0, 50.0]]), # Start at altitude start_orn=np.array([[0.0, 0.0, 0.0]]), drone_type="fixedwing", drone_options={ "starting_velocity": np.array([20.0, 0.0, 0.0]), # Initial forward speed "use_camera": True, "camera_position_offset": np.array([-3.0, 0.0, 1.0]), # Chase camera }, render=True, ) # Flight modes for Fixedwing: # Mode -1: Direct surface control [LeftAil, RightAil, HorTail, VertTail, MainWing, Thrust] # Mode 0: Assisted control [Pitch, Roll, Yaw, Thrust] # Use assisted mode env.set_mode(0) # Fly a simple pattern for step in range(1000): t = step / 100.0 # Setpoint: [pitch, roll, yaw, thrust] # Positive pitch = nose up, positive roll = right wing down setpoint = np.array([ 0.1 * np.sin(t), # Gentle pitch oscillation 0.2 * np.sin(t/2), # Roll oscillation 0.0, # No yaw command 0.7, # 70% thrust ]) env.set_setpoint(0, setpoint) env.step() # Get aircraft state state = env.state(0) airspeed = np.linalg.norm(state[2]) # Body frame velocity magnitude altitude = state[3][2] print(f"Airspeed: {airspeed:.1f} m/s, Altitude: {altitude:.1f} m") ``` -------------------------------- ### Initialize and Run MAQuadXHoverEnvV2 Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation/pz_envs/ma_quadx_hover_env.md.txt Demonstrates the basic lifecycle of the environment, including initialization, resetting, and the agent-based step loop. ```python from PyFlyt.pz_envs import MAQuadXHoverEnvV2 env = MAQuadXHoverEnvV2(render_mode="human") observations, infos = env.reset() while env.agents: # this is where you would insert your policy actions = {agent: env.action_space(agent).sample() for agent in env.agents} observations, rewards, terminations, truncations, infos = env.step(actions) env.close() ``` -------------------------------- ### Gymnasium Environment Initialization Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation/gym_envs/quadx_hover_env.md.txt How to instantiate and run the QuadX-Hover-v3 environment. ```APIDOC ## GET PyFlyt/QuadX-Hover-v3 ### Description Initializes the quadrotor drone environment for the hovering task. ### Method GET (via gymnasium.make) ### Endpoint PyFlyt/QuadX-Hover-v2 ### Request Example import gymnasium import PyFlyt.gym_envs env = gymnasium.make("PyFlyt/QuadX-Hover-v2", render_mode="human") ### Response Returns a Gymnasium environment object configured for the QuadX-Hover task. ``` -------------------------------- ### Initialize and Run Rocket-Landing-v4 Environment Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation/gym_envs/rocket_landing_env.md.txt Demonstrates how to instantiate the environment using Gymnasium and execute a basic control loop with random actions. ```python import gymnasium import PyFlyt.gym_envs env = gymnasium.make("PyFlyt/Rocket-Landing-v4", render_mode="human") term, trunc = False, False obs, _ = env.reset() while not (term or trunc): obs, rew, term, trunc, _ = env.step(env.action_space.sample()) ``` -------------------------------- ### Configure QuadX with Onboard Camera Source: https://context7.com/jjshoots/pyflyt/llms.txt Shows how to initialize a QuadX drone with camera options enabled and access visual sensor data during simulation. ```python import numpy as np from PyFlyt.core import Aviary # Create environment with camera-equipped quadcopter env = Aviary( start_pos=np.array([[0.0, 0.0, 1.0]]), start_orn=np.array([[0.0, 0.0, 0.0]]), drone_type="quadx", drone_options={ "use_camera": True, "camera_resolution": (128, 128), "camera_FOV_degrees": 90, "camera_angle_degrees": 20, "camera_fps": 30, "use_gimbal": True, # Horizon-locked camera }, render=True, ) # Available flight modes for QuadX: # Mode -1: Direct motor PWM [m1, m2, m3, m4] # Mode 0: Angular velocity + Thrust [vp, vq, vr, T] # Mode 1: Angular position + Vertical velocity [p, q, r, vz] # Mode 2: Angular velocity + Altitude [vp, vq, vr, z] # Mode 3: Angular position + Altitude [p, q, r, z] # Mode 4: Local velocity + Yaw rate + Altitude [u, v, vr, z] # Mode 5: Local velocity + Yaw rate + Vertical velocity [u, v, vr, vz] # Mode 6: Ground velocity + Yaw rate + Vertical velocity [vx, vy, vr, vz] # Mode 7: Position hold [x, y, yaw, z] # Set to angular velocity control mode env.set_mode(0) env.set_setpoint(0, np.array([0.0, 0.0, 0.5, 0.6])) # Yaw right with 60% thrust for _ in range(200): env.step() # Access camera images drone = env.drones[0] if drone.use_camera: rgba_img = drone.rgbaImg # (128, 128, 4) RGBA image depth_img = drone.depthImg # (128, 128, 1) depth map seg_img = drone.segImg # (128, 128, 1) segmentation mask ``` -------------------------------- ### Initialize QuadX-Pole-Waypoints-v3 Source: https://github.com/jjshoots/pyflyt/blob/master/docs_source/documentation/gym_envs/quadx_pole_waypoints_env.md How to instantiate the environment using Gymnasium and perform a basic simulation loop. ```APIDOC ## Gymnasium Environment Initialization ### Description Instantiates the QuadX-Pole-Waypoints-v3 environment and runs a standard simulation loop. ### Request Example ```python import gymnasium import PyFlyt.gym_envs env = gymnasium.make("PyFlyt/QuadX-Pole-Waypoints-v3", render_mode="human") term, trunc = False, False obs, _ = env.reset() while not (term or trunc): obs, rew, term, trunc, _ = env.step(env.action_space.sample()) ``` ``` -------------------------------- ### GET get_states() Source: https://github.com/jjshoots/pyflyt/blob/master/docs_source/documentation/core/abstractions/boosters.md Retrieves the current state of all booster components. ```APIDOC ## GET get_states() ### Description Gets the current state of the components, returning an array containing ignition states, fuel ratios, and throttle states. ### Returns - **ndarray** - A (3 * num_boosters, ) array where (a0...an) is ignition, (b0...bn) is fuel ratio, and (c0...cn) is throttle state. ``` -------------------------------- ### Initialize and Use QuadX-Pole-Balance-v3 Environment Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation/gym_envs/quadx_pole_balance_env.md.txt Demonstrates how to create an instance of the QuadX-Pole-Balance-v3 environment using Gymnasium and interact with it by sampling random actions. Ensure PyFlyt.gym_envs is imported. ```python import gymnasium import PyFlyt.gym_envs env = gymnasium.make("PyFlyt/QuadX-Pole-Balance-v3", render_mode="human") term, trunc = False, False obs, _ = env.reset() while not (term or trunc): obs, rew, term, trunc, _ = env.step(env.action_space.sample()) ``` -------------------------------- ### GET /motors/states Source: https://github.com/jjshoots/pyflyt/blob/master/docs/documentation/core/abstractions/motors.html Retrieves the current throttle level for each motor. ```APIDOC ## GET /motors/states ### Description Gets the current state of the motor components. ### Response #### Success Response (200) - **states** (np.ndarray) - An (num_motors,) array representing the current throttle level of each motor. ``` -------------------------------- ### Build documentation Source: https://github.com/jjshoots/pyflyt/blob/master/CONTRIBUTING.md Execute the build script to generate project documentation. ```shell ./build_docs.sh ``` -------------------------------- ### Gymnasium Environment Initialization Source: https://github.com/jjshoots/pyflyt/blob/master/docs/documentation/gym_envs/quadx_pole_balance_env.html How to initialize and run the QuadX-Pole-Balance-v3 environment using the Gymnasium interface. ```APIDOC ## Gymnasium Environment: PyFlyt/QuadX-Pole-Balance-v3 ### Description The goal of this environment is to hover a quadrotor drone for as long as possible while balancing a 1 meter long pole. Actions are direct motor PWM commands. ### Usage ```python import gymnasium import PyFlyt.gym_envs env = gymnasium.make("PyFlyt/QuadX-Pole-Balance-v3", render_mode="human") term, trunc = False, False obs, _ = env.reset() while not (term or trunc): obs, rew, term, trunc, _ = env.step(env.action_space.sample()) ``` ### Environment Parameters - **sparse_reward** (bool) - Optional - Whether to use sparse rewards. - **flight_mode** (int) - Optional - The flight mode of the UAV. - **flight_dome_size** (float) - Optional - Size of the allowable flying area. - **max_duration_seconds** (float) - Optional - Maximum simulation time of the environment. - **angle_representation** (Literal['euler', 'quaternion']) - Optional - Representation of angles. - **agent_hz** (int) - Optional - Frequency of the agent. - **render_mode** (None | Literal['human', 'rgb_array']) - Optional - Rendering mode. - **render_resolution** (tuple[int, int]) - Optional - Resolution for rendering. ``` -------------------------------- ### Initialize and Use a PyFlyt Gymnasium Environment Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation/gym_envs.md.txt Demonstrates how to make a PyFlyt Gymnasium environment and interact with it using a basic RL loop. Ensure PyFlyt.gym_envs is imported. ```python import gymnasium import PyFlyt.gym_envs # noqa env = gymnasium.make("PyFlyt/QuadX-Hover-v2", render_mode="human") obs = env.reset() termination = False truncation = False while not termination or truncation: observation, reward, termination, truncation, info = env.step(env.action_space.sample()) ``` -------------------------------- ### Define Valid Multi-Drone Looprates Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation/core/aviary.md.txt Example of a valid configuration where control looprates are multiples of each other. ```python ... drone_options = [] drone_options.append(dict(control_hz=60)) drone_options.append(dict(control_hz=30)) drone_options.append(dict(control_hz=120)) ... ``` -------------------------------- ### Initialize and Run PyFlyt Aviary Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation/core.md.txt Demonstrates the standard workflow for spawning drones, setting flight modes, and stepping the physics simulation. ```python """Spawn a single drone on x=0, y=0, z=1, with 0 rpy.""" # Step 1: import things import numpy as np from PyFlyt.core import Aviary # Step 2: define starting positions and orientations start_pos = np.array([[0.0, 0.0, 1.0]]) start_orn = np.array([[0.0, 0.0, 0.0]]) # Step 3: instantiate aviary env = Aviary(start_pos=start_pos, start_orn=start_orn, render=True, drone_type="quadx") # Step 4: (Optional) define control mode to use for drone env.set_mode(7) # Step 5: (Optional) define a setpoint for the first drone (at index 0) in the aviary setpoint = np.array([1.0, 0.0, 0.0, 1.0]) env.set_setpoint(0, setpoint) # Step 6: step the physics for i in range(1000): env.step() # Gracefully close env.close() ``` -------------------------------- ### Initialize and Run QuadX Waypoints Environment Source: https://context7.com/jjshoots/pyflyt/llms.txt Sets up a QuadX drone to navigate through waypoints using the Gymnasium API. ```python env = gymnasium.make( "PyFlyt/QuadX-Waypoints-v4", render_mode="human", num_targets=4, use_yaw_targets=False, goal_reach_distance=0.2, sparse_reward=False, ) obs, info = env.reset() # obs["attitude"]: drone state # obs["target_deltas"]: list of (x, y, z) distances to each waypoint while True: action = env.action_space.sample() obs, reward, terminated, truncated, info = env.step(action) print(f"Targets reached: {info.get('num_targets_reached', 0)}") if terminated or truncated: if info.get('env_complete', False): print("All waypoints reached!") break env.close() ``` -------------------------------- ### Fixedwing Variants and Properties Source: https://github.com/jjshoots/pyflyt/blob/master/docs_source/documentation/core/drones/fixedwing.md Details on the available Fixedwing drone models and its properties like starting velocity. ```APIDOC ## Fixedwing Variants and Properties ### Model Description Small tube-and-wing fixed wing UAV with a single motor (~2.5 Kg). ### Variants Two different models of the Fixedwing drone are provided. This option can be selected through the `drone_model` parameter during initialization. - `fixedwing` (default): The standard fixedwing model. - `acrowing`: A more aggressive aircraft with a higher thrust-to-weight ratio, larger flight and control surfaces, and a trailing edge flap. ### `starting_velocity` Property #### Description Reads the `fixedwing.yaml` file and loads the UAV parameters, including the starting velocity. #### Access This is a property that can be read after the Fixedwing instance is initialized. ``` -------------------------------- ### Gymnasium Environment Initialization Source: https://github.com/jjshoots/pyflyt/blob/master/docs/documentation/gym_envs/rocket_landing_env.html How to instantiate the Rocket Landing environment using the Gymnasium make function. ```APIDOC ## Gymnasium Environment Initialization ### Description Initializes the PyFlyt Rocket Landing environment for simulation. ### Method GET (via gymnasium.make) ### Endpoint PyFlyt/Rocket-Landing-v3 ### Request Example ```python import gymnasium import PyFlyt.gym_envs env = gymnasium.make("PyFlyt/Rocket-Landing-v4", render_mode="human") ``` ``` -------------------------------- ### Initialize and Run MAFixedwingDogfightEnvV2 Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation/pz_envs/ma_fixedwing_dogfight_env.md.txt Demonstrates how to initialize the MAFixedwingDogfightEnvV2 environment, reset it, and run a basic loop with random actions for each agent. Ensure the environment is closed after use. ```python from PyFlyt.pz_envs import MAFixedwingDogfightEnvV2 env = MAFixedwingDogfightEnvV2(render_mode="human") observations, infos = env.reset() while env.agents: # this is where you would insert your policy actions = {agent: env.action_space(agent).sample() for agent in env.agents} observations, rewards, terminations, truncations, infos = env.step(actions) env.close() ``` -------------------------------- ### Initialize and run a PettingZoo environment Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation/pz_envs.md.txt Demonstrates the standard initialization and interaction loop for a PyFlyt PettingZoo environment. ```python from PyFlyt.pz_envs import MAQuadXHoverEnv env = MAQuadXHoverEnv(render_mode="human") observations, infos = env.reset(seed=42) while env.agents: # this is where you would insert your policy actions = {agent: env.action_space(agent).sample() for agent in env.agents} observations, rewards, terminations, truncations, infos = env.step(actions) env.close() ``` -------------------------------- ### Get Joint Information Source: https://github.com/jjshoots/pyflyt/blob/master/docs/documentation/core/abstractions/base_drone.html A debugging function to display all joint IDs and names as defined in the drone's URDF file. ```python def get_joint_info(_self_) -> None: ``` -------------------------------- ### Define Invalid Multi-Drone Looprates Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation/core/aviary.md.txt Example of an invalid configuration where control looprates do not follow the required integer multiple relationship. ```python ... drone_options = [] drone_options.append(dict(control_hz=40)) drone_options.append(dict(control_hz=30)) drone_options.append(dict(control_hz=120)) ... ``` -------------------------------- ### Basic Environment Usage Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation/gym_envs/quadx_waypoints_env.md.txt Demonstrates how to initialize and interact with the QuadX-Waypoints-v3 environment using Gymnasium. This is the standard way to use the environment for training or simulation. ```python import gymnasium import PyFlyt.gym_envs env = gymnasium.make("PyFlyt/QuadX-Waypoints-v3", render_mode="human") term, trunc = False, False obs, _ = env.reset() while not (term or trunc): obs, rew, term, trunc, _ = env.step(env.action_space.sample()) ``` -------------------------------- ### Implement Custom Drone with PyFlyt Source: https://context7.com/jjshoots/pyflyt/llms.txt Define a custom drone by inheriting from DroneClass and implementing abstract methods. This example shows a 'CustomRocketBrick' with boosters. ```python import numpy as np import yaml import os from pybullet_utils import bullet_client from PyFlyt.core.abstractions.base_drone import DroneClass from PyFlyt.core.abstractions.boosters import Boosters from PyFlyt.core.abstractions.lifting_surfaces import LiftingSurface, LiftingSurfaces from PyFlyt import Aviary class CustomRocketBrick(DroneClass): """A simple custom rocket with boosters and fins.""" def __init__( self, p: bullet_client.BulletClient, start_pos: np.ndarray, start_orn: np.ndarray, control_hz: int = 120, physics_hz: int = 240, drone_model: str = "rocket_brick", model_dir: str = None, # Path to your URDF/YAML files np_random: np.random.Generator = None, ): super().__init__( p=p, start_pos=start_pos, start_orn=start_orn, control_hz=control_hz, physics_hz=physics_hz, model_dir=model_dir, drone_model=drone_model, np_random=np_random, ) # Load parameters from YAML with open(self.param_path, "rb") as f: params = yaml.safe_load(f) # Initialize boosters self.boosters = Boosters( p=self.p, physics_period=self.physics_period, np_random=self.np_random, uav_id=self.Id, booster_ids=np.array([0]), fueltank_ids=np.array([0]), tau=np.array([0.1]), total_fuel_mass=np.array([10.0]), max_fuel_rate=np.array([1.0]), max_inertia=np.array([[1.0, 1.0, 0.1]]), min_thrust=np.array([50.0]), max_thrust=np.array([200.0]), thrust_unit=np.array([[0.0, 0.0, 1.0]]), reignitable=np.array([True]), noise_ratio=np.array([0.01]), ) def reset(self): self.set_mode(0) self.setpoint = np.zeros(2) # [ignition, throttle] self.cmd = np.zeros(2) self.p.resetBasePositionAndOrientation( self.Id, self.start_pos, self.start_orn ) self.disable_artificial_damping() self.boosters.reset(starting_fuel_ratio=1.0) def set_mode(self, mode): self.mode = mode def update_control(self, physics_step: int): if physics_step % self.physics_control_ratio != 0: return self.cmd = self.setpoint def update_physics(self): self.boosters.physics_update( ignition=self.cmd[[0]], pwm=self.cmd[[1]], rotation=None, ) def update_state(self): lin_pos, ang_pos = self.p.getBasePositionAndOrientation(self.Id) lin_vel, ang_vel = self.p.getBaseVelocity(self.Id) rotation = np.array( self.p.getMatrixFromQuaternion(ang_pos) ).reshape(3, 3).T lin_vel = np.matmul(rotation, lin_vel) ang_vel = np.matmul(rotation, ang_vel) ang_pos = self.p.getEulerFromQuaternion(ang_pos) self.state = np.stack([ang_vel, ang_pos, lin_vel, lin_pos], axis=0) self.aux_state = self.boosters.get_states() def update_last(self, physics_step: int): pass # No camera updates # Register and use custom drone env = Aviary( start_pos=np.array([[0.0, 0.0, 10.0]]), start_orn=np.array([[0.0, 0.0, 0.0]]), drone_type="custom_rocket", drone_type_mappings={"custom_rocket": CustomRocketBrick}, drone_options={"model_dir": "/path/to/your/models"}, render=True, ) ``` -------------------------------- ### QuadX Hover Environment Usage Source: https://github.com/jjshoots/pyflyt/blob/master/docs_source/documentation/gym_envs/quadx_hover_env.md Demonstrates how to initialize and use the QuadX Hover environment with Gymnasium. ```APIDOC ## Usage ```python import gymnasium import PyFlyt.gym_envs env = gymnasium.make("PyFlyt/QuadX-Hover-v2", render_mode="human") term, trunc = False, False obs, _ = env.reset() while not (term or trunc): obs, rew, term, trunc, _ = env.step(env.action_space.sample()) ``` ``` -------------------------------- ### Setting Custom Drone Options in Aviary Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation/core/aviary.md.txt Use the 'drone_options' argument to pass custom instantiation parameters to specific drone types. For example, setting 'starting_velocity' for a 'fixedwing' drone. ```python # define the parameters for the underlying drone drone_options = dict() drone_options["starting_velocity"] = np.array([3.0, 0.0, 3.0]) # pass the relevant arguments to the `aviary` env = Aviary(..., drone_type="fixedwing", drone_options=drone_options) ``` -------------------------------- ### Using Preimplemented Wind Models Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation/core/wind.md.txt Demonstrates how to initialize the Aviary environment with a preimplemented wind model. ```APIDOC ## Using Preimplemented Wind Models ### Description Initialize the `Aviary` environment with a specified wind model type. ### Method Initialization of `Aviary` class. ### Endpoint N/A (Class Initialization) ### Request Example ```python env = Aviary(..., wind_type="Lorem Ipsum") ``` ### Response N/A ``` -------------------------------- ### Basic Usage Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation/gym_envs/fixedwing_waypoints_env.md.txt Demonstrates the fundamental steps to initialize and run the Fixedwing-Waypoints-v3 environment. ```APIDOC ## Basic Usage of Fixedwing-Waypoints-v3 ### Description This snippet shows how to import the environment, create an instance, and perform basic reset and step operations. ### Method N/A (Environment Initialization and Interaction) ### Endpoint N/A (Gymnasium Environment) ### Request Example ```python import gymnasium import PyFlyt.gym_envs env = gymnasium.make("PyFlyt/Fixedwing-Waypoints-v3", render_mode="human") term, trunc = False, False obs, _ = env.reset() while not (term or trunc): obs, rew, term, trunc, _ = env.step(env.action_space.sample()) ``` ### Response N/A (Environment interaction produces observations, rewards, and termination signals.) ``` -------------------------------- ### LiftingSurface Class Source: https://github.com/jjshoots/pyflyt/blob/master/docs/documentation/core/abstractions/lifting_surfaces.html Represents a single lifting surface with properties like drag coefficient, deflection limit, and actuation time constant. Provides methods to get states, update physics, and reset. ```APIDOC ## LiftingSurface Class ### Description Represents a single lifting surface with properties like drag coefficient, deflection limit, and actuation time constant. Provides methods to get states, update physics, and reset. ### Attributes * **Cd_0** (_float_) – drag coefficient at zero angle-of-attack. * **deflection_limit** (_float_) – maximum deflection limit of the actuated flap in degrees. * **tau** (_float_) – actuation ramp time constant. ### Methods #### get_states() Gets the current state of the components. Returns: the level of deflection of the surface. Return type: float #### physics_update(cmd: float) Converts a commanded actuation state into forces on the lifting surface. Parameters: * **cmd** (_float_) – normalized actuation in [-1, 1]. Returns: vec3 force, vec3 torque Return type: tuple[np.ndarray, np.ndarray] #### reset() Reset the lifting surfaces. #### state_update(surface_velocity: ndarray) Updates the local surface velocity of the lifting surface. Parameters: * **surface_velocity** (_np.ndarray_) – surface_velocity. ``` -------------------------------- ### Initialize Aviary with Custom Wind Field Source: https://github.com/jjshoots/pyflyt/blob/master/docs/documentation/core/wind.html Instantiate the Aviary environment, specifying the custom wind field class and any necessary options. This example overrides the default 'my_parameter' for the custom wind field. ```python env = Aviary(..., wind_type=MyWindField, wind_options=dict(my_parameter=1.2)) ``` -------------------------------- ### Configuring Drone Looprates in Aviary Source: https://github.com/jjshoots/pyflyt/blob/master/docs/_sources/documentation/core/aviary.md.txt Control looprates for individual drones using the 'drone_options' argument. This example shows how to set a custom looprate, though it's not recommended due to potential instability. ```python # define the parameters for the underlying drone drone_options = dict() drone_options["control_loop_rate_hz"] = 120 # pass the relevant arguments to the `aviary` env = Aviary(..., drone_options=drone_options) ``` -------------------------------- ### Reset Drone to Initial State Source: https://github.com/jjshoots/pyflyt/blob/master/docs/documentation/core/abstractions/base_drone.html Resets the vehicle to its initial state, including flight mode, setpoints, commands, position, orientation, and component states. This method is crucial for starting or restarting a simulation. ```python def reset(self): # set the flight mode and reset the setpoint and actuator command self.set_mode(0) self.setpoint = np.zeros(2) self.cmd = np.zeros(2) # reset the drone position and orientation and damping self.p.resetBasePositionAndOrientation(self.Id, self.start_pos, self.start_orn) self.disable_artificial_damping() # reset the components to their default states self.lifting_surfaces.reset() self.boosters.reset() ``` -------------------------------- ### QuadXHoverEnv Environment Options Source: https://github.com/jjshoots/pyflyt/blob/master/docs_source/documentation/gym_envs/quadx_hover_env.md Details the parameters available when initializing the QuadXHoverEnv. ```APIDOC ## Environment Options ### *class* PyFlyt.gym_envs.quadx_envs.quadx_hover_env.QuadXHoverEnv(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)) 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. * **Parameters:** * **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. ``` -------------------------------- ### Initialize DroneClass with Parameters Source: https://github.com/jjshoots/pyflyt/blob/master/docs/documentation/core/abstractions/base_drone.html Initializes the DroneClass, loading parameters from a YAML file and setting up components like lifting surfaces, boosters, and optionally a camera. ```python def __init__( self, use_camera: bool = False, use_gimbal: bool = False, camera_angle_degrees: int = 0, camera_FOV_degrees: int = 90, camera_resolution: tuple[int, int] = (128, 128), ): super().__init__( p=p, start_pos=start_pos, start_orn=start_orn, control_hz=control_hz, physics_hz=physics_hz, model_dir=model_dir, drone_model=drone_model, np_random=np_random, ) with open(self.param_path, "rb") as f: # load all params from yaml into components all_params = yaml.safe_load(f) self.lifting_surfaces = LiftingSurfaces(...) self.boosters = Boosters(...) self.use_camera = use_camera if self.use_camera: self.camera = Camera(...) ``` -------------------------------- ### Define a Complex Custom Wind Model using WindFieldClass Source: https://github.com/jjshoots/pyflyt/blob/master/docs_source/documentation/core/wind.md Illustrates creating a custom wind model by subclassing `WindFieldClass`. This example simulates a thermal windfield with customizable strength and adds random noise. ```python from PyFlyt.core import Aviary from PyFlyt.core.abstractions import WindFieldClass # define the wind field class MyWindField(WindFieldClass): def __init__(self, my_parameter=1.0, np_random: None | np.random.Generator = None): super().__init__(np_random) self.strength = my_parameter def __call__(self, time: float, position: np.ndarray): # simulate a thermal windfield, where the xy velocities are 0, wind = np.zeros_like(position) # but the z velocity varies to the log of height, wind[:, -1] = np.log(position[:, -1]) * self.strength # plus some noise, wind += self.np_random.randn(*wind.shape) return wind ``` ```python # environment setup, attach the windfield, override the parameter `my_parameter` from the default env = Aviary(..., wind_type=MyWindField, wind_options=dict(my_parameter=1.2)) ```