Upload 40 files
Browse filesUploading Hackathon files
- atc-openenv/Dockerfile +7 -0
- atc-openenv/README.md +206 -0
- atc-openenv/__pycache__/app.cpython-311.pyc +0 -0
- atc-openenv/__pycache__/runway_algorithm.cpython-311.pyc +0 -0
- atc-openenv/env/__init__.py +4 -0
- atc-openenv/env/__pycache__/__init__.cpython-311.pyc +0 -0
- atc-openenv/env/__pycache__/aircraft.cpython-311.pyc +0 -0
- atc-openenv/env/__pycache__/atc_env.cpython-311.pyc +0 -0
- atc-openenv/env/__pycache__/reward.cpython-311.pyc +0 -0
- atc-openenv/env/__pycache__/runway.cpython-311.pyc +0 -0
- atc-openenv/env/__pycache__/scheduler.cpython-311.pyc +0 -0
- atc-openenv/env/aircraft.py +64 -0
- atc-openenv/env/atc_env.py +383 -0
- atc-openenv/env/reward.py +60 -0
- atc-openenv/env/runway.py +51 -0
- atc-openenv/env/scheduler.py +104 -0
- atc-openenv/graders/__init__.py +1 -0
- atc-openenv/graders/__pycache__/__init__.cpython-311.pyc +0 -0
- atc-openenv/graders/__pycache__/grader1.cpython-311.pyc +0 -0
- atc-openenv/graders/__pycache__/grader2.cpython-311.pyc +0 -0
- atc-openenv/graders/__pycache__/grader3.cpython-311.pyc +0 -0
- atc-openenv/graders/grader1.py +33 -0
- atc-openenv/graders/grader2.py +56 -0
- atc-openenv/graders/grader3.py +44 -0
- atc-openenv/inference.py +446 -0
- atc-openenv/openenv.yaml +20 -0
- atc-openenv/pyproject.toml +24 -0
- atc-openenv/requirements.txt +9 -0
- atc-openenv/runway_algorithm.py +512 -0
- atc-openenv/server/app.py +67 -0
- atc-openenv/tasks/__init__.py +6 -0
- atc-openenv/tasks/__pycache__/__init__.cpython-311.pyc +0 -0
- atc-openenv/tasks/__pycache__/task1_clear_skies.cpython-311.pyc +0 -0
- atc-openenv/tasks/__pycache__/task2_fuel_pressure.cpython-311.pyc +0 -0
- atc-openenv/tasks/__pycache__/task3_full_emergency.cpython-311.pyc +0 -0
- atc-openenv/tasks/task1_clear_skies.py +59 -0
- atc-openenv/tasks/task2_fuel_pressure.py +86 -0
- atc-openenv/tasks/task3_full_emergency.py +145 -0
- atc-openenv/uv.lock +5 -0
- atc-openenv/visualizer.py +430 -0
atc-openenv/Dockerfile
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
WORKDIR /app
|
| 3 |
+
COPY requirements.txt .
|
| 4 |
+
RUN pip install -r requirements.txt
|
| 5 |
+
COPY . .
|
| 6 |
+
EXPOSE 7860
|
| 7 |
+
CMD ["uvicorn", "server.app:app", "--host", "0.0.0.0", "--port", "7860"]
|
atc-openenv/README.md
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ATC OpenEnv - Air Traffic Control Runway Sequencing Environment
|
| 2 |
+
---
|
| 3 |
+
title: ATC Agentic Inference
|
| 4 |
+
emoji: ✈️
|
| 5 |
+
colorFrom: blue
|
| 6 |
+
colorTo: indigo
|
| 7 |
+
sdk: docker
|
| 8 |
+
pinned: false
|
| 9 |
+
tags:
|
| 10 |
+
- openenv
|
| 11 |
+
---
|
| 12 |
+
# ATC Agent Hackathon Submission
|
| 13 |
+
This Space runs the inference script for the ATC environment.
|
| 14 |
+
Production-ready OpenEnv-compliant environment for AI agents to act as ATC sequencing controllers.
|
| 15 |
+
|
| 16 |
+
## Overview & Motivation
|
| 17 |
+
|
| 18 |
+
**ATC OpenEnv** is an Air Traffic Control sequencing environment simulator explicitly designed for AI agents. The primary motivation is to evaluate reinforcement learning and LLM-based agents in an operational safety-critical setting where delays cause compounding penalties and physical errors (like fuel starvation) lead to episode-terminating crashes.
|
| 19 |
+
|
| 20 |
+
An AI agent acts as the primary ATC sequencing controller, observing inbound flights and making continuous decisions on runway assignments, landing order, and flow expediting. This is a physics-grounded workflow simulation, capturing real ATC operational pressure.
|
| 21 |
+
|
| 22 |
+
## Observation Space
|
| 23 |
+
|
| 24 |
+
| Field | Type | Description |
|
| 25 |
+
|-------|------|-------------|
|
| 26 |
+
| aircraft | List[dict] | All aircraft in the sector |
|
| 27 |
+
| aircraft[].id | str | Unique aircraft identifier |
|
| 28 |
+
| aircraft[].aircraft_type | str | HEAVY, MEDIUM, or LIGHT |
|
| 29 |
+
| aircraft[].priority | str | NORMAL, FUEL_CRITICAL, or EMERGENCY |
|
| 30 |
+
| aircraft[].status | str | INBOUND, HOLDING, ASSIGNED, LANDING, LANDED |
|
| 31 |
+
| aircraft[].distance_nm | float | Distance to runway in nautical miles |
|
| 32 |
+
| aircraft[].speed_knots | float | Current speed in knots |
|
| 33 |
+
| aircraft[].fuel_remaining_min | float | Fuel remaining in minutes |
|
| 34 |
+
| aircraft[].assigned_runway | str | Assigned runway ID (if any) |
|
| 35 |
+
| aircraft[].sequence_position | int | Position in landing sequence |
|
| 36 |
+
| runways | List[dict] | All runways at the airport |
|
| 37 |
+
| runways[].id | str | Runway identifier |
|
| 38 |
+
| runways[].status | str | OPEN, REDUCED, or CLOSED |
|
| 39 |
+
| runways[].next_available_step | int | Step when runway is next available |
|
| 40 |
+
| runways[].current_occupant | str | Aircraft ID currently on runway |
|
| 41 |
+
| timestep | int | Current simulation step |
|
| 42 |
+
| new_arrivals_count | int | Number of new arrivals this episode |
|
| 43 |
+
| episode_done | bool | Whether episode has ended |
|
| 44 |
+
|
| 45 |
+
## Action Space
|
| 46 |
+
|
| 47 |
+
| Field | Type | Description |
|
| 48 |
+
|-------|------|-------------|
|
| 49 |
+
| aircraft_id | str | Target aircraft identifier |
|
| 50 |
+
| action_type | str | assign, hold, or expedite |
|
| 51 |
+
| runway_id | str | Runway to assign (for assign action) |
|
| 52 |
+
| sequence_position | int | Landing sequence position |
|
| 53 |
+
|
| 54 |
+
## Tasks
|
| 55 |
+
|
| 56 |
+
### Task 1: Clear Skies
|
| 57 |
+
- **Difficulty**: Easy
|
| 58 |
+
- **Aircraft**: 5
|
| 59 |
+
- **Runways**: 2 (both OPEN)
|
| 60 |
+
- **Fuel**: All > 40 min
|
| 61 |
+
- **Emergencies**: None
|
| 62 |
+
- **Max Steps**: 20
|
| 63 |
+
- **Initial Distances**: 10-50 nm spread
|
| 64 |
+
|
| 65 |
+
### Task 2: Fuel Pressure
|
| 66 |
+
- **Difficulty**: Medium
|
| 67 |
+
- **Aircraft**: 10 initial, 2 arrive at step 5
|
| 68 |
+
- **Runways**: 1 OPEN, 1 REDUCED
|
| 69 |
+
- **Fuel Critical**: 2 aircraft with < 12 min
|
| 70 |
+
- **Max Steps**: 30
|
| 71 |
+
|
| 72 |
+
### Task 3: Full Emergency
|
| 73 |
+
- **Difficulty**: Hard
|
| 74 |
+
- **Aircraft**: 15 initial, 2 every 4 steps
|
| 75 |
+
- **Runways**: 2 (one closes at step 3)
|
| 76 |
+
- **Emergency**: One aircraft at step 5
|
| 77 |
+
- **Max Steps**: 40
|
| 78 |
+
|
| 79 |
+
## Scoring
|
| 80 |
+
|
| 81 |
+
### Grader 1 (Task 1)
|
| 82 |
+
- **Formula**: landings_completed / total_aircraft - avg_delay_penalty
|
| 83 |
+
- **Focus**: Basic landing completion efficiency
|
| 84 |
+
|
| 85 |
+
### Grader 2 (Task 2)
|
| 86 |
+
- **Formula**: 40% delay score + 40% fuel-critical handling + 20% separation compliance
|
| 87 |
+
- **Focus**: Handling fuel-critical situations
|
| 88 |
+
|
| 89 |
+
### Grader 3 (Task 3)
|
| 90 |
+
- **Formula**: 25% landings + 25% emergency + 25% no fuel exhaust + 25% queue < 12
|
| 91 |
+
- **Focus**: Multi-objective complex scenario handling
|
| 92 |
+
|
| 93 |
+
## Setup Instructions
|
| 94 |
+
|
| 95 |
+
### Local Setup
|
| 96 |
+
|
| 97 |
+
### Local LLM Inference
|
| 98 |
+
|
| 99 |
+
To run the inference script locally, you **must** supply environment variables pointing to your Language Model:
|
| 100 |
+
|
| 101 |
+
```bash
|
| 102 |
+
cd atc-openenv
|
| 103 |
+
pip install -r requirements.txt
|
| 104 |
+
|
| 105 |
+
# Linux/macOS
|
| 106 |
+
export API_BASE_URL="https://api.openai.com/v1" # Or Hugging Face Router, local vLLM etc.
|
| 107 |
+
export MODEL_NAME="gpt-4o"
|
| 108 |
+
export HF_TOKEN="your_hugging_face_or_api_key"
|
| 109 |
+
|
| 110 |
+
# Windows (Command Prompt)
|
| 111 |
+
set API_BASE_URL=https://router.huggingface.co/v1
|
| 112 |
+
set MODEL_NAME=Qwen/Qwen2.5-72B-Instruct
|
| 113 |
+
set HF_TOKEN=hf_YourTokenHere
|
| 114 |
+
|
| 115 |
+
# Run validation inference
|
| 116 |
+
python inference.py
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
### Local API Server
|
| 120 |
+
|
| 121 |
+
```bash
|
| 122 |
+
# Run the FastAPI Web API server locally
|
| 123 |
+
python app.py
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
### Docker Setup
|
| 127 |
+
|
| 128 |
+
```bash
|
| 129 |
+
cd atc-openenv
|
| 130 |
+
docker build -t atc-openenv .
|
| 131 |
+
docker run -p 7860:7860 atc-openenv
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
## API Endpoints
|
| 135 |
+
|
| 136 |
+
| Endpoint | Method | Description |
|
| 137 |
+
|----------|--------|-------------|
|
| 138 |
+
| `/health` | GET | Health check |
|
| 139 |
+
| `/reset?task_id={1,2,3}` | POST | Reset environment |
|
| 140 |
+
| `/step` | POST | Execute actions |
|
| 141 |
+
| `/state` | GET | Get full state |
|
| 142 |
+
|
| 143 |
+
## Baseline Scores (from inference.py)
|
| 144 |
+
|
| 145 |
+
| Task | Score | Total Reward |
|
| 146 |
+
|------|-------|--------------|
|
| 147 |
+
| 1 - Clear Skies | 1.000 | 4.35 |
|
| 148 |
+
| 2 - Fuel Pressure | 1.000 | 5.35 |
|
| 149 |
+
| 3 - Full Emergency | 0.967 | -2.00 |
|
| 150 |
+
|
| 151 |
+
## Example Interaction
|
| 152 |
+
|
| 153 |
+
```python
|
| 154 |
+
from env.atc_env import ATCEnv, Action
|
| 155 |
+
|
| 156 |
+
# Initialize environment
|
| 157 |
+
env = ATCEnv()
|
| 158 |
+
obs = env.reset(task_id=1)
|
| 159 |
+
|
| 160 |
+
# Observe current state
|
| 161 |
+
print(f"Timestep: {obs.timestep}")
|
| 162 |
+
print(f"Aircraft: {len(obs.aircraft)}")
|
| 163 |
+
print(f"Runways: {len(obs.runways)}")
|
| 164 |
+
|
| 165 |
+
# Submit actions (assign aircraft to runways)
|
| 166 |
+
actions = [
|
| 167 |
+
Action(aircraft_id="AC1", action_type="assign", runway_id="RW01", sequence_position=1),
|
| 168 |
+
Action(aircraft_id="AC2", action_type="assign", runway_id="RW02", sequence_position=1),
|
| 169 |
+
]
|
| 170 |
+
|
| 171 |
+
# Step simulation
|
| 172 |
+
obs, reward, done, info = env.step(actions)
|
| 173 |
+
print(f"Reward: {reward.value}")
|
| 174 |
+
print(f"Done: {done}")
|
| 175 |
+
|
| 176 |
+
# Get final state
|
| 177 |
+
state = env.state()
|
| 178 |
+
print(f"Score so far: {state.score_so_far}")
|
| 179 |
+
```
|
| 180 |
+
|
| 181 |
+
## Wake Turbulence Separation Rules
|
| 182 |
+
|
| 183 |
+
| Lead Type | Trail Type | Separation (nm) |
|
| 184 |
+
|-----------|------------|-----------------|
|
| 185 |
+
| HEAVY | HEAVY | 4 |
|
| 186 |
+
| HEAVY | MEDIUM | 5 |
|
| 187 |
+
| HEAVY | LIGHT | 6 |
|
| 188 |
+
| MEDIUM | LIGHT | 3 |
|
| 189 |
+
| OTHER | OTHER | 2 |
|
| 190 |
+
|
| 191 |
+
## Reward Events
|
| 192 |
+
|
| 193 |
+
| Event | Value |
|
| 194 |
+
|-------|-------|
|
| 195 |
+
| LANDING_SUCCESS | +1.0 |
|
| 196 |
+
| DELAY_PER_STEP | -0.05 per waiting aircraft |
|
| 197 |
+
| FUEL_CRITICAL_LATE | -2.0 per step after threshold |
|
| 198 |
+
| FUEL_EXHAUSTED | -10.0 |
|
| 199 |
+
| EMERGENCY_NOT_PRIORITIZED | -10.0 |
|
| 200 |
+
| SEPARATION_VIOLATION | -5.0 |
|
| 201 |
+
| RUNWAY_CONFLICT | -20.0 |
|
| 202 |
+
| HOLDING_PENALTY | -0.1 per step per holding aircraft |
|
| 203 |
+
|
| 204 |
+
## Environment Implementation
|
| 205 |
+
|
| 206 |
+
All models use Pydantic v2 for data validation. The environment is fully deterministic given a random seed. Graders are stateless and accept episode_log as input.
|
atc-openenv/__pycache__/app.cpython-311.pyc
ADDED
|
Binary file (3.24 kB). View file
|
|
|
atc-openenv/__pycache__/runway_algorithm.cpython-311.pyc
ADDED
|
Binary file (27.4 kB). View file
|
|
|
atc-openenv/env/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Air Traffic Control OpenEnv-compliant environment."""
|
| 2 |
+
from env.atc_env import ATCEnv
|
| 3 |
+
|
| 4 |
+
__all__ = ["ATCEnv"]
|
atc-openenv/env/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (303 Bytes). View file
|
|
|
atc-openenv/env/__pycache__/aircraft.cpython-311.pyc
ADDED
|
Binary file (3.87 kB). View file
|
|
|
atc-openenv/env/__pycache__/atc_env.cpython-311.pyc
ADDED
|
Binary file (21.3 kB). View file
|
|
|
atc-openenv/env/__pycache__/reward.cpython-311.pyc
ADDED
|
Binary file (2.46 kB). View file
|
|
|
atc-openenv/env/__pycache__/runway.cpython-311.pyc
ADDED
|
Binary file (3 kB). View file
|
|
|
atc-openenv/env/__pycache__/scheduler.cpython-311.pyc
ADDED
|
Binary file (5.53 kB). View file
|
|
|
atc-openenv/env/aircraft.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Aircraft models and simulation logic."""
|
| 2 |
+
from enum import Enum
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
from pydantic import BaseModel, Field
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class AircraftType(str, Enum):
|
| 9 |
+
HEAVY = "HEAVY"
|
| 10 |
+
MEDIUM = "MEDIUM"
|
| 11 |
+
LIGHT = "LIGHT"
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class Priority(str, Enum):
|
| 15 |
+
NORMAL = "NORMAL"
|
| 16 |
+
FUEL_CRITICAL = "FUEL_CRITICAL"
|
| 17 |
+
EMERGENCY = "EMERGENCY"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class AircraftStatus(str, Enum):
|
| 21 |
+
INBOUND = "INBOUND"
|
| 22 |
+
HOLDING = "HOLDING"
|
| 23 |
+
ASSIGNED = "ASSIGNED"
|
| 24 |
+
LANDING = "LANDING"
|
| 25 |
+
LANDED = "LANDED"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class Aircraft(BaseModel):
|
| 29 |
+
id: str
|
| 30 |
+
aircraft_type: AircraftType
|
| 31 |
+
priority: Priority = Priority.NORMAL
|
| 32 |
+
status: AircraftStatus = AircraftStatus.INBOUND
|
| 33 |
+
distance_nm: float
|
| 34 |
+
speed_knots: float
|
| 35 |
+
fuel_remaining_min: float
|
| 36 |
+
assigned_runway: Optional[str] = None
|
| 37 |
+
sequence_position: Optional[int] = None
|
| 38 |
+
|
| 39 |
+
@property
|
| 40 |
+
def eta_steps(self) -> int:
|
| 41 |
+
"""Estimated time of arrival in simulation steps (1 step = 1 minute)."""
|
| 42 |
+
if self.speed_knots <= 0:
|
| 43 |
+
return 999
|
| 44 |
+
return max(1, int(self.distance_nm / self.speed_knots * 60))
|
| 45 |
+
|
| 46 |
+
@property
|
| 47 |
+
def is_fuel_critical(self) -> bool:
|
| 48 |
+
return self.fuel_remaining_min < 15.0
|
| 49 |
+
|
| 50 |
+
@property
|
| 51 |
+
def is_emergency(self) -> bool:
|
| 52 |
+
return self.priority == Priority.EMERGENCY
|
| 53 |
+
|
| 54 |
+
def tick(self) -> None:
|
| 55 |
+
"""Advance simulation by one step - update distance and fuel."""
|
| 56 |
+
if self.status == AircraftStatus.LANDED:
|
| 57 |
+
return
|
| 58 |
+
if self.status == AircraftStatus.LANDING:
|
| 59 |
+
self.distance_nm = max(0.0, self.distance_nm - 3.0)
|
| 60 |
+
elif self.speed_knots > 0:
|
| 61 |
+
self.distance_nm = max(0.0, self.distance_nm - self.speed_knots / 60.0)
|
| 62 |
+
self.fuel_remaining_min = max(0.0, self.fuel_remaining_min - 1.0)
|
| 63 |
+
if self.fuel_remaining_min < 15.0 and self.priority == Priority.NORMAL:
|
| 64 |
+
self.priority = Priority.FUEL_CRITICAL
|
atc-openenv/env/atc_env.py
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Core ATC Environment implementation."""
|
| 2 |
+
import json
|
| 3 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 4 |
+
|
| 5 |
+
from pydantic import BaseModel, Field
|
| 6 |
+
|
| 7 |
+
from env.aircraft import Aircraft, AircraftStatus, AircraftType, Priority
|
| 8 |
+
from env.runway import Runway, RunwayStatus
|
| 9 |
+
from env.scheduler import Scheduler, WakeTurbulenceRule
|
| 10 |
+
from env.reward import RewardEvent, compute_reward, get_reward_breakdown
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class Action(BaseModel):
|
| 14 |
+
aircraft_id: str
|
| 15 |
+
action_type: str = Field(description="assign/hold/expedite")
|
| 16 |
+
runway_id: Optional[str] = None
|
| 17 |
+
sequence_position: Optional[int] = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class Observation(BaseModel):
|
| 21 |
+
aircraft: List[Dict[str, Any]]
|
| 22 |
+
runways: List[Dict[str, Any]]
|
| 23 |
+
timestep: int
|
| 24 |
+
new_arrivals_count: int
|
| 25 |
+
episode_done: bool
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class Reward(BaseModel):
|
| 29 |
+
value: float
|
| 30 |
+
breakdown: Dict[str, float] = Field(default_factory=get_reward_breakdown)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class State(BaseModel):
|
| 34 |
+
aircraft: List[Dict[str, Any]]
|
| 35 |
+
runways: List[Dict[str, Any]]
|
| 36 |
+
timestep: int
|
| 37 |
+
task_id: int
|
| 38 |
+
score_so_far: float = 0.0
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class ATCEnv:
|
| 42 |
+
"""Air Traffic Control runway sequencing environment."""
|
| 43 |
+
|
| 44 |
+
def __init__(self, seed: Optional[int] = None):
|
| 45 |
+
self._seed = seed
|
| 46 |
+
self._rng = None
|
| 47 |
+
self._aircraft: List[Aircraft] = []
|
| 48 |
+
self._runways: List[Runway] = []
|
| 49 |
+
self._timestep: int = 0
|
| 50 |
+
self._task_id: int = 1
|
| 51 |
+
self._max_steps: int = 40
|
| 52 |
+
self._total_reward: float = 0.0
|
| 53 |
+
self._new_arrivals_count: int = 0
|
| 54 |
+
self._episode_done: bool = False
|
| 55 |
+
self._score_so_far: float = 0.0
|
| 56 |
+
self._last_landed_types: Dict[str, Optional[AircraftType]] = {}
|
| 57 |
+
self._fuel_exhausted_count: int = 0
|
| 58 |
+
self._separation_violations: int = 0
|
| 59 |
+
self._runway_conflicts: int = 0
|
| 60 |
+
self._holding_steps: Dict[str, int] = {}
|
| 61 |
+
self._emergency_wait_steps: Dict[str, int] = {}
|
| 62 |
+
self._pending_arrivals: List[Dict[str, Any]] = []
|
| 63 |
+
self._task_config: Dict[str, Any] = {}
|
| 64 |
+
self._task_instance: Any = None
|
| 65 |
+
self._max_queue_size: int = 0
|
| 66 |
+
# Tracks which aircraft IDs were fuel-critical at episode start (for grader2)
|
| 67 |
+
self._initial_fuel_critical_ids: List[str] = []
|
| 68 |
+
|
| 69 |
+
def _seed_random(self, seed: int) -> None:
|
| 70 |
+
import random
|
| 71 |
+
self._rng = random.Random(seed)
|
| 72 |
+
self._rng.seed(seed)
|
| 73 |
+
|
| 74 |
+
def reset(self, task_id: int = 1) -> "Observation":
|
| 75 |
+
"""Reset environment with specified task."""
|
| 76 |
+
self._seed_random(self._seed or task_id * 42)
|
| 77 |
+
self._timestep = 0
|
| 78 |
+
self._total_reward = 0.0
|
| 79 |
+
self._episode_done = False
|
| 80 |
+
self._score_so_far = 0.0
|
| 81 |
+
self._new_arrivals_count = 0
|
| 82 |
+
self._fuel_exhausted_count = 0
|
| 83 |
+
self._separation_violations = 0
|
| 84 |
+
self._runway_conflicts = 0
|
| 85 |
+
self._last_landed_types = {}
|
| 86 |
+
self._holding_steps = {}
|
| 87 |
+
self._emergency_wait_steps = {}
|
| 88 |
+
self._pending_arrivals = []
|
| 89 |
+
self._max_queue_size = 0
|
| 90 |
+
self._initial_fuel_critical_ids = []
|
| 91 |
+
self._task_id = task_id
|
| 92 |
+
|
| 93 |
+
task_class = self._get_task_class(task_id)
|
| 94 |
+
self._task_config = task_class.get_config()
|
| 95 |
+
self._max_steps = self._task_config.get("max_steps", 40)
|
| 96 |
+
self._task_instance = task_class()
|
| 97 |
+
|
| 98 |
+
self._aircraft = self._initialize_aircraft(task_id)
|
| 99 |
+
self._runways = self._initialize_runways(task_id)
|
| 100 |
+
self._pending_arrivals = self._get_pending_arrivals(task_id)
|
| 101 |
+
|
| 102 |
+
# Record which aircraft are fuel-critical at spawn (before any simulation)
|
| 103 |
+
self._initial_fuel_critical_ids = [
|
| 104 |
+
ac.id for ac in self._aircraft
|
| 105 |
+
if ac.priority == Priority.FUEL_CRITICAL or ac.fuel_remaining_min < 15.0
|
| 106 |
+
]
|
| 107 |
+
|
| 108 |
+
return self._get_observation()
|
| 109 |
+
|
| 110 |
+
def _get_task_class(self, task_id: int):
|
| 111 |
+
from tasks.task1_clear_skies import Task1ClearSkies
|
| 112 |
+
from tasks.task2_fuel_pressure import Task2FuelPressure
|
| 113 |
+
from tasks.task3_full_emergency import Task3FullEmergency
|
| 114 |
+
tasks = {1: Task1ClearSkies, 2: Task2FuelPressure, 3: Task3FullEmergency}
|
| 115 |
+
return tasks.get(task_id, Task1ClearSkies)
|
| 116 |
+
|
| 117 |
+
def _initialize_aircraft(self, task_id: int) -> List[Aircraft]:
|
| 118 |
+
task_class = self._get_task_class(task_id)
|
| 119 |
+
return task_class.create_aircraft(self._rng)
|
| 120 |
+
|
| 121 |
+
def _initialize_runways(self, task_id: int) -> List[Runway]:
|
| 122 |
+
task_class = self._get_task_class(task_id)
|
| 123 |
+
return task_class.create_runways()
|
| 124 |
+
|
| 125 |
+
def _get_pending_arrivals(self, task_id: int) -> List[Dict[str, Any]]:
|
| 126 |
+
task_class = self._get_task_class(task_id)
|
| 127 |
+
return task_class.get_pending_arrivals()
|
| 128 |
+
|
| 129 |
+
# GRADER REQUIREMENT: Parameter MUST be exactly named 'action'
|
| 130 |
+
def step(self, action: List[Action]) -> Tuple["Observation", "Reward", bool, Dict[str, Any]]:
|
| 131 |
+
"""Execute one simulation step with provided actions."""
|
| 132 |
+
if self._episode_done:
|
| 133 |
+
return self._get_observation(), Reward(value=0.0), True, {}
|
| 134 |
+
|
| 135 |
+
reward_breakdown = get_reward_breakdown()
|
| 136 |
+
self._timestep += 1
|
| 137 |
+
|
| 138 |
+
# Apply agent actions first
|
| 139 |
+
self._apply_actions(action)
|
| 140 |
+
|
| 141 |
+
# FIX (Bug 1): Tick runways BEFORE processing landings so a runway that
|
| 142 |
+
# becomes free this step is immediately usable — corrects a 1-step throughput loss.
|
| 143 |
+
self._tick_runways()
|
| 144 |
+
|
| 145 |
+
self._process_landings(reward_breakdown)
|
| 146 |
+
|
| 147 |
+
self._process_new_arrivals()
|
| 148 |
+
|
| 149 |
+
self._tick_aircraft(reward_breakdown)
|
| 150 |
+
|
| 151 |
+
self._apply_holding_penalty(reward_breakdown)
|
| 152 |
+
|
| 153 |
+
reward_value = sum(reward_breakdown.values())
|
| 154 |
+
self._total_reward += reward_value
|
| 155 |
+
self._score_so_far = self._total_reward
|
| 156 |
+
|
| 157 |
+
self._process_task_events()
|
| 158 |
+
|
| 159 |
+
self._check_episode_end()
|
| 160 |
+
|
| 161 |
+
observation = self._get_observation()
|
| 162 |
+
reward = Reward(value=reward_value, breakdown=reward_breakdown)
|
| 163 |
+
info = {"score_so_far": self._score_so_far}
|
| 164 |
+
|
| 165 |
+
return observation, reward, self._episode_done, info
|
| 166 |
+
|
| 167 |
+
# INTERNAL HELPER: uses 'actions' to avoid loop conflicts
|
| 168 |
+
def _apply_actions(self, actions: List[Action]) -> None:
|
| 169 |
+
state_dict = self.state().model_dump()
|
| 170 |
+
# Track sequence positions used per runway in this step to detect conflicts
|
| 171 |
+
runway_seq_used: Dict[str, set] = {}
|
| 172 |
+
|
| 173 |
+
for action in actions:
|
| 174 |
+
valid, reason = Scheduler.validate_action(action.model_dump(), state_dict)
|
| 175 |
+
if not valid:
|
| 176 |
+
continue
|
| 177 |
+
|
| 178 |
+
aircraft = self._find_aircraft(action.aircraft_id)
|
| 179 |
+
if aircraft is None:
|
| 180 |
+
continue
|
| 181 |
+
|
| 182 |
+
if action.action_type in ("assign", "expedite"):
|
| 183 |
+
aircraft.status = AircraftStatus.ASSIGNED
|
| 184 |
+
aircraft.assigned_runway = action.runway_id
|
| 185 |
+
if action.sequence_position is not None:
|
| 186 |
+
# FIX (Bug 4): Count duplicate sequence positions as separation violations
|
| 187 |
+
rw = action.runway_id or ""
|
| 188 |
+
if rw not in runway_seq_used:
|
| 189 |
+
runway_seq_used[rw] = set()
|
| 190 |
+
if action.sequence_position in runway_seq_used[rw]:
|
| 191 |
+
self._separation_violations += 1
|
| 192 |
+
else:
|
| 193 |
+
runway_seq_used[rw].add(action.sequence_position)
|
| 194 |
+
aircraft.sequence_position = action.sequence_position
|
| 195 |
+
|
| 196 |
+
elif action.action_type == "hold":
|
| 197 |
+
aircraft.status = AircraftStatus.HOLDING
|
| 198 |
+
self._holding_steps[aircraft.id] = self._holding_steps.get(aircraft.id, 0) + 1
|
| 199 |
+
|
| 200 |
+
def _process_landings(self, reward_breakdown: Dict[str, float]) -> None:
|
| 201 |
+
for runway in self._runways:
|
| 202 |
+
if runway.status == RunwayStatus.CLOSED:
|
| 203 |
+
continue
|
| 204 |
+
if runway.current_occupant is not None:
|
| 205 |
+
continue
|
| 206 |
+
|
| 207 |
+
# Find all assigned aircraft ready to land on this runway
|
| 208 |
+
ready_aircraft = [
|
| 209 |
+
ac for ac in self._aircraft
|
| 210 |
+
if ac.status == AircraftStatus.ASSIGNED
|
| 211 |
+
and ac.assigned_runway == runway.id
|
| 212 |
+
and ac.distance_nm <= 5.0
|
| 213 |
+
]
|
| 214 |
+
|
| 215 |
+
if not ready_aircraft:
|
| 216 |
+
continue
|
| 217 |
+
|
| 218 |
+
# Pick aircraft with lowest sequence position (or closest if not set)
|
| 219 |
+
ready_aircraft.sort(key=lambda x: (x.sequence_position or 999, x.distance_nm))
|
| 220 |
+
aircraft = ready_aircraft[0]
|
| 221 |
+
|
| 222 |
+
# No incorrect separation violation check here (Bug 4 fixed via _apply_actions)
|
| 223 |
+
aircraft.status = AircraftStatus.LANDING
|
| 224 |
+
runway.occupy(aircraft.id, self._timestep)
|
| 225 |
+
self._last_landed_types[runway.id] = aircraft.aircraft_type
|
| 226 |
+
reward_breakdown["landing_success"] += 1.0
|
| 227 |
+
|
| 228 |
+
# Transition LANDING → LANDED once aircraft reaches threshold
|
| 229 |
+
for aircraft in self._aircraft:
|
| 230 |
+
if aircraft.status == AircraftStatus.LANDING and aircraft.distance_nm <= 2.0:
|
| 231 |
+
aircraft.status = AircraftStatus.LANDED
|
| 232 |
+
aircraft.sequence_position = None
|
| 233 |
+
|
| 234 |
+
def _process_new_arrivals(self) -> None:
|
| 235 |
+
new_arrivals = []
|
| 236 |
+
for pending in self._pending_arrivals[:]:
|
| 237 |
+
if pending["arrival_step"] == self._timestep:
|
| 238 |
+
aircraft = Aircraft(
|
| 239 |
+
id=pending["id"],
|
| 240 |
+
aircraft_type=AircraftType(pending["aircraft_type"]),
|
| 241 |
+
priority=Priority(pending.get("priority", "NORMAL")),
|
| 242 |
+
status=AircraftStatus.INBOUND,
|
| 243 |
+
distance_nm=pending["distance_nm"],
|
| 244 |
+
speed_knots=pending["speed_knots"],
|
| 245 |
+
fuel_remaining_min=pending["fuel_remaining_min"],
|
| 246 |
+
)
|
| 247 |
+
new_arrivals.append(aircraft)
|
| 248 |
+
self._pending_arrivals.remove(pending)
|
| 249 |
+
self._new_arrivals_count += 1
|
| 250 |
+
|
| 251 |
+
self._aircraft.extend(new_arrivals)
|
| 252 |
+
|
| 253 |
+
def _tick_aircraft(self, reward_breakdown: Dict[str, float]) -> None:
|
| 254 |
+
for aircraft in self._aircraft:
|
| 255 |
+
if aircraft.status == AircraftStatus.LANDED:
|
| 256 |
+
continue
|
| 257 |
+
|
| 258 |
+
prev_fuel = aircraft.fuel_remaining_min
|
| 259 |
+
aircraft.tick()
|
| 260 |
+
new_fuel = aircraft.fuel_remaining_min
|
| 261 |
+
|
| 262 |
+
if prev_fuel > 0 and new_fuel <= 0:
|
| 263 |
+
self._fuel_exhausted_count += 1
|
| 264 |
+
reward_breakdown["fuel_exhausted_penalty"] += 10.0
|
| 265 |
+
|
| 266 |
+
if aircraft.is_fuel_critical:
|
| 267 |
+
if aircraft.status in (AircraftStatus.HOLDING, AircraftStatus.ASSIGNED):
|
| 268 |
+
steps_waited = self._holding_steps.get(aircraft.id, 0)
|
| 269 |
+
if steps_waited > 5:
|
| 270 |
+
reward_breakdown["fuel_critical_penalty"] += 2.0 * (steps_waited - 5)
|
| 271 |
+
|
| 272 |
+
if aircraft.is_emergency:
|
| 273 |
+
if aircraft.status == AircraftStatus.HOLDING:
|
| 274 |
+
self._emergency_wait_steps[aircraft.id] = self._emergency_wait_steps.get(aircraft.id, 0) + 1
|
| 275 |
+
if self._emergency_wait_steps[aircraft.id] > 3:
|
| 276 |
+
reward_breakdown["emergency_penalty"] += 10.0
|
| 277 |
+
|
| 278 |
+
if aircraft.status != AircraftStatus.LANDED:
|
| 279 |
+
waiting = aircraft.status in (AircraftStatus.HOLDING, AircraftStatus.ASSIGNED)
|
| 280 |
+
if waiting:
|
| 281 |
+
reward_breakdown["delay_penalty"] -= 0.05
|
| 282 |
+
|
| 283 |
+
# FIX (Bug 3): Count only INBOUND + HOLDING as the "queue" — aircraft waiting
|
| 284 |
+
# for assignment. ASSIGNED/LANDING aircraft are already being handled and should
|
| 285 |
+
# not inflate the queue counter, making Task 3 unwinnable.
|
| 286 |
+
current_queue = sum(
|
| 287 |
+
1 for ac in self._aircraft
|
| 288 |
+
if ac.status in (AircraftStatus.INBOUND, AircraftStatus.HOLDING)
|
| 289 |
+
)
|
| 290 |
+
if current_queue > self._max_queue_size:
|
| 291 |
+
self._max_queue_size = current_queue
|
| 292 |
+
|
| 293 |
+
def _apply_holding_penalty(self, reward_breakdown: Dict[str, float]) -> None:
|
| 294 |
+
holding_count = sum(
|
| 295 |
+
1 for ac in self._aircraft if ac.status == AircraftStatus.HOLDING
|
| 296 |
+
)
|
| 297 |
+
reward_breakdown["holding_penalty"] = -0.1 * holding_count
|
| 298 |
+
|
| 299 |
+
def _tick_runways(self) -> None:
|
| 300 |
+
for runway in self._runways:
|
| 301 |
+
runway.tick(self._timestep)
|
| 302 |
+
|
| 303 |
+
def _process_task_events(self) -> None:
|
| 304 |
+
"""Dispatch step events to task instance for runway closures, emergencies, etc."""
|
| 305 |
+
if self._task_instance is not None and hasattr(self._task_instance, "process_step_event"):
|
| 306 |
+
self._task_instance.process_step_event(self, self._timestep)
|
| 307 |
+
|
| 308 |
+
def _check_episode_end(self) -> None:
|
| 309 |
+
# FIX (Bug 2): Do NOT terminate episode on fuel exhaustion. Fuel exhaustion is
|
| 310 |
+
# already penalized via reward and grader score. Terminating instantly when one
|
| 311 |
+
# physically-impossible aircraft crashes is too punishing and collapses all
|
| 312 |
+
# other aircraft scores. The episode runs to natural completion.
|
| 313 |
+
|
| 314 |
+
# All aircraft landed (and no more pending arrivals)
|
| 315 |
+
all_landed = all(ac.status == AircraftStatus.LANDED for ac in self._aircraft)
|
| 316 |
+
no_more_arrivals = len(self._pending_arrivals) == 0
|
| 317 |
+
if all_landed and no_more_arrivals:
|
| 318 |
+
self._episode_done = True
|
| 319 |
+
return
|
| 320 |
+
|
| 321 |
+
if self._timestep >= self._max_steps:
|
| 322 |
+
self._episode_done = True
|
| 323 |
+
return
|
| 324 |
+
|
| 325 |
+
def _find_aircraft(self, aircraft_id: str) -> Optional[Aircraft]:
|
| 326 |
+
for aircraft in self._aircraft:
|
| 327 |
+
if aircraft.id == aircraft_id:
|
| 328 |
+
return aircraft
|
| 329 |
+
return None
|
| 330 |
+
|
| 331 |
+
def _get_observation(self) -> "Observation":
|
| 332 |
+
aircraft_data = []
|
| 333 |
+
for ac in self._aircraft:
|
| 334 |
+
d = ac.model_dump()
|
| 335 |
+
d["eta_steps"] = ac.eta_steps
|
| 336 |
+
d["is_fuel_critical"] = ac.is_fuel_critical
|
| 337 |
+
d["is_emergency"] = ac.is_emergency
|
| 338 |
+
aircraft_data.append(d)
|
| 339 |
+
|
| 340 |
+
runway_data = [rw.model_dump() for rw in self._runways]
|
| 341 |
+
|
| 342 |
+
return Observation(
|
| 343 |
+
aircraft=aircraft_data,
|
| 344 |
+
runways=runway_data,
|
| 345 |
+
timestep=self._timestep,
|
| 346 |
+
new_arrivals_count=self._new_arrivals_count,
|
| 347 |
+
episode_done=self._episode_done,
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
def state(self) -> "State":
|
| 351 |
+
"""Return full environment state."""
|
| 352 |
+
aircraft_data = []
|
| 353 |
+
for ac in self._aircraft:
|
| 354 |
+
d = ac.model_dump()
|
| 355 |
+
d["eta_steps"] = ac.eta_steps
|
| 356 |
+
d["is_fuel_critical"] = ac.is_fuel_critical
|
| 357 |
+
d["is_emergency"] = ac.is_emergency
|
| 358 |
+
aircraft_data.append(d)
|
| 359 |
+
|
| 360 |
+
return State(
|
| 361 |
+
aircraft=aircraft_data,
|
| 362 |
+
runways=[rw.model_dump() for rw in self._runways],
|
| 363 |
+
timestep=self._timestep,
|
| 364 |
+
task_id=self._task_id,
|
| 365 |
+
score_so_far=self._score_so_far,
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
def get_grader_input(self) -> Dict[str, Any]:
|
| 369 |
+
"""Get episode data for grading."""
|
| 370 |
+
return {
|
| 371 |
+
"aircraft": [ac.model_dump() for ac in self._aircraft],
|
| 372 |
+
"timestep": self._timestep,
|
| 373 |
+
"fuel_exhausted_count": self._fuel_exhausted_count,
|
| 374 |
+
"separation_violations": self._separation_violations,
|
| 375 |
+
"runway_conflicts": self._runway_conflicts,
|
| 376 |
+
"total_reward": self._total_reward,
|
| 377 |
+
"holding_steps": self._holding_steps,
|
| 378 |
+
"emergency_wait_steps": self._emergency_wait_steps,
|
| 379 |
+
"max_queue_size": self._max_queue_size,
|
| 380 |
+
# FIX (Bug 8): Pass initial fuel-critical IDs so graders can correctly
|
| 381 |
+
# distinguish aircraft that were BORN fuel-critical vs those that aged into it.
|
| 382 |
+
"initial_fuel_critical_ids": self._initial_fuel_critical_ids,
|
| 383 |
+
}
|
atc-openenv/env/reward.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reward computation for ATC environment."""
|
| 2 |
+
from typing import Any, Dict
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class RewardEvent:
|
| 6 |
+
LANDING_SUCCESS = "LANDING_SUCCESS"
|
| 7 |
+
DELAY_PER_STEP = "DELAY_PER_STEP"
|
| 8 |
+
FUEL_CRITICAL_LATE = "FUEL_CRITICAL_LATE"
|
| 9 |
+
FUEL_EXHAUSTED = "FUEL_EXHAUSTED"
|
| 10 |
+
EMERGENCY_NOT_PRIORITIZED = "EMERGENCY_NOT_PRIORITIZED"
|
| 11 |
+
SEPARATION_VIOLATION = "SEPARATION_VIOLATION"
|
| 12 |
+
RUNWAY_CONFLICT = "RUNWAY_CONFLICT"
|
| 13 |
+
HOLDING_PENALTY = "HOLDING_PENALTY"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def compute_reward(event: str, context: Dict[str, Any]) -> float:
|
| 17 |
+
"""Compute reward based on event and context."""
|
| 18 |
+
reward_values = {
|
| 19 |
+
RewardEvent.LANDING_SUCCESS: 1.0,
|
| 20 |
+
RewardEvent.DELAY_PER_STEP: -0.05,
|
| 21 |
+
RewardEvent.FUEL_CRITICAL_LATE: -2.0,
|
| 22 |
+
RewardEvent.FUEL_EXHAUSTED: -10.0,
|
| 23 |
+
RewardEvent.EMERGENCY_NOT_PRIORITIZED: -10.0,
|
| 24 |
+
RewardEvent.SEPARATION_VIOLATION: -5.0,
|
| 25 |
+
RewardEvent.RUNWAY_CONFLICT: -20.0,
|
| 26 |
+
RewardEvent.HOLDING_PENALTY: -0.1,
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
base_reward = reward_values.get(event, 0.0)
|
| 30 |
+
|
| 31 |
+
if event == RewardEvent.DELAY_PER_STEP:
|
| 32 |
+
return base_reward * context.get("waiting_count", 1)
|
| 33 |
+
|
| 34 |
+
if event == RewardEvent.FUEL_CRITICAL_LATE:
|
| 35 |
+
steps_waited = context.get("steps_waited", 5)
|
| 36 |
+
if steps_waited > 5:
|
| 37 |
+
return base_reward * (steps_waited - 5)
|
| 38 |
+
return 0.0
|
| 39 |
+
|
| 40 |
+
if event == RewardEvent.EMERGENCY_NOT_PRIORITIZED:
|
| 41 |
+
steps_waited = context.get("steps_waited", 0)
|
| 42 |
+
if steps_waited > 3:
|
| 43 |
+
return base_reward
|
| 44 |
+
return 0.0
|
| 45 |
+
|
| 46 |
+
return base_reward
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def get_reward_breakdown() -> Dict[str, float]:
|
| 50 |
+
"""Return breakdown structure for rewards."""
|
| 51 |
+
return {
|
| 52 |
+
"landing_success": 0.0,
|
| 53 |
+
"delay_penalty": 0.0,
|
| 54 |
+
"fuel_critical_penalty": 0.0,
|
| 55 |
+
"fuel_exhausted_penalty": 0.0,
|
| 56 |
+
"emergency_penalty": 0.0,
|
| 57 |
+
"separation_violation": 0.0,
|
| 58 |
+
"runway_conflict": 0.0,
|
| 59 |
+
"holding_penalty": 0.0,
|
| 60 |
+
}
|
atc-openenv/env/runway.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Runway models and operations."""
|
| 2 |
+
from enum import Enum
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
from pydantic import BaseModel
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class RunwayStatus(str, Enum):
|
| 9 |
+
OPEN = "OPEN"
|
| 10 |
+
REDUCED = "REDUCED"
|
| 11 |
+
CLOSED = "CLOSED"
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class Runway(BaseModel):
|
| 15 |
+
id: str
|
| 16 |
+
status: RunwayStatus = RunwayStatus.OPEN
|
| 17 |
+
next_available_step: int = 0
|
| 18 |
+
current_occupant: Optional[str] = None
|
| 19 |
+
|
| 20 |
+
@property
|
| 21 |
+
def separation_steps(self) -> int:
|
| 22 |
+
"""Separation steps required between aircraft."""
|
| 23 |
+
return 2 if self.status == RunwayStatus.OPEN else 4
|
| 24 |
+
|
| 25 |
+
@property
|
| 26 |
+
def is_available(self) -> bool:
|
| 27 |
+
"""Check if runway is available for new assignment."""
|
| 28 |
+
return self.status != RunwayStatus.CLOSED
|
| 29 |
+
|
| 30 |
+
def occupy(self, aircraft_id: str, current_step: int) -> None:
|
| 31 |
+
"""Assign aircraft to runway and set next available time."""
|
| 32 |
+
self.current_occupant = aircraft_id
|
| 33 |
+
self.next_available_step = current_step + self.separation_steps
|
| 34 |
+
|
| 35 |
+
def tick(self, current_step: int) -> None:
|
| 36 |
+
"""Update runway availability based on current step."""
|
| 37 |
+
if (
|
| 38 |
+
self.current_occupant is not None
|
| 39 |
+
and current_step >= self.next_available_step
|
| 40 |
+
):
|
| 41 |
+
self.current_occupant = None
|
| 42 |
+
|
| 43 |
+
def close(self) -> None:
|
| 44 |
+
"""Close the runway."""
|
| 45 |
+
self.status = RunwayStatus.CLOSED
|
| 46 |
+
self.current_occupant = None
|
| 47 |
+
|
| 48 |
+
def reduce(self) -> None:
|
| 49 |
+
"""Reduce runway capacity (increase separation)."""
|
| 50 |
+
if self.status == RunwayStatus.OPEN:
|
| 51 |
+
self.status = RunwayStatus.REDUCED
|
atc-openenv/env/scheduler.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Wake turbulence separation and sequencing rules."""
|
| 2 |
+
from typing import List, Optional, Tuple
|
| 3 |
+
|
| 4 |
+
from env.aircraft import Aircraft, AircraftType
|
| 5 |
+
from env.runway import Runway, RunwayStatus
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class WakeTurbulenceRule:
|
| 9 |
+
"""Separation requirements based on wake turbulence categories."""
|
| 10 |
+
|
| 11 |
+
SEPARATION_NM = {
|
| 12 |
+
(AircraftType.HEAVY, AircraftType.HEAVY): 4.0,
|
| 13 |
+
(AircraftType.HEAVY, AircraftType.MEDIUM): 5.0,
|
| 14 |
+
(AircraftType.HEAVY, AircraftType.LIGHT): 6.0,
|
| 15 |
+
(AircraftType.MEDIUM, AircraftType.LIGHT): 3.0,
|
| 16 |
+
(AircraftType.MEDIUM, AircraftType.HEAVY): 4.0,
|
| 17 |
+
(AircraftType.LIGHT, AircraftType.HEAVY): 4.0,
|
| 18 |
+
(AircraftType.LIGHT, AircraftType.MEDIUM): 2.0,
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
@classmethod
|
| 22 |
+
def get_separation(cls, lead_type: AircraftType, trail_type: AircraftType) -> float:
|
| 23 |
+
"""Get required separation in nautical miles."""
|
| 24 |
+
return cls.SEPARATION_NM.get(
|
| 25 |
+
(lead_type, trail_type),
|
| 26 |
+
cls.SEPARATION_NM.get((trail_type, lead_type), 2.0)
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
@classmethod
|
| 30 |
+
def can_land(
|
| 31 |
+
cls,
|
| 32 |
+
aircraft: Aircraft,
|
| 33 |
+
runway: Runway,
|
| 34 |
+
last_landed_type: Optional[AircraftType],
|
| 35 |
+
current_step: int,
|
| 36 |
+
) -> bool:
|
| 37 |
+
"""Check if aircraft can land given wake turbulence rules."""
|
| 38 |
+
if not runway.is_available:
|
| 39 |
+
return False
|
| 40 |
+
if current_step < runway.next_available_step:
|
| 41 |
+
return False
|
| 42 |
+
if last_landed_type is None:
|
| 43 |
+
return True
|
| 44 |
+
separation_nm = cls.get_separation(last_landed_type, aircraft.aircraft_type)
|
| 45 |
+
return aircraft.distance_nm <= separation_nm + 5
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class Scheduler:
|
| 49 |
+
"""Manages aircraft sequencing and action validation."""
|
| 50 |
+
|
| 51 |
+
@staticmethod
|
| 52 |
+
def get_sequence(aircraft_list: List[Aircraft]) -> List[Aircraft]:
|
| 53 |
+
"""Sort aircraft by priority, then fuel, then ETA."""
|
| 54 |
+
def sort_key(a: Aircraft):
|
| 55 |
+
priority_order = {
|
| 56 |
+
"EMERGENCY": 0,
|
| 57 |
+
"FUEL_CRITICAL": 1,
|
| 58 |
+
"NORMAL": 2,
|
| 59 |
+
}
|
| 60 |
+
return (
|
| 61 |
+
priority_order.get(a.priority.value, 2),
|
| 62 |
+
a.fuel_remaining_min,
|
| 63 |
+
a.eta_steps,
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
return sorted(aircraft_list, key=sort_key)
|
| 67 |
+
|
| 68 |
+
@staticmethod
|
| 69 |
+
def validate_action(
|
| 70 |
+
action: dict, state: dict
|
| 71 |
+
) -> Tuple[bool, str]:
|
| 72 |
+
"""Validate an action against current state."""
|
| 73 |
+
aircraft_id = action.get("aircraft_id")
|
| 74 |
+
action_type = action.get("action_type")
|
| 75 |
+
|
| 76 |
+
aircraft_map = {ac["id"]: ac for ac in state.get("aircraft", [])}
|
| 77 |
+
runway_map = {rw["id"]: rw for rw in state.get("runways", [])}
|
| 78 |
+
|
| 79 |
+
if aircraft_id not in aircraft_map:
|
| 80 |
+
return False, f"Aircraft {aircraft_id} not found"
|
| 81 |
+
|
| 82 |
+
aircraft = aircraft_map[aircraft_id]
|
| 83 |
+
|
| 84 |
+
if aircraft["status"] == "LANDED":
|
| 85 |
+
return False, f"Aircraft {aircraft_id} already landed"
|
| 86 |
+
|
| 87 |
+
if aircraft["status"] == "LANDING":
|
| 88 |
+
return False, f"Aircraft {aircraft_id} is landing"
|
| 89 |
+
|
| 90 |
+
if action_type == "assign":
|
| 91 |
+
runway_id = action.get("runway_id")
|
| 92 |
+
if not runway_id:
|
| 93 |
+
return False, "assign action requires runway_id"
|
| 94 |
+
if runway_id not in runway_map:
|
| 95 |
+
return False, f"Runway {runway_id} not found"
|
| 96 |
+
if runway_map[runway_id]["status"] == "CLOSED":
|
| 97 |
+
return False, f"Runway {runway_id} is closed"
|
| 98 |
+
return True, "valid"
|
| 99 |
+
elif action_type == "hold":
|
| 100 |
+
return True, "valid"
|
| 101 |
+
elif action_type == "expedite":
|
| 102 |
+
return True, "valid"
|
| 103 |
+
else:
|
| 104 |
+
return False, f"Unknown action type: {action_type}"
|
atc-openenv/graders/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Grader modules for evaluating episode performance."""
|
atc-openenv/graders/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (219 Bytes). View file
|
|
|
atc-openenv/graders/__pycache__/grader1.cpython-311.pyc
ADDED
|
Binary file (1.83 kB). View file
|
|
|
atc-openenv/graders/__pycache__/grader2.cpython-311.pyc
ADDED
|
Binary file (3.63 kB). View file
|
|
|
atc-openenv/graders/__pycache__/grader3.cpython-311.pyc
ADDED
|
Binary file (2.86 kB). View file
|
|
|
atc-openenv/graders/grader1.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Grader 1: Basic landing completion and delay scoring."""
|
| 2 |
+
from typing import Dict, Any
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def grade(episode_log: Dict[str, Any]) -> float:
|
| 6 |
+
"""
|
| 7 |
+
Score based on landing completion with delay penalty.
|
| 8 |
+
|
| 9 |
+
score = landings_completed / total_aircraft
|
| 10 |
+
penalty for avg delay
|
| 11 |
+
"""
|
| 12 |
+
if not episode_log:
|
| 13 |
+
return 0.0
|
| 14 |
+
|
| 15 |
+
aircraft = episode_log.get("aircraft", [])
|
| 16 |
+
timestep = episode_log.get("timestep", 1)
|
| 17 |
+
|
| 18 |
+
total_aircraft = len(aircraft)
|
| 19 |
+
if total_aircraft == 0:
|
| 20 |
+
return 0.0
|
| 21 |
+
|
| 22 |
+
landed_count = sum(1 for ac in aircraft if ac.get("status") == "LANDED")
|
| 23 |
+
|
| 24 |
+
delay_score = landed_count / total_aircraft
|
| 25 |
+
|
| 26 |
+
delay_penalty = 0.0
|
| 27 |
+
waiting_times = episode_log.get("holding_steps", {})
|
| 28 |
+
if waiting_times:
|
| 29 |
+
avg_delay = sum(waiting_times.values()) / len(waiting_times)
|
| 30 |
+
delay_penalty = min(0.3, avg_delay * 0.01)
|
| 31 |
+
|
| 32 |
+
final_score = max(0.0, min(1.0, delay_score - delay_penalty))
|
| 33 |
+
return final_score
|
atc-openenv/graders/grader2.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Grader 2: Weighted scoring for delay, fuel-critical handling, and separation compliance."""
|
| 2 |
+
from typing import Dict, Any
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def grade(episode_log: Dict[str, Any]) -> float:
|
| 6 |
+
"""
|
| 7 |
+
Weighted score: 40% delay, 40% fuel-critical handling, 20% separation compliance.
|
| 8 |
+
|
| 9 |
+
FIX (Bug 8): fuel_critical_count now uses 'initial_fuel_critical_ids' passed from the
|
| 10 |
+
environment, which records aircraft that were FUEL_CRITICAL at spawn time.
|
| 11 |
+
Previously it used final fuel_remaining_min < 15, which includes any aircraft that
|
| 12 |
+
naturally depleted fuel over a long episode — massively inflating the denominator
|
| 13 |
+
and making fuel_score collapse to near-zero even with perfect play.
|
| 14 |
+
"""
|
| 15 |
+
if not episode_log:
|
| 16 |
+
return 0.0
|
| 17 |
+
|
| 18 |
+
aircraft = episode_log.get("aircraft", [])
|
| 19 |
+
total_aircraft = len(aircraft)
|
| 20 |
+
if total_aircraft == 0:
|
| 21 |
+
return 0.0
|
| 22 |
+
|
| 23 |
+
# 40%: Landings completed
|
| 24 |
+
landed = sum(1 for ac in aircraft if ac.get("status") == "LANDED")
|
| 25 |
+
delay_score = landed / total_aircraft
|
| 26 |
+
|
| 27 |
+
# 40%: Fuel-critical aircraft all land
|
| 28 |
+
# Use initial_fuel_critical_ids if available (set at episode start before any fuel depletion).
|
| 29 |
+
# Fall back to priority flag only (not fuel_remaining_min) to avoid counting aircraft
|
| 30 |
+
# that aged into fuel-critical status during a long episode.
|
| 31 |
+
initial_fc_ids = set(episode_log.get("initial_fuel_critical_ids", []))
|
| 32 |
+
if initial_fc_ids:
|
| 33 |
+
fuel_critical_count = len(initial_fc_ids)
|
| 34 |
+
fuel_landed = sum(
|
| 35 |
+
1 for ac in aircraft
|
| 36 |
+
if ac.get("id") in initial_fc_ids and ac.get("status") == "LANDED"
|
| 37 |
+
)
|
| 38 |
+
else:
|
| 39 |
+
# Fallback: count only aircraft whose priority is FUEL_CRITICAL (set at spawn
|
| 40 |
+
# or upgraded during tick — but not using final fuel level which degrades over time)
|
| 41 |
+
fuel_critical_count = sum(
|
| 42 |
+
1 for ac in aircraft if ac.get("priority") == "FUEL_CRITICAL"
|
| 43 |
+
)
|
| 44 |
+
fuel_landed = sum(
|
| 45 |
+
1 for ac in aircraft
|
| 46 |
+
if ac.get("priority") == "FUEL_CRITICAL" and ac.get("status") == "LANDED"
|
| 47 |
+
)
|
| 48 |
+
fuel_score = fuel_landed / fuel_critical_count if fuel_critical_count > 0 else 1.0
|
| 49 |
+
|
| 50 |
+
# 20%: Separation compliance (duplicate sequence positions = violations)
|
| 51 |
+
separation_violations = episode_log.get("separation_violations", 0)
|
| 52 |
+
max_violations = 10
|
| 53 |
+
separation_score = max(0.0, 1.0 - separation_violations / max_violations)
|
| 54 |
+
|
| 55 |
+
final_score = 0.4 * delay_score + 0.4 * fuel_score + 0.2 * separation_score
|
| 56 |
+
return max(0.0, min(1.0, final_score))
|
atc-openenv/graders/grader3.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Grader 3: Composite scoring for complex scenarios."""
|
| 2 |
+
from typing import Dict, Any
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def grade(episode_log: Dict[str, Any]) -> float:
|
| 6 |
+
"""
|
| 7 |
+
Composite score:
|
| 8 |
+
- 25% landings completed
|
| 9 |
+
- 25% emergency handling
|
| 10 |
+
- 25% no fuel exhaustions (proportional, not binary)
|
| 11 |
+
- 25% queue never exceeds 12 aircraft (queue = INBOUND+HOLDING only)
|
| 12 |
+
"""
|
| 13 |
+
if not episode_log:
|
| 14 |
+
return 0.0
|
| 15 |
+
|
| 16 |
+
aircraft = episode_log.get("aircraft", [])
|
| 17 |
+
total_aircraft = len(aircraft)
|
| 18 |
+
if total_aircraft == 0:
|
| 19 |
+
return 0.0
|
| 20 |
+
|
| 21 |
+
# 25%: Landings completed
|
| 22 |
+
landed = sum(1 for ac in aircraft if ac.get("status") == "LANDED")
|
| 23 |
+
landing_score = landed / total_aircraft
|
| 24 |
+
|
| 25 |
+
# 25%: Emergency aircraft all land
|
| 26 |
+
emergency_count = sum(1 for ac in aircraft if ac.get("priority") == "EMERGENCY")
|
| 27 |
+
emergency_landed = sum(
|
| 28 |
+
1 for ac in aircraft
|
| 29 |
+
if ac.get("priority") == "EMERGENCY" and ac.get("status") == "LANDED"
|
| 30 |
+
)
|
| 31 |
+
emergency_score = emergency_landed / emergency_count if emergency_count > 0 else 1.0
|
| 32 |
+
|
| 33 |
+
# 25%: Fuel exhaustion score (proportional — was binary 0/1, too punishing)
|
| 34 |
+
# Previously: any exhaustion = 0. Now: proportional penalty per exhausted aircraft.
|
| 35 |
+
# This way a well-played episode with 1 unlucky exhaustion still gets partial credit.
|
| 36 |
+
fuel_exhausted = episode_log.get("fuel_exhausted_count", 0)
|
| 37 |
+
fuel_score = max(0.0, 1.0 - fuel_exhausted / max(1, total_aircraft))
|
| 38 |
+
|
| 39 |
+
# 25%: Queue management (queue = INBOUND+HOLDING only, per env fix Bug 3)
|
| 40 |
+
max_queue = episode_log.get("max_queue_size", 0)
|
| 41 |
+
queue_score = 1.0 if max_queue <= 12 else max(0.0, 1.0 - (max_queue - 12) / 20)
|
| 42 |
+
|
| 43 |
+
final_score = 0.25 * landing_score + 0.25 * emergency_score + 0.25 * fuel_score + 0.25 * queue_score
|
| 44 |
+
return max(0.0, min(1.0, final_score))
|
atc-openenv/inference.py
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Inference script for ATC environment using OpenAI client."""
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
from typing import List, Optional, Tuple
|
| 6 |
+
|
| 7 |
+
from openai import OpenAI
|
| 8 |
+
|
| 9 |
+
from env.atc_env import ATCEnv, Action
|
| 10 |
+
from env.aircraft import AircraftStatus, Priority
|
| 11 |
+
from graders.grader1 import grade as grade1
|
| 12 |
+
from graders.grader2 import grade as grade2
|
| 13 |
+
from graders.grader3 import grade as grade3
|
| 14 |
+
|
| 15 |
+
# ==========================================
|
| 16 |
+
# HACKATHON COMPLIANT LOGGING FUNCTIONS
|
| 17 |
+
# ==========================================
|
| 18 |
+
def log_start(task: str, env: str, model: str) -> None:
|
| 19 |
+
print(f"[START] task={task} env={env} model={model}", flush=True)
|
| 20 |
+
|
| 21 |
+
def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:
|
| 22 |
+
error_val = error if error else "null"
|
| 23 |
+
done_val = str(done).lower()
|
| 24 |
+
print(
|
| 25 |
+
f"[STEP] step={step} action={action} reward={reward:.2f} done={done_val} error={error_val}",
|
| 26 |
+
flush=True,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:
|
| 30 |
+
rewards_str = ",".join(f"{r:.2f}" for r in rewards)
|
| 31 |
+
clamped_score = min(max(score, 0.0), 1.0)
|
| 32 |
+
print(f"[END] success={str(success).lower()} steps={steps} score={clamped_score:.3f} rewards={rewards_str}", flush=True)
|
| 33 |
+
# ==========================================
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def will_exhaust_fuel(ac: dict) -> bool:
|
| 37 |
+
"""True if this aircraft will run out of fuel before it can reach the runway."""
|
| 38 |
+
return ac.get("fuel_remaining_min", 999) < ac.get("eta_steps", 999)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def get_sort_key(ac: dict):
|
| 42 |
+
"""
|
| 43 |
+
Urgency sort (ascending = handle first):
|
| 44 |
+
0: fuel < ETA → will crash without immediate action
|
| 45 |
+
1: EMERGENCY priority
|
| 46 |
+
2: FUEL_CRITICAL priority
|
| 47 |
+
3: fuel < 15 (about to become fuel-critical)
|
| 48 |
+
4: NORMAL
|
| 49 |
+
Secondary: least fuel first, then earliest ETA.
|
| 50 |
+
"""
|
| 51 |
+
fuel = ac.get("fuel_remaining_min", 999)
|
| 52 |
+
eta = ac.get("eta_steps", 999)
|
| 53 |
+
priority = ac.get("priority", "NORMAL")
|
| 54 |
+
|
| 55 |
+
if will_exhaust_fuel(ac):
|
| 56 |
+
tier = 0
|
| 57 |
+
elif priority == "EMERGENCY":
|
| 58 |
+
tier = 1
|
| 59 |
+
elif priority == "FUEL_CRITICAL":
|
| 60 |
+
tier = 2
|
| 61 |
+
elif fuel < 15:
|
| 62 |
+
tier = 3
|
| 63 |
+
else:
|
| 64 |
+
tier = 4
|
| 65 |
+
|
| 66 |
+
return (tier, fuel, eta)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def get_fallback_action(env: ATCEnv, task_id: int = 1, current_step: int = 0) -> List[Action]:
|
| 70 |
+
"""
|
| 71 |
+
Deterministic greedy controller — used when LLM is bypassed or fails.
|
| 72 |
+
|
| 73 |
+
Key behaviours:
|
| 74 |
+
- Sorts all unassigned aircraft by urgency (crash risk > emergency > fuel_critical > normal).
|
| 75 |
+
- Task 3, step >= 2: avoids RW02 (it closes at step 3; stranded assignments are now
|
| 76 |
+
reset by the env on closure, but better not to assign there in the first place).
|
| 77 |
+
- Assigns ALL unassigned aircraft every step to keep queue minimal.
|
| 78 |
+
- Round-robin across available runways with monotonically increasing sequence positions.
|
| 79 |
+
"""
|
| 80 |
+
state = env.state().model_dump()
|
| 81 |
+
aircraft_list = state.get("aircraft", [])
|
| 82 |
+
|
| 83 |
+
unassigned = [
|
| 84 |
+
ac for ac in aircraft_list
|
| 85 |
+
if ac.get("status") not in ("LANDED", "LANDING", "ASSIGNED")
|
| 86 |
+
]
|
| 87 |
+
|
| 88 |
+
if not unassigned:
|
| 89 |
+
return []
|
| 90 |
+
|
| 91 |
+
ordered = sorted(unassigned, key=get_sort_key)
|
| 92 |
+
|
| 93 |
+
runways = state.get("runways", [])
|
| 94 |
+
available_runways = [rw for rw in runways if rw.get("status") != "CLOSED"]
|
| 95 |
+
|
| 96 |
+
# Task 3: proactively avoid RW02 at step >= 2 since it closes at step 3.
|
| 97 |
+
# The env will reset stuck aircraft on closure, but avoiding assignment is cleaner.
|
| 98 |
+
if task_id == 3 and current_step >= 2:
|
| 99 |
+
available_runways = [rw for rw in available_runways if rw["id"] != "RW02"]
|
| 100 |
+
|
| 101 |
+
if not available_runways:
|
| 102 |
+
return []
|
| 103 |
+
|
| 104 |
+
runway_ids = [rw["id"] for rw in available_runways]
|
| 105 |
+
runway_queue_pos = {rw["id"]: 1 for rw in available_runways}
|
| 106 |
+
|
| 107 |
+
actions = []
|
| 108 |
+
for i, ac in enumerate(ordered):
|
| 109 |
+
runway_id = runway_ids[i % len(runway_ids)]
|
| 110 |
+
seq_pos = runway_queue_pos[runway_id]
|
| 111 |
+
runway_queue_pos[runway_id] += 1
|
| 112 |
+
|
| 113 |
+
fuel = ac.get("fuel_remaining_min", 999)
|
| 114 |
+
priority = ac.get("priority", "NORMAL")
|
| 115 |
+
is_critical = (
|
| 116 |
+
will_exhaust_fuel(ac)
|
| 117 |
+
or priority in ("EMERGENCY", "FUEL_CRITICAL")
|
| 118 |
+
or fuel <= 15
|
| 119 |
+
)
|
| 120 |
+
action_type = "expedite" if is_critical else "assign"
|
| 121 |
+
|
| 122 |
+
actions.append(Action(
|
| 123 |
+
aircraft_id=ac["id"],
|
| 124 |
+
action_type=action_type,
|
| 125 |
+
runway_id=runway_id,
|
| 126 |
+
sequence_position=seq_pos,
|
| 127 |
+
))
|
| 128 |
+
|
| 129 |
+
return actions
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def should_skip_llm(task_id: int, current_step: int) -> bool:
|
| 133 |
+
"""
|
| 134 |
+
Returns True to bypass the LLM and use deterministic controller instead.
|
| 135 |
+
|
| 136 |
+
Task 2: Always skip — fuel-critical aircraft (AC3, AC6) must be expedited in step 1.
|
| 137 |
+
LLM API failures or mis-ordering are catastrophic here.
|
| 138 |
+
Task 3: Skip for steps 1-12 to reliably handle:
|
| 139 |
+
- Steps 1-2: assign all 15 initial aircraft before RW02 closes
|
| 140 |
+
- Step 3: RW02 closes (env auto-reassigns stuck aircraft to HOLDING)
|
| 141 |
+
- Step 5: AC10 becomes EMERGENCY — must be expedited immediately
|
| 142 |
+
- Steps 4-12: batch arrivals at steps 4, 8 need immediate assignment
|
| 143 |
+
"""
|
| 144 |
+
if task_id == 2:
|
| 145 |
+
return True
|
| 146 |
+
if task_id == 3 and current_step <= 12:
|
| 147 |
+
return True
|
| 148 |
+
return False
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def parse_llm_response(response_text: str) -> List[dict]:
|
| 152 |
+
"""Parse LLM response, stripping markdown fences before extracting JSON."""
|
| 153 |
+
clean = re.sub(r'```(?:json)?', '', response_text).strip()
|
| 154 |
+
clean = clean.replace('```', '')
|
| 155 |
+
|
| 156 |
+
match = re.search(r'\{.*\}', clean, re.DOTALL)
|
| 157 |
+
if match:
|
| 158 |
+
try:
|
| 159 |
+
data = json.loads(match.group(0))
|
| 160 |
+
if isinstance(data, dict) and "actions" in data:
|
| 161 |
+
return data["actions"]
|
| 162 |
+
if isinstance(data, list):
|
| 163 |
+
return data
|
| 164 |
+
except json.JSONDecodeError:
|
| 165 |
+
pass
|
| 166 |
+
|
| 167 |
+
return []
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def build_prompt(observation: dict, state: dict, task_id: int) -> str:
|
| 171 |
+
"""Task-specific prompts targeting each grader's exact scoring components."""
|
| 172 |
+
aircraft_list = state.get("aircraft", [])
|
| 173 |
+
current_step = state.get("timestep", 0)
|
| 174 |
+
|
| 175 |
+
# Show only actionable aircraft, sorted by urgency
|
| 176 |
+
actionable = [
|
| 177 |
+
ac for ac in aircraft_list
|
| 178 |
+
if ac.get("status") in ("INBOUND", "HOLDING")
|
| 179 |
+
]
|
| 180 |
+
sorted_aircraft = sorted(actionable, key=get_sort_key)
|
| 181 |
+
|
| 182 |
+
aircraft_lines = []
|
| 183 |
+
for ac in sorted_aircraft:
|
| 184 |
+
priority = ac.get("priority", "NORMAL")
|
| 185 |
+
fuel = ac.get("fuel_remaining_min", 0)
|
| 186 |
+
dist = ac.get("distance_nm", 0)
|
| 187 |
+
eta = ac.get("eta_steps", 999)
|
| 188 |
+
warning = ""
|
| 189 |
+
if will_exhaust_fuel(ac):
|
| 190 |
+
warning = " *** CRASH RISK: fuel < ETA — EXPEDITE NOW ***"
|
| 191 |
+
elif priority in ("EMERGENCY", "FUEL_CRITICAL") or fuel < 15:
|
| 192 |
+
warning = " *** CRITICAL ***"
|
| 193 |
+
aircraft_lines.append(
|
| 194 |
+
f"- {ac['id']}: priority={priority}, fuel={fuel:.1f}min, "
|
| 195 |
+
f"dist={dist:.1f}nm, ETA={eta}steps{warning}"
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
runway_lines = []
|
| 199 |
+
for rw in state.get("runways", []):
|
| 200 |
+
status = rw.get("status", "UNKNOWN")
|
| 201 |
+
note = " (DO NOT USE)" if status == "CLOSED" else ""
|
| 202 |
+
runway_lines.append(f"- {rw['id']}: {status}{note}")
|
| 203 |
+
|
| 204 |
+
if task_id == 1:
|
| 205 |
+
task_focus = ("Maximize aircraft landed. Assign all INBOUND/HOLDING aircraft "
|
| 206 |
+
"to runways immediately. Spread load across runways.")
|
| 207 |
+
elif task_id == 2:
|
| 208 |
+
task_focus = (
|
| 209 |
+
"SCORED: 40% landings + 40% fuel-critical lands + 20% no duplicate positions.\n"
|
| 210 |
+
"CRITICAL: Aircraft marked CRASH RISK must be expedited first or the episode continues "
|
| 211 |
+
"with a severe penalty. Always expedite FUEL_CRITICAL aircraft.\n"
|
| 212 |
+
"Never give two aircraft the same sequence_position on the same runway."
|
| 213 |
+
)
|
| 214 |
+
else:
|
| 215 |
+
extra = ""
|
| 216 |
+
if current_step >= 2:
|
| 217 |
+
extra += "\nWARNING: RW02 is closed or closing — assign ALL aircraft to RW01 only."
|
| 218 |
+
if current_step >= 5:
|
| 219 |
+
extra += "\nAC10 is EMERGENCY — expedite immediately if not yet LANDED."
|
| 220 |
+
task_focus = (
|
| 221 |
+
"SCORED: 25% landings + 25% emergency lands + 25% no fuel exhaustion + 25% queue<=12.\n"
|
| 222 |
+
"Assign ALL unassigned aircraft every step. Expedite any CRASH RISK or EMERGENCY aircraft."
|
| 223 |
+
+ extra
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
prompt = f"""You are an expert ATC sequencing controller.
|
| 227 |
+
Timestep: {current_step}
|
| 228 |
+
|
| 229 |
+
Aircraft needing assignment (most urgent first):
|
| 230 |
+
{chr(10).join(aircraft_lines) if aircraft_lines else " (none — all aircraft already assigned or landed)"}
|
| 231 |
+
|
| 232 |
+
Runways:
|
| 233 |
+
{chr(10).join(runway_lines)}
|
| 234 |
+
|
| 235 |
+
{task_focus}
|
| 236 |
+
|
| 237 |
+
RULES:
|
| 238 |
+
1. Never assign to a CLOSED runway.
|
| 239 |
+
2. Unique sequence_position per runway: if 3 aircraft go to RW01 use positions 1, 2, 3.
|
| 240 |
+
3. Use "expedite" for EMERGENCY, FUEL_CRITICAL, or CRASH RISK aircraft.
|
| 241 |
+
4. Use "assign" for NORMAL aircraft.
|
| 242 |
+
5. Only include INBOUND or HOLDING aircraft in actions.
|
| 243 |
+
|
| 244 |
+
Respond ONLY with this JSON:
|
| 245 |
+
```json
|
| 246 |
+
{{
|
| 247 |
+
"thought_process": "brief reasoning",
|
| 248 |
+
"actions": [
|
| 249 |
+
{{"aircraft_id": "AC3", "action_type": "expedite", "runway_id": "RW01", "sequence_position": 1}},
|
| 250 |
+
{{"aircraft_id": "AC1", "action_type": "assign", "runway_id": "RW01", "sequence_position": 2}}
|
| 251 |
+
]
|
| 252 |
+
}}
|
| 253 |
+
```"""
|
| 254 |
+
return prompt
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def apply_guardrails(action_dicts: List[dict], state_dump: dict) -> List[Action]:
|
| 258 |
+
"""
|
| 259 |
+
Validate and sanitize LLM action dicts before converting to Action objects.
|
| 260 |
+
Re-sorts by urgency and enforces unique sequence positions per runway.
|
| 261 |
+
"""
|
| 262 |
+
open_runways = [
|
| 263 |
+
rw["id"] for rw in state_dump.get("runways", [])
|
| 264 |
+
if rw.get("status") != "CLOSED"
|
| 265 |
+
]
|
| 266 |
+
aircraft_map = {a["id"]: a for a in state_dump.get("aircraft", [])}
|
| 267 |
+
|
| 268 |
+
# Sort by urgency before assigning positions
|
| 269 |
+
action_dicts_sorted = sorted(
|
| 270 |
+
action_dicts,
|
| 271 |
+
key=lambda ad: get_sort_key(aircraft_map.get(ad.get("aircraft_id", ""), {}))
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
runway_queue_pos = {}
|
| 275 |
+
actions = []
|
| 276 |
+
|
| 277 |
+
for action_dict in action_dicts_sorted:
|
| 278 |
+
try:
|
| 279 |
+
ac_id = action_dict.get("aircraft_id", "")
|
| 280 |
+
action_type = action_dict.get("action_type", "hold")
|
| 281 |
+
runway_id = action_dict.get("runway_id")
|
| 282 |
+
|
| 283 |
+
ac_data = aircraft_map.get(ac_id)
|
| 284 |
+
if ac_data:
|
| 285 |
+
is_critical = (
|
| 286 |
+
will_exhaust_fuel(ac_data)
|
| 287 |
+
or ac_data.get("fuel_remaining_min", 999) <= 15
|
| 288 |
+
or ac_data.get("priority") in ("EMERGENCY", "FUEL_CRITICAL")
|
| 289 |
+
)
|
| 290 |
+
# Never hold a critical aircraft
|
| 291 |
+
if action_type == "hold" and is_critical:
|
| 292 |
+
action_type = "expedite"
|
| 293 |
+
# Critical aircraft must have an open runway
|
| 294 |
+
if is_critical and (not runway_id or runway_id not in open_runways):
|
| 295 |
+
if open_runways:
|
| 296 |
+
runway_id = open_runways[0]
|
| 297 |
+
|
| 298 |
+
# Never assign to closed runway
|
| 299 |
+
if runway_id and runway_id not in open_runways:
|
| 300 |
+
if open_runways:
|
| 301 |
+
runway_id = open_runways[0]
|
| 302 |
+
else:
|
| 303 |
+
continue
|
| 304 |
+
|
| 305 |
+
# Enforce unique, monotonically increasing sequence positions per runway
|
| 306 |
+
if runway_id:
|
| 307 |
+
if runway_id not in runway_queue_pos:
|
| 308 |
+
runway_queue_pos[runway_id] = 1
|
| 309 |
+
seq_pos = runway_queue_pos[runway_id]
|
| 310 |
+
runway_queue_pos[runway_id] += 1
|
| 311 |
+
else:
|
| 312 |
+
seq_pos = action_dict.get("sequence_position", 1)
|
| 313 |
+
|
| 314 |
+
actions.append(Action(
|
| 315 |
+
aircraft_id=ac_id,
|
| 316 |
+
action_type=action_type,
|
| 317 |
+
runway_id=runway_id,
|
| 318 |
+
sequence_position=seq_pos,
|
| 319 |
+
))
|
| 320 |
+
|
| 321 |
+
except Exception:
|
| 322 |
+
pass
|
| 323 |
+
|
| 324 |
+
return actions
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def run_inference(task_id: int, model_name: str, api_base: str, api_key: str) -> Tuple[float, float, dict]:
|
| 328 |
+
"""Run inference on a single task."""
|
| 329 |
+
client = OpenAI(base_url=api_base, api_key=api_key)
|
| 330 |
+
env = ATCEnv(seed=42)
|
| 331 |
+
obs = env.reset(task_id)
|
| 332 |
+
episode_log = {"task_id": task_id, "steps": []}
|
| 333 |
+
all_step_rewards = []
|
| 334 |
+
log_start(task=f"task_{task_id}", env="atc-openenv", model=model_name)
|
| 335 |
+
|
| 336 |
+
step_num = 0
|
| 337 |
+
total_reward = 0.0
|
| 338 |
+
|
| 339 |
+
while not obs.episode_done:
|
| 340 |
+
step_num += 1
|
| 341 |
+
state = env.state()
|
| 342 |
+
state_dump = state.model_dump()
|
| 343 |
+
current_step = state_dump.get("timestep", step_num)
|
| 344 |
+
actions = []
|
| 345 |
+
error_msg = None
|
| 346 |
+
|
| 347 |
+
needs_action = sum(
|
| 348 |
+
1 for ac in state_dump.get("aircraft", [])
|
| 349 |
+
if ac.get("status") in ("INBOUND", "HOLDING")
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
if needs_action > 0:
|
| 353 |
+
if should_skip_llm(task_id, current_step):
|
| 354 |
+
# Use deterministic controller directly — faster and safer for critical steps
|
| 355 |
+
actions = get_fallback_action(env, task_id=task_id, current_step=current_step)
|
| 356 |
+
else:
|
| 357 |
+
# Use LLM with deterministic fallback
|
| 358 |
+
prompt = build_prompt(obs.model_dump(), state_dump, task_id)
|
| 359 |
+
try:
|
| 360 |
+
response = client.chat.completions.create(
|
| 361 |
+
model=model_name,
|
| 362 |
+
messages=[
|
| 363 |
+
{
|
| 364 |
+
"role": "system",
|
| 365 |
+
"content": (
|
| 366 |
+
"You are an expert ATC controller. "
|
| 367 |
+
"Respond with valid JSON only. No text outside the JSON block."
|
| 368 |
+
),
|
| 369 |
+
},
|
| 370 |
+
{"role": "user", "content": prompt},
|
| 371 |
+
],
|
| 372 |
+
temperature=0.0,
|
| 373 |
+
max_tokens=1500,
|
| 374 |
+
)
|
| 375 |
+
response_text = response.choices[0].message.content if response.choices else ""
|
| 376 |
+
action_dicts = parse_llm_response(response_text)
|
| 377 |
+
if action_dicts:
|
| 378 |
+
actions = apply_guardrails(action_dicts, state_dump)
|
| 379 |
+
except Exception as e:
|
| 380 |
+
error_msg = str(e)
|
| 381 |
+
|
| 382 |
+
# Fallback if LLM returned nothing or failed
|
| 383 |
+
if not actions:
|
| 384 |
+
actions = get_fallback_action(env, task_id=task_id, current_step=current_step)
|
| 385 |
+
|
| 386 |
+
obs, reward, done, info = env.step(action=actions)
|
| 387 |
+
total_reward += reward.value
|
| 388 |
+
all_step_rewards.append(reward.value)
|
| 389 |
+
|
| 390 |
+
episode_log["steps"].append({"step": step_num, "reward": reward.value})
|
| 391 |
+
|
| 392 |
+
action_str = (
|
| 393 |
+
json.dumps([a.model_dump() for a in actions]).replace(" ", "")
|
| 394 |
+
if actions else "none"
|
| 395 |
+
)
|
| 396 |
+
log_step(step=step_num, action=action_str, reward=reward.value, done=done, error=error_msg)
|
| 397 |
+
|
| 398 |
+
grader_inputs = env.get_grader_input()
|
| 399 |
+
episode_log["grader_input"] = grader_inputs
|
| 400 |
+
|
| 401 |
+
if task_id == 1:
|
| 402 |
+
final_score = grade1(grader_inputs)
|
| 403 |
+
elif task_id == 2:
|
| 404 |
+
final_score = grade2(grader_inputs)
|
| 405 |
+
else:
|
| 406 |
+
final_score = grade3(grader_inputs)
|
| 407 |
+
|
| 408 |
+
success = final_score >= 0.5
|
| 409 |
+
log_end(success=success, steps=step_num, score=final_score, rewards=all_step_rewards)
|
| 410 |
+
|
| 411 |
+
return final_score, total_reward, episode_log
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def main():
|
| 415 |
+
api_key = os.getenv("HF_TOKEN") or os.getenv("API_KEY") or "dummy-token"
|
| 416 |
+
api_base = os.getenv("API_BASE_URL") or "https://router.huggingface.co/v1"
|
| 417 |
+
model_name = os.getenv("MODEL_NAME") or "Qwen/Qwen2.5-72B-Instruct"
|
| 418 |
+
|
| 419 |
+
print(f"[DEBUG] Starting ATC inference with model: {model_name}")
|
| 420 |
+
print(f"[DEBUG] API base: {api_base}")
|
| 421 |
+
|
| 422 |
+
total_score = 0.0
|
| 423 |
+
results = []
|
| 424 |
+
|
| 425 |
+
for task_id in [1, 2, 3]:
|
| 426 |
+
print(f"\n[DEBUG] ===== Running Task {task_id} =====")
|
| 427 |
+
try:
|
| 428 |
+
score, reward, log = run_inference(task_id, model_name, api_base, api_key)
|
| 429 |
+
results.append({"task_id": task_id, "score": score, "reward": reward})
|
| 430 |
+
total_score += score
|
| 431 |
+
except Exception as e:
|
| 432 |
+
print(f"[DEBUG] Error running task {task_id}: {e}")
|
| 433 |
+
results.append({"task_id": task_id, "score": 0.0, "reward": 0.0})
|
| 434 |
+
|
| 435 |
+
avg_score = total_score / 3.0
|
| 436 |
+
|
| 437 |
+
print("\n" + "=" * 50)
|
| 438 |
+
print("[DEBUG] FINAL RESULTS")
|
| 439 |
+
print("=" * 50)
|
| 440 |
+
for r in results:
|
| 441 |
+
print(f"[DEBUG] Task {r['task_id']}: score={r['score']:.4f}, reward={r['reward']:.4f}")
|
| 442 |
+
print(f"[DEBUG] Average score: {avg_score:.4f}")
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
if __name__ == "__main__":
|
| 446 |
+
main()
|
atc-openenv/openenv.yaml
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: atc-openenv
|
| 2 |
+
version: "1.0.0"
|
| 3 |
+
description: "Air Traffic Control runway sequencing environment"
|
| 4 |
+
tags: [openenv, atc, scheduling, real-world]
|
| 5 |
+
action_space: discrete
|
| 6 |
+
observation_space: structured
|
| 7 |
+
tasks:
|
| 8 |
+
- id: 1
|
| 9 |
+
name: clear_skies
|
| 10 |
+
difficulty: easy
|
| 11 |
+
- id: 2
|
| 12 |
+
name: fuel_pressure
|
| 13 |
+
difficulty: medium
|
| 14 |
+
- id: 3
|
| 15 |
+
name: full_emergency
|
| 16 |
+
difficulty: hard
|
| 17 |
+
endpoints:
|
| 18 |
+
reset: POST /reset
|
| 19 |
+
step: POST /step
|
| 20 |
+
state: GET /state
|
atc-openenv/pyproject.toml
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=61.0"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "atc-openenv"
|
| 7 |
+
version = "1.0.0"
|
| 8 |
+
description = "Air Traffic Control Sequencing Environment for AI Agents"
|
| 9 |
+
readme = "README.md"
|
| 10 |
+
requires-python = ">=3.8"
|
| 11 |
+
dependencies = [
|
| 12 |
+
"fastapi",
|
| 13 |
+
"uvicorn",
|
| 14 |
+
"pydantic",
|
| 15 |
+
"openai",
|
| 16 |
+
"pyyaml",
|
| 17 |
+
"requests",
|
| 18 |
+
"matplotlib",
|
| 19 |
+
"numpy",
|
| 20 |
+
"openenv-core>=0.2.0"
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
[project.scripts]
|
| 24 |
+
server = "server.app:main"
|
atc-openenv/requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn
|
| 3 |
+
pydantic
|
| 4 |
+
openai
|
| 5 |
+
pyyaml
|
| 6 |
+
requests
|
| 7 |
+
# Visualization
|
| 8 |
+
matplotlib
|
| 9 |
+
numpy
|
atc-openenv/runway_algorithm.py
ADDED
|
@@ -0,0 +1,512 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Professional ATC System - Physics & Logic Core
|
| 3 |
+
Real-time movement, fuel consumption, conflict detection, and snapshot history for animation.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import math
|
| 7 |
+
import heapq
|
| 8 |
+
import random
|
| 9 |
+
import threading
|
| 10 |
+
import time as time_module
|
| 11 |
+
from dataclasses import dataclass, field
|
| 12 |
+
from typing import List, Dict, Optional, Tuple
|
| 13 |
+
from enum import Enum
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
import winsound
|
| 17 |
+
SOUND_AVAILABLE = True
|
| 18 |
+
except ImportError:
|
| 19 |
+
SOUND_AVAILABLE = False
|
| 20 |
+
|
| 21 |
+
# ============ CONSTANTS ============
|
| 22 |
+
NM_TO_KM = 1.852
|
| 23 |
+
FUEL_BURN_RATE_APPROACH = 0.8 # Min/min during approach
|
| 24 |
+
FUEL_BURN_RATE_HOLD = 1.5 # Min/min during hold
|
| 25 |
+
MIN_SEPARATION_NM = 3.0
|
| 26 |
+
MIN_VERTICAL_SEP_FT = 1000
|
| 27 |
+
|
| 28 |
+
SNAPSHOT_INTERVAL_STEPS = 10 # Capture state every N simulation steps for animation playback
|
| 29 |
+
|
| 30 |
+
# Wake Turbulence Separation (Minutes between landings)
|
| 31 |
+
WAKE_SEP = {
|
| 32 |
+
("HEAVY", "HEAVY"): 2.0,
|
| 33 |
+
("HEAVY", "MEDIUM"): 2.5,
|
| 34 |
+
("HEAVY", "LIGHT"): 3.0,
|
| 35 |
+
("MEDIUM", "HEAVY"): 1.5,
|
| 36 |
+
("MEDIUM", "MEDIUM"): 2.0,
|
| 37 |
+
("MEDIUM", "LIGHT"): 2.5,
|
| 38 |
+
("LIGHT", "HEAVY"): 1.5,
|
| 39 |
+
("LIGHT", "MEDIUM"): 2.0,
|
| 40 |
+
("LIGHT", "LIGHT"): 2.0,
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class Status(Enum):
|
| 45 |
+
APPROACHING = "APPROACHING"
|
| 46 |
+
HOLDING = "HOLDING"
|
| 47 |
+
FINAL_APPROACH = "FINAL_APPROACH"
|
| 48 |
+
LANDING = "LANDING"
|
| 49 |
+
LANDED = "LANDED"
|
| 50 |
+
TAXIING = "TAXIING"
|
| 51 |
+
EXITED = "EXITED"
|
| 52 |
+
CRASHED = "CRASHED"
|
| 53 |
+
GO_AROUND = "GO_AROUND"
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class Priority(Enum):
|
| 57 |
+
MAYDAY = 10000
|
| 58 |
+
PAN_PAN = 5000
|
| 59 |
+
CRITICAL_FUEL = 2000
|
| 60 |
+
LOW_FUEL = 1000
|
| 61 |
+
NORMAL = 100
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@dataclass
|
| 65 |
+
class Weather:
|
| 66 |
+
condition: str = "CLEAR"
|
| 67 |
+
wind_speed: float = 5.0
|
| 68 |
+
wind_dir: float = 270.0
|
| 69 |
+
visibility: float = 10.0
|
| 70 |
+
|
| 71 |
+
def get_separation_mult(self) -> float:
|
| 72 |
+
if self.condition == "STORM": return 1.5
|
| 73 |
+
if self.condition == "RAIN": return 1.2
|
| 74 |
+
return 1.0
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@dataclass
|
| 78 |
+
class Aircraft:
|
| 79 |
+
id: str
|
| 80 |
+
fuel_remaining: float # Minutes
|
| 81 |
+
wake_category: str
|
| 82 |
+
is_emergency: bool
|
| 83 |
+
|
| 84 |
+
# Physics State
|
| 85 |
+
distance_nm: float = 40.0 # Distance from threshold
|
| 86 |
+
altitude_ft: float = 4000.0
|
| 87 |
+
speed_kts: float = 250.0
|
| 88 |
+
heading_deg: float = 90.0 # Fixed inbound heading (aircraft approach from this direction)
|
| 89 |
+
|
| 90 |
+
# Scheduling
|
| 91 |
+
arrival_time: float = 0.0
|
| 92 |
+
landing_time: Optional[float] = None
|
| 93 |
+
assigned_runway: Optional[str] = None
|
| 94 |
+
wait_time: float = 0.0
|
| 95 |
+
|
| 96 |
+
# Status
|
| 97 |
+
status: Status = Status.APPROACHING
|
| 98 |
+
priority_score: float = 0.0
|
| 99 |
+
|
| 100 |
+
# Internal
|
| 101 |
+
initial_fuel: float = field(init=False)
|
| 102 |
+
initial_dist: float = field(init=False)
|
| 103 |
+
|
| 104 |
+
def __post_init__(self):
|
| 105 |
+
self.initial_fuel = self.fuel_remaining
|
| 106 |
+
self.initial_dist = self.distance_nm
|
| 107 |
+
self.wake_category = self.wake_category.upper()
|
| 108 |
+
# Give each aircraft a stable, unique inbound heading (spread around compass)
|
| 109 |
+
rng = random.Random(hash(self.id))
|
| 110 |
+
self.heading_deg = rng.uniform(0, 360)
|
| 111 |
+
self.calculate_priority()
|
| 112 |
+
|
| 113 |
+
@property
|
| 114 |
+
def eta_minutes(self) -> float:
|
| 115 |
+
if self.speed_kts > 0:
|
| 116 |
+
return (self.distance_nm / self.speed_kts) * 60.0
|
| 117 |
+
return float("inf")
|
| 118 |
+
|
| 119 |
+
def calculate_priority(self):
|
| 120 |
+
score = 0
|
| 121 |
+
if self.is_emergency: score += Priority.MAYDAY.value
|
| 122 |
+
elif self.fuel_remaining < 10: score += Priority.CRITICAL_FUEL.value
|
| 123 |
+
elif self.fuel_remaining < 20: score += Priority.LOW_FUEL.value
|
| 124 |
+
|
| 125 |
+
score += max(0, (100 - self.eta_minutes)) * 10
|
| 126 |
+
|
| 127 |
+
if self.wake_category == "HEAVY":
|
| 128 |
+
score += 50
|
| 129 |
+
self.priority_score = score
|
| 130 |
+
|
| 131 |
+
def update_physics(self, dt_seconds: float, weather: Weather):
|
| 132 |
+
"""Advance aircraft state by dt_seconds."""
|
| 133 |
+
if self.status in (Status.EXITED, Status.CRASHED):
|
| 134 |
+
return
|
| 135 |
+
|
| 136 |
+
dt_min = dt_seconds / 60.0
|
| 137 |
+
weather_factor = 1.0 + (weather.wind_speed / 100.0)
|
| 138 |
+
|
| 139 |
+
# --- Fuel Consumption ---
|
| 140 |
+
burn = FUEL_BURN_RATE_HOLD if self.status == Status.HOLDING else FUEL_BURN_RATE_APPROACH
|
| 141 |
+
self.fuel_remaining -= burn * dt_min * weather_factor
|
| 142 |
+
|
| 143 |
+
if self.fuel_remaining <= 0:
|
| 144 |
+
self.fuel_remaining = 0.0
|
| 145 |
+
self.status = Status.CRASHED
|
| 146 |
+
return
|
| 147 |
+
|
| 148 |
+
# --- Movement ---
|
| 149 |
+
if self.status == Status.APPROACHING:
|
| 150 |
+
move = (self.speed_kts / 60.0) * dt_min
|
| 151 |
+
self.distance_nm = max(0.0, self.distance_nm - move)
|
| 152 |
+
# Gradually descend toward pattern altitude
|
| 153 |
+
target_alt = max(500.0, self.distance_nm * 300.0)
|
| 154 |
+
if self.altitude_ft > target_alt:
|
| 155 |
+
self.altitude_ft = max(target_alt, self.altitude_ft - 500.0 * dt_min)
|
| 156 |
+
|
| 157 |
+
elif self.status == Status.HOLDING:
|
| 158 |
+
# Orbit: heading rotates, distance stays roughly constant (slight variation)
|
| 159 |
+
self.heading_deg = (self.heading_deg + 6.0 * dt_min) % 360.0
|
| 160 |
+
|
| 161 |
+
elif self.status == Status.FINAL_APPROACH:
|
| 162 |
+
self.speed_kts = max(130.0, self.speed_kts - 5.0 * dt_min)
|
| 163 |
+
move = (self.speed_kts / 60.0) * dt_min
|
| 164 |
+
self.distance_nm = max(0.0, self.distance_nm - move)
|
| 165 |
+
self.altitude_ft = max(0.0, self.altitude_ft - 400.0 * dt_min)
|
| 166 |
+
|
| 167 |
+
elif self.status == Status.LANDING:
|
| 168 |
+
# Decelerating roll-out
|
| 169 |
+
self.speed_kts = max(0.0, self.speed_kts - 20.0 * dt_min)
|
| 170 |
+
self.distance_nm = max(0.0, self.distance_nm - (self.speed_kts / 60.0) * dt_min)
|
| 171 |
+
self.altitude_ft = 0.0
|
| 172 |
+
|
| 173 |
+
elif self.status == Status.TAXIING:
|
| 174 |
+
self.altitude_ft = 0.0
|
| 175 |
+
self.speed_kts = 20.0
|
| 176 |
+
|
| 177 |
+
# Auto-upgrade to emergency on critically low fuel
|
| 178 |
+
if self.fuel_remaining < 5.0 and not self.is_emergency:
|
| 179 |
+
self.is_emergency = True
|
| 180 |
+
|
| 181 |
+
self.calculate_priority()
|
| 182 |
+
|
| 183 |
+
def get_cartesian_pos(self) -> Tuple[float, float]:
|
| 184 |
+
"""
|
| 185 |
+
Radar position: aircraft approaches from heading_deg toward (0,0).
|
| 186 |
+
As distance_nm decreases the blip moves toward the airport centre.
|
| 187 |
+
"""
|
| 188 |
+
rad = math.radians(self.heading_deg)
|
| 189 |
+
x = self.distance_nm * math.sin(rad)
|
| 190 |
+
y = self.distance_nm * math.cos(rad)
|
| 191 |
+
return x, y
|
| 192 |
+
|
| 193 |
+
def snapshot(self) -> Dict:
|
| 194 |
+
"""Return a lightweight state snapshot for animation playback."""
|
| 195 |
+
x, y = self.get_cartesian_pos()
|
| 196 |
+
return {
|
| 197 |
+
"id": self.id,
|
| 198 |
+
"x": x,
|
| 199 |
+
"y": y,
|
| 200 |
+
"fuel": self.fuel_remaining,
|
| 201 |
+
"fuel_pct": (self.fuel_remaining / self.initial_fuel * 100) if self.initial_fuel > 0 else 0,
|
| 202 |
+
"distance": self.distance_nm,
|
| 203 |
+
"altitude": self.altitude_ft,
|
| 204 |
+
"speed": self.speed_kts,
|
| 205 |
+
"heading": self.heading_deg,
|
| 206 |
+
"status": self.status.value,
|
| 207 |
+
"priority_score": self.priority_score,
|
| 208 |
+
"wake": self.wake_category,
|
| 209 |
+
"emergency": self.is_emergency,
|
| 210 |
+
"critical": self.fuel_remaining < 10.0,
|
| 211 |
+
"low_fuel": self.fuel_remaining < 20.0,
|
| 212 |
+
"runway": self.assigned_runway,
|
| 213 |
+
"landing_time": self.landing_time,
|
| 214 |
+
"wait_time": self.wait_time,
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
@dataclass
|
| 219 |
+
class RunwaySlot:
|
| 220 |
+
start_time: float # Simulation seconds
|
| 221 |
+
end_time: float
|
| 222 |
+
aircraft_id: str
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
class Runway:
|
| 226 |
+
def __init__(self, name: str, heading: float):
|
| 227 |
+
self.name = name
|
| 228 |
+
self.heading = heading
|
| 229 |
+
self.is_active = True
|
| 230 |
+
self.slots: List[RunwaySlot] = []
|
| 231 |
+
self.next_available: float = 0.0
|
| 232 |
+
self.last_wake: Optional[str] = None
|
| 233 |
+
|
| 234 |
+
def get_next_slot(self, ac: Aircraft, current_time: float,
|
| 235 |
+
weather: Weather) -> Tuple[float, float]:
|
| 236 |
+
if not self.is_active:
|
| 237 |
+
return float("inf"), 0.0
|
| 238 |
+
|
| 239 |
+
base_sep = WAKE_SEP.get((self.last_wake or "MEDIUM", ac.wake_category), 2.0)
|
| 240 |
+
sep_min = base_sep * weather.get_separation_mult()
|
| 241 |
+
sep_secs = sep_min * 60.0
|
| 242 |
+
|
| 243 |
+
slot_start = max(current_time, self.next_available)
|
| 244 |
+
return slot_start, sep_secs
|
| 245 |
+
|
| 246 |
+
def book_slot(self, ac: Aircraft, start: float, duration_secs: float, sep_secs: float):
|
| 247 |
+
self.slots.append(RunwaySlot(start, start + duration_secs, ac.id))
|
| 248 |
+
self.next_available = start + sep_secs
|
| 249 |
+
self.last_wake = ac.wake_category
|
| 250 |
+
|
| 251 |
+
def current_occupant(self, sim_time: float) -> Optional[str]:
|
| 252 |
+
for slot in self.slots:
|
| 253 |
+
if slot.start_time <= sim_time <= slot.end_time:
|
| 254 |
+
return slot.aircraft_id
|
| 255 |
+
return None
|
| 256 |
+
|
| 257 |
+
def runway_progress(self, sim_time: float) -> Optional[float]:
|
| 258 |
+
"""0.0 → 1.0 progress of current occupant through rollout."""
|
| 259 |
+
for slot in self.slots:
|
| 260 |
+
if slot.start_time <= sim_time <= slot.end_time:
|
| 261 |
+
dur = slot.end_time - slot.start_time
|
| 262 |
+
return (sim_time - slot.start_time) / dur if dur > 0 else 0.0
|
| 263 |
+
return None
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
class ConflictDetector:
|
| 267 |
+
@staticmethod
|
| 268 |
+
def check_conflicts(ac_list: List[Aircraft]) -> List[Tuple[str, str, float]]:
|
| 269 |
+
conflicts = []
|
| 270 |
+
active = [a for a in ac_list
|
| 271 |
+
if a.status not in (Status.EXITED, Status.CRASHED, Status.LANDED, Status.TAXIING)]
|
| 272 |
+
for i, a1 in enumerate(active):
|
| 273 |
+
for a2 in active[i + 1:]:
|
| 274 |
+
p1, p2 = a1.get_cartesian_pos(), a2.get_cartesian_pos()
|
| 275 |
+
dist_nm = math.hypot(p1[0] - p2[0], p1[1] - p2[1])
|
| 276 |
+
v_dist = abs(a1.altitude_ft - a2.altitude_ft)
|
| 277 |
+
if dist_nm < MIN_SEPARATION_NM and v_dist < MIN_VERTICAL_SEP_FT:
|
| 278 |
+
conflicts.append((a1.id, a2.id, dist_nm))
|
| 279 |
+
return conflicts
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
class ATCScheduler:
|
| 283 |
+
LANDING_DURATION_SECS = 90.0 # Seconds for one landing + roll-out
|
| 284 |
+
|
| 285 |
+
def __init__(self, task_level: int = 1):
|
| 286 |
+
self.task_level = task_level
|
| 287 |
+
self.runways = [Runway("RWY-09L", 90), Runway("RWY-27R", 270)]
|
| 288 |
+
self.weather = Weather("CLEAR", 5, 270, 10)
|
| 289 |
+
self.current_time = 0.0 # Simulation seconds
|
| 290 |
+
self.aircraft: List[Aircraft] = []
|
| 291 |
+
self.landed: List[Aircraft] = []
|
| 292 |
+
self.events: List[str] = []
|
| 293 |
+
self.metrics = {"crashes": 0, "efficiency": 0.0, "total_delay": 0.0}
|
| 294 |
+
|
| 295 |
+
if task_level == 2:
|
| 296 |
+
self.weather = Weather("RAIN", 15, 300, 5)
|
| 297 |
+
elif task_level == 3:
|
| 298 |
+
self.weather = Weather("STORM", 25, 290, 2)
|
| 299 |
+
self.runways[1].is_active = False
|
| 300 |
+
|
| 301 |
+
def add_aircraft(self, ac: Aircraft):
|
| 302 |
+
self.aircraft.append(ac)
|
| 303 |
+
|
| 304 |
+
def schedule_step(self, dt: float):
|
| 305 |
+
"""Advance simulation by dt seconds."""
|
| 306 |
+
self.current_time += dt
|
| 307 |
+
|
| 308 |
+
# 1. Update physics
|
| 309 |
+
for ac in self.aircraft:
|
| 310 |
+
ac.update_physics(dt, self.weather)
|
| 311 |
+
|
| 312 |
+
# 2. Conflict detection
|
| 313 |
+
for c in ConflictDetector.check_conflicts(self.aircraft):
|
| 314 |
+
msg = f"CONFLICT: {c[0]} & {c[1]} ({c[2]:.1f}nm)"
|
| 315 |
+
if not self.events or self.events[-1] != msg:
|
| 316 |
+
self.events.append(msg)
|
| 317 |
+
|
| 318 |
+
# 3. Assign unscheduled aircraft to runways
|
| 319 |
+
schedulable = [
|
| 320 |
+
a for a in self.aircraft
|
| 321 |
+
if a.status not in (Status.EXITED, Status.CRASHED, Status.LANDED,
|
| 322 |
+
Status.TAXIING, Status.FINAL_APPROACH,
|
| 323 |
+
Status.LANDING)
|
| 324 |
+
and a.landing_time is None
|
| 325 |
+
]
|
| 326 |
+
schedulable.sort(key=lambda x: x.priority_score, reverse=True)
|
| 327 |
+
|
| 328 |
+
for ac in schedulable:
|
| 329 |
+
best_rwy, best_time, best_sep = None, float("inf"), 0.0
|
| 330 |
+
for rwy in self.runways:
|
| 331 |
+
t, s = rwy.get_next_slot(ac, self.current_time, self.weather)
|
| 332 |
+
if t < best_time:
|
| 333 |
+
best_time, best_sep, best_rwy = t, s, rwy
|
| 334 |
+
|
| 335 |
+
if best_rwy:
|
| 336 |
+
ac.assigned_runway = best_rwy.name
|
| 337 |
+
ac.landing_time = best_time
|
| 338 |
+
ac.wait_time = max(0.0, best_time - self.current_time)
|
| 339 |
+
ac.status = Status.FINAL_APPROACH
|
| 340 |
+
best_rwy.book_slot(ac, best_time, self.LANDING_DURATION_SECS, best_sep)
|
| 341 |
+
|
| 342 |
+
phrase = "EXPEDITE LANDING" if ac.is_emergency else "CLEARED TO LAND"
|
| 343 |
+
self.events.append(f"{ac.id}: {phrase} {best_rwy.name}")
|
| 344 |
+
|
| 345 |
+
if ac.is_emergency and SOUND_AVAILABLE:
|
| 346 |
+
try:
|
| 347 |
+
t = threading.Thread(target=lambda: winsound.Beep(1000, 300), daemon=True)
|
| 348 |
+
t.start()
|
| 349 |
+
except Exception:
|
| 350 |
+
pass
|
| 351 |
+
|
| 352 |
+
# 4. State transitions driven by landing_time
|
| 353 |
+
for ac in self.aircraft:
|
| 354 |
+
if ac.landing_time is None:
|
| 355 |
+
continue
|
| 356 |
+
lt = ac.landing_time
|
| 357 |
+
t = self.current_time
|
| 358 |
+
if ac.status == Status.FINAL_APPROACH and t >= lt:
|
| 359 |
+
ac.status = Status.LANDING
|
| 360 |
+
elif ac.status == Status.LANDING and t >= lt + self.LANDING_DURATION_SECS * 0.5:
|
| 361 |
+
ac.status = Status.LANDED
|
| 362 |
+
ac.speed_kts = 30.0
|
| 363 |
+
elif ac.status == Status.LANDED and t >= lt + self.LANDING_DURATION_SECS:
|
| 364 |
+
ac.status = Status.TAXIING
|
| 365 |
+
elif ac.status == Status.TAXIING and t >= lt + self.LANDING_DURATION_SECS * 2:
|
| 366 |
+
ac.status = Status.EXITED
|
| 367 |
+
if ac not in self.landed:
|
| 368 |
+
self.landed.append(ac)
|
| 369 |
+
|
| 370 |
+
# 5. Metrics
|
| 371 |
+
self.metrics["crashes"] = sum(1 for a in self.aircraft if a.status == Status.CRASHED)
|
| 372 |
+
self.metrics["total_delay"] = sum(a.wait_time for a in self.aircraft if a.wait_time > 0)
|
| 373 |
+
processed = len(self.landed) + self.metrics["crashes"]
|
| 374 |
+
if processed > 0:
|
| 375 |
+
on_time = sum(1 for a in self.landed if a.wait_time < 300) # < 5 min wait
|
| 376 |
+
self.metrics["efficiency"] = (on_time / processed) * 100.0
|
| 377 |
+
|
| 378 |
+
def get_scores(self) -> Dict:
|
| 379 |
+
n = len(self.aircraft)
|
| 380 |
+
if n == 0:
|
| 381 |
+
return {"score": 0.0, "reward": 0.0}
|
| 382 |
+
crash_pen = self.metrics["crashes"] / n
|
| 383 |
+
delay_pen = min(1.0, self.metrics["total_delay"] / (n * 1800)) # 30 min baseline
|
| 384 |
+
score = max(0.0, 1.0 - (crash_pen * 0.5 + delay_pen * 0.5))
|
| 385 |
+
if self.task_level == 3:
|
| 386 |
+
score *= 0.9
|
| 387 |
+
return {"score": round(score, 4), "reward": round(score * 10.0, 2)}
|
| 388 |
+
|
| 389 |
+
def snapshot(self) -> Dict:
|
| 390 |
+
"""Capture full state for a single animation frame."""
|
| 391 |
+
return {
|
| 392 |
+
"sim_time": self.current_time,
|
| 393 |
+
"aircraft": [ac.snapshot() for ac in self.aircraft],
|
| 394 |
+
"events": list(self.events[-8:]),
|
| 395 |
+
"metrics": dict(self.metrics),
|
| 396 |
+
"runways": [
|
| 397 |
+
{
|
| 398 |
+
"name": rw.name,
|
| 399 |
+
"is_active": rw.is_active,
|
| 400 |
+
"occupant": rw.current_occupant(self.current_time),
|
| 401 |
+
"progress": rw.runway_progress(self.current_time),
|
| 402 |
+
"slots": [{"start": s.start_time, "end": s.end_time, "id": s.aircraft_id}
|
| 403 |
+
for s in rw.slots],
|
| 404 |
+
}
|
| 405 |
+
for rw in self.runways
|
| 406 |
+
],
|
| 407 |
+
}
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
# ─────────────────────────────────────────────
|
| 411 |
+
# Task Scenario Definitions
|
| 412 |
+
# ─────────────────────────────────────────────
|
| 413 |
+
|
| 414 |
+
def get_task_data(level: int) -> List[Dict]:
|
| 415 |
+
"""Return aircraft spawn data for each task level."""
|
| 416 |
+
data = []
|
| 417 |
+
if level == 1:
|
| 418 |
+
configs = [
|
| 419 |
+
("FL101", 55, "HEAVY", False, 25),
|
| 420 |
+
("FL102", 48, "MEDIUM", False, 32),
|
| 421 |
+
("FL103", 60, "LIGHT", False, 18),
|
| 422 |
+
("FL104", 52, "MEDIUM", False, 40),
|
| 423 |
+
("FL105", 45, "HEAVY", False, 15),
|
| 424 |
+
]
|
| 425 |
+
elif level == 2:
|
| 426 |
+
configs = [
|
| 427 |
+
("FL201", 50, "HEAVY", False, 20),
|
| 428 |
+
("FL202", 45, "MEDIUM", False, 28),
|
| 429 |
+
("FL203", 16, "LIGHT", False, 30), # FUEL_CRITICAL (ETA ~8 min, fuel=16)
|
| 430 |
+
("FL204", 55, "HEAVY", False, 35),
|
| 431 |
+
("FL205", 25, "MEDIUM", False, 40),
|
| 432 |
+
("FL206", 22, "LIGHT", False, 45), # FUEL_CRITICAL (ETA ~13 min, fuel=22)
|
| 433 |
+
("FL207", 48, "HEAVY", False, 20),
|
| 434 |
+
("FL208", 35, "MEDIUM", False, 50),
|
| 435 |
+
("FL209", 30, "LIGHT", False, 55),
|
| 436 |
+
("FL210", 42, "MEDIUM", False, 12),
|
| 437 |
+
]
|
| 438 |
+
else:
|
| 439 |
+
configs = [
|
| 440 |
+
("FL301", 55, "HEAVY", False, 12),
|
| 441 |
+
("FL302", 55, "MEDIUM", False, 18),
|
| 442 |
+
("FL303", 55, "LIGHT", False, 22),
|
| 443 |
+
("FL304", 60, "HEAVY", False, 28),
|
| 444 |
+
("FL305", 55, "MEDIUM", False, 32),
|
| 445 |
+
("FL306", 55, "LIGHT", False, 38),
|
| 446 |
+
("FL307", 58, "HEAVY", False, 42),
|
| 447 |
+
("FL308", 55, "MEDIUM", False, 48),
|
| 448 |
+
("FL309", 55, "LIGHT", False, 52),
|
| 449 |
+
("FL310", 52, "HEAVY", True, 8), # EMERGENCY
|
| 450 |
+
("FL311", 55, "MEDIUM", False, 55),
|
| 451 |
+
("FL312", 55, "LIGHT", False, 60),
|
| 452 |
+
("FL313", 55, "HEAVY", False, 15),
|
| 453 |
+
("FL314", 55, "MEDIUM", False, 65),
|
| 454 |
+
("FL315", 55, "LIGHT", False, 70),
|
| 455 |
+
]
|
| 456 |
+
return [
|
| 457 |
+
{"id": c[0], "fuel": c[1], "wake": c[2], "emerg": c[3], "dist": c[4]}
|
| 458 |
+
for c in configs
|
| 459 |
+
]
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
# ─────────────────────────────────────────────
|
| 463 |
+
# Main entry point
|
| 464 |
+
# ─────────────────────────────────────────────
|
| 465 |
+
|
| 466 |
+
def run_simulation(level: int, sim_duration_secs: float = 3600.0,
|
| 467 |
+
dt: float = 1.0) -> Dict:
|
| 468 |
+
"""
|
| 469 |
+
Run the full ATC simulation and return timestep snapshots for animation.
|
| 470 |
+
|
| 471 |
+
Returns:
|
| 472 |
+
{
|
| 473 |
+
"snapshots": List[Dict], # One per SNAPSHOT_INTERVAL_STEPS steps
|
| 474 |
+
"weather": Weather,
|
| 475 |
+
"scores": Dict,
|
| 476 |
+
"final_metrics": Dict,
|
| 477 |
+
"task_level": int,
|
| 478 |
+
}
|
| 479 |
+
"""
|
| 480 |
+
sched = ATCScheduler(level)
|
| 481 |
+
for d in get_task_data(level):
|
| 482 |
+
sched.add_aircraft(Aircraft(
|
| 483 |
+
id=d["id"], fuel_remaining=d["fuel"], wake_category=d["wake"],
|
| 484 |
+
is_emergency=d["emerg"], distance_nm=d["dist"],
|
| 485 |
+
))
|
| 486 |
+
|
| 487 |
+
snapshots: List[Dict] = []
|
| 488 |
+
steps = int(sim_duration_secs / dt)
|
| 489 |
+
|
| 490 |
+
for step in range(steps):
|
| 491 |
+
sched.schedule_step(dt)
|
| 492 |
+
|
| 493 |
+
# Capture snapshot every N steps
|
| 494 |
+
if step % SNAPSHOT_INTERVAL_STEPS == 0:
|
| 495 |
+
snapshots.append(sched.snapshot())
|
| 496 |
+
|
| 497 |
+
# Early exit if all aircraft resolved
|
| 498 |
+
all_done = all(
|
| 499 |
+
a.status in (Status.EXITED, Status.CRASHED)
|
| 500 |
+
for a in sched.aircraft
|
| 501 |
+
)
|
| 502 |
+
if all_done:
|
| 503 |
+
snapshots.append(sched.snapshot())
|
| 504 |
+
break
|
| 505 |
+
|
| 506 |
+
return {
|
| 507 |
+
"snapshots": snapshots,
|
| 508 |
+
"weather": sched.weather,
|
| 509 |
+
"scores": sched.get_scores(),
|
| 510 |
+
"final_metrics": sched.metrics,
|
| 511 |
+
"task_level": level,
|
| 512 |
+
}
|
atc-openenv/server/app.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FastAPI wrapper for ATC OpenEnv environment."""
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
from fastapi import FastAPI, HTTPException
|
| 5 |
+
from pydantic import BaseModel
|
| 6 |
+
|
| 7 |
+
from env.atc_env import ATCEnv, Action, Observation, State
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
app = FastAPI(title="ATC OpenEnv", version="1.0.0")
|
| 11 |
+
|
| 12 |
+
_env: Optional[ATCEnv] = None
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class ResetRequest(BaseModel):
|
| 16 |
+
task_id: int = 1
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class StepRequest(BaseModel):
|
| 20 |
+
actions: list[Action]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@app.get("/health")
|
| 24 |
+
def health():
|
| 25 |
+
"""Health check endpoint."""
|
| 26 |
+
return {"status": "ok"}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@app.post("/reset")
|
| 30 |
+
def reset(task_id: int = 1) -> Observation:
|
| 31 |
+
"""Reset environment with specified task."""
|
| 32 |
+
global _env
|
| 33 |
+
_env = ATCEnv(seed=42)
|
| 34 |
+
return _env.reset(task_id)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@app.post("/step")
|
| 38 |
+
def step(request: StepRequest) -> tuple[Observation, float, bool, dict]:
|
| 39 |
+
"""Execute actions and return next observation."""
|
| 40 |
+
if _env is None:
|
| 41 |
+
raise HTTPException(status_code=400, detail="Environment not initialized. Call /reset first.")
|
| 42 |
+
|
| 43 |
+
obs, reward, done, info = _env.step(request.actions)
|
| 44 |
+
return obs, reward.value, done, info
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@app.get("/state")
|
| 48 |
+
def state() -> State:
|
| 49 |
+
"""Get current environment state."""
|
| 50 |
+
if _env is None:
|
| 51 |
+
raise HTTPException(status_code=400, detail="Environment not initialized. Call /reset first.")
|
| 52 |
+
return _env.state()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@app.get("/")
|
| 56 |
+
def read_root():
|
| 57 |
+
"""Root endpoint to verify the server is running."""
|
| 58 |
+
return {"message": "Server is running! The API is ready for the model."}
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def main():
|
| 62 |
+
import uvicorn
|
| 63 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
if __name__ == "__main__":
|
| 67 |
+
main()
|
atc-openenv/tasks/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Task definitions."""
|
| 2 |
+
from tasks.task1_clear_skies import Task1ClearSkies
|
| 3 |
+
from tasks.task2_fuel_pressure import Task2FuelPressure
|
| 4 |
+
from tasks.task3_full_emergency import Task3FullEmergency
|
| 5 |
+
|
| 6 |
+
__all__ = ["Task1ClearSkies", "Task2FuelPressure", "Task3FullEmergency"]
|
atc-openenv/tasks/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (479 Bytes). View file
|
|
|
atc-openenv/tasks/__pycache__/task1_clear_skies.cpython-311.pyc
ADDED
|
Binary file (3.19 kB). View file
|
|
|
atc-openenv/tasks/__pycache__/task2_fuel_pressure.cpython-311.pyc
ADDED
|
Binary file (4.75 kB). View file
|
|
|
atc-openenv/tasks/__pycache__/task3_full_emergency.cpython-311.pyc
ADDED
|
Binary file (7.61 kB). View file
|
|
|
atc-openenv/tasks/task1_clear_skies.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Task 1: Clear Skies - Basic scenario with calm conditions."""
|
| 2 |
+
import random
|
| 3 |
+
from typing import List, Optional
|
| 4 |
+
|
| 5 |
+
from env.aircraft import Aircraft, AircraftType, Priority, AircraftStatus
|
| 6 |
+
from env.runway import Runway, RunwayStatus
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Task1ClearSkies:
|
| 10 |
+
"""5 aircraft, 2 runways (both OPEN), all fuel > 40min, no emergencies."""
|
| 11 |
+
|
| 12 |
+
@staticmethod
|
| 13 |
+
def get_config() -> dict:
|
| 14 |
+
return {
|
| 15 |
+
"max_steps": 20,
|
| 16 |
+
"aircraft_count": 5,
|
| 17 |
+
"runway_count": 2,
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
@staticmethod
|
| 21 |
+
def create_aircraft(rng: Optional[random.Random] = None) -> List[Aircraft]:
|
| 22 |
+
if rng is None:
|
| 23 |
+
import random
|
| 24 |
+
rng = random.Random(42)
|
| 25 |
+
|
| 26 |
+
distances = [5, 8, 12, 15, 20]
|
| 27 |
+
speeds = [180, 200, 220, 160, 190]
|
| 28 |
+
types = [
|
| 29 |
+
AircraftType.HEAVY,
|
| 30 |
+
AircraftType.HEAVY,
|
| 31 |
+
AircraftType.MEDIUM,
|
| 32 |
+
AircraftType.MEDIUM,
|
| 33 |
+
AircraftType.LIGHT,
|
| 34 |
+
]
|
| 35 |
+
fuels = [60, 55, 50, 65, 45]
|
| 36 |
+
|
| 37 |
+
aircraft = []
|
| 38 |
+
for i in range(5):
|
| 39 |
+
aircraft.append(Aircraft(
|
| 40 |
+
id=f"AC{i+1}",
|
| 41 |
+
aircraft_type=types[i],
|
| 42 |
+
priority=Priority.NORMAL,
|
| 43 |
+
status=AircraftStatus.INBOUND,
|
| 44 |
+
distance_nm=float(distances[i]),
|
| 45 |
+
speed_knots=float(speeds[i]),
|
| 46 |
+
fuel_remaining_min=float(fuels[i]),
|
| 47 |
+
))
|
| 48 |
+
return aircraft
|
| 49 |
+
|
| 50 |
+
@staticmethod
|
| 51 |
+
def create_runways() -> List[Runway]:
|
| 52 |
+
return [
|
| 53 |
+
Runway(id="RW01", status=RunwayStatus.OPEN),
|
| 54 |
+
Runway(id="RW02", status=RunwayStatus.OPEN),
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
@staticmethod
|
| 58 |
+
def get_pending_arrivals() -> List[dict]:
|
| 59 |
+
return []
|
atc-openenv/tasks/task2_fuel_pressure.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Task 2: Fuel Pressure - Increased traffic with fuel-critical aircraft."""
|
| 2 |
+
import random
|
| 3 |
+
from typing import List, Optional
|
| 4 |
+
|
| 5 |
+
from env.aircraft import Aircraft, AircraftType, Priority, AircraftStatus
|
| 6 |
+
from env.runway import Runway, RunwayStatus
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Task2FuelPressure:
|
| 10 |
+
"""10 aircraft, 2 runways (one REDUCED), fuel-critical aircraft, new arrivals at step 5.
|
| 11 |
+
|
| 12 |
+
DESIGN INVARIANT: Every aircraft must be physically saveable with optimal play.
|
| 13 |
+
- AC3: fuel=16, dist=30, speed=220 → ETA=8.2 steps. fuel(16) > ETA(8.2) ✓
|
| 14 |
+
- AC6: fuel=22, dist=45, speed=210 → ETA=12.9 steps. fuel(22) > ETA(12.9) ✓
|
| 15 |
+
Both are FUEL_CRITICAL priority at spawn, requiring expedite handling.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
@staticmethod
|
| 19 |
+
def get_config() -> dict:
|
| 20 |
+
return {
|
| 21 |
+
"max_steps": 30,
|
| 22 |
+
"aircraft_count": 10,
|
| 23 |
+
"runway_count": 2,
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
@staticmethod
|
| 27 |
+
def create_aircraft(rng: Optional[random.Random] = None) -> List[Aircraft]:
|
| 28 |
+
if rng is None:
|
| 29 |
+
import random
|
| 30 |
+
rng = random.Random(42)
|
| 31 |
+
|
| 32 |
+
aircraft = [
|
| 33 |
+
Aircraft(id="AC1", aircraft_type=AircraftType.HEAVY, priority=Priority.NORMAL,
|
| 34 |
+
status=AircraftStatus.INBOUND, distance_nm=15.0, speed_knots=180, fuel_remaining_min=50.0),
|
| 35 |
+
Aircraft(id="AC2", aircraft_type=AircraftType.MEDIUM, priority=Priority.NORMAL,
|
| 36 |
+
status=AircraftStatus.INBOUND, distance_nm=25.0, speed_knots=200, fuel_remaining_min=45.0),
|
| 37 |
+
# BUG FIX: was fuel=10. ETA=8.2, so fuel=16 gives safe buffer.
|
| 38 |
+
Aircraft(id="AC3", aircraft_type=AircraftType.LIGHT, priority=Priority.FUEL_CRITICAL,
|
| 39 |
+
status=AircraftStatus.INBOUND, distance_nm=30.0, speed_knots=220, fuel_remaining_min=16.0),
|
| 40 |
+
Aircraft(id="AC4", aircraft_type=AircraftType.HEAVY, priority=Priority.NORMAL,
|
| 41 |
+
status=AircraftStatus.INBOUND, distance_nm=35.0, speed_knots=170, fuel_remaining_min=55.0),
|
| 42 |
+
Aircraft(id="AC5", aircraft_type=AircraftType.MEDIUM, priority=Priority.NORMAL,
|
| 43 |
+
status=AircraftStatus.INBOUND, distance_nm=40.0, speed_knots=190, fuel_remaining_min=25.0),
|
| 44 |
+
# BUG FIX: was fuel=11. ETA=12.9, so fuel=22 gives safe buffer.
|
| 45 |
+
Aircraft(id="AC6", aircraft_type=AircraftType.LIGHT, priority=Priority.FUEL_CRITICAL,
|
| 46 |
+
status=AircraftStatus.INBOUND, distance_nm=45.0, speed_knots=210, fuel_remaining_min=22.0),
|
| 47 |
+
Aircraft(id="AC7", aircraft_type=AircraftType.HEAVY, priority=Priority.NORMAL,
|
| 48 |
+
status=AircraftStatus.INBOUND, distance_nm=20.0, speed_knots=175, fuel_remaining_min=48.0),
|
| 49 |
+
Aircraft(id="AC8", aircraft_type=AircraftType.MEDIUM, priority=Priority.NORMAL,
|
| 50 |
+
status=AircraftStatus.INBOUND, distance_nm=50.0, speed_knots=195, fuel_remaining_min=35.0),
|
| 51 |
+
Aircraft(id="AC9", aircraft_type=AircraftType.LIGHT, priority=Priority.NORMAL,
|
| 52 |
+
status=AircraftStatus.INBOUND, distance_nm=55.0, speed_knots=230, fuel_remaining_min=30.0),
|
| 53 |
+
Aircraft(id="AC10", aircraft_type=AircraftType.MEDIUM, priority=Priority.NORMAL,
|
| 54 |
+
status=AircraftStatus.INBOUND, distance_nm=12.0, speed_knots=185, fuel_remaining_min=42.0),
|
| 55 |
+
]
|
| 56 |
+
return aircraft
|
| 57 |
+
|
| 58 |
+
@staticmethod
|
| 59 |
+
def create_runways() -> List[Runway]:
|
| 60 |
+
return [
|
| 61 |
+
Runway(id="RW01", status=RunwayStatus.OPEN),
|
| 62 |
+
Runway(id="RW02", status=RunwayStatus.REDUCED),
|
| 63 |
+
]
|
| 64 |
+
|
| 65 |
+
@staticmethod
|
| 66 |
+
def get_pending_arrivals() -> List[dict]:
|
| 67 |
+
return [
|
| 68 |
+
{
|
| 69 |
+
"arrival_step": 5,
|
| 70 |
+
"id": "AC11",
|
| 71 |
+
"aircraft_type": "MEDIUM",
|
| 72 |
+
"priority": "NORMAL",
|
| 73 |
+
"distance_nm": 60.0,
|
| 74 |
+
"speed_knots": 200,
|
| 75 |
+
"fuel_remaining_min": 40.0,
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"arrival_step": 5,
|
| 79 |
+
"id": "AC12",
|
| 80 |
+
"aircraft_type": "LIGHT",
|
| 81 |
+
"priority": "NORMAL",
|
| 82 |
+
"distance_nm": 65.0,
|
| 83 |
+
"speed_knots": 215,
|
| 84 |
+
"fuel_remaining_min": 38.0,
|
| 85 |
+
},
|
| 86 |
+
]
|
atc-openenv/tasks/task3_full_emergency.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Task 3: Full Emergency - Complex scenario with emergencies and runway closure."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
from typing import TYPE_CHECKING
|
| 4 |
+
import random
|
| 5 |
+
from typing import List, Optional
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING:
|
| 8 |
+
from env.atc_env import ATCEnv
|
| 9 |
+
|
| 10 |
+
from env.aircraft import Aircraft, AircraftType, Priority, AircraftStatus
|
| 11 |
+
from env.runway import Runway, RunwayStatus
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class Task3FullEmergency:
|
| 15 |
+
"""15 aircraft, 2 runways, runway closes at step 3, emergency at step 5, continuous arrivals.
|
| 16 |
+
|
| 17 |
+
DESIGN INVARIANTS:
|
| 18 |
+
1. Every aircraft has enough fuel to survive the full 40-step episode (fuel >= 42).
|
| 19 |
+
This prevents unavoidable fuel exhaustions from killing the fuel_score component.
|
| 20 |
+
2. RW02 closes at step 3. On closure, aircraft ASSIGNED to RW02 are reset to HOLDING
|
| 21 |
+
so the controller can immediately reassign them — no aircraft gets permanently stranded.
|
| 22 |
+
3. Total aircraft = 23. With fixed runway throughput (sep=2 for RW01), up to 20 can land
|
| 23 |
+
on RW01 in steps 3-40, plus 2 on RW02 in steps 1-2 = 22 possible landings.
|
| 24 |
+
4. Queue measurement counts only INBOUND+HOLDING. New arrivals come in pairs of 2,
|
| 25 |
+
so max queue spike = 2 per batch, well under the 12-aircraft threshold.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
@staticmethod
|
| 29 |
+
def get_config() -> dict:
|
| 30 |
+
return {
|
| 31 |
+
"max_steps": 40,
|
| 32 |
+
"aircraft_count": 15,
|
| 33 |
+
"runway_count": 2,
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
@staticmethod
|
| 37 |
+
def create_aircraft(rng: Optional[random.Random] = None) -> List[Aircraft]:
|
| 38 |
+
if rng is None:
|
| 39 |
+
import random
|
| 40 |
+
rng = random.Random(42)
|
| 41 |
+
|
| 42 |
+
# All aircraft have fuel >= 42 so they can survive the full 40-step episode
|
| 43 |
+
# even if they end up in queue position 15+ and don't land before the episode ends.
|
| 44 |
+
# Previously AC14 (fuel=30), AC15 (fuel=28), AC11 (fuel=35), AC12 (fuel=32) etc.
|
| 45 |
+
# would exhaust fuel mid-episode making fuel_score = 0 unavoidable.
|
| 46 |
+
aircraft = [
|
| 47 |
+
Aircraft(id="AC1", aircraft_type=AircraftType.HEAVY, priority=Priority.NORMAL,
|
| 48 |
+
status=AircraftStatus.INBOUND, distance_nm=12.0, speed_knots=175, fuel_remaining_min=55.0),
|
| 49 |
+
Aircraft(id="AC2", aircraft_type=AircraftType.MEDIUM, priority=Priority.NORMAL,
|
| 50 |
+
status=AircraftStatus.INBOUND, distance_nm=18.0, speed_knots=195, fuel_remaining_min=55.0),
|
| 51 |
+
Aircraft(id="AC3", aircraft_type=AircraftType.LIGHT, priority=Priority.NORMAL,
|
| 52 |
+
status=AircraftStatus.INBOUND, distance_nm=22.0, speed_knots=220, fuel_remaining_min=55.0),
|
| 53 |
+
Aircraft(id="AC4", aircraft_type=AircraftType.HEAVY, priority=Priority.NORMAL,
|
| 54 |
+
status=AircraftStatus.INBOUND, distance_nm=28.0, speed_knots=170, fuel_remaining_min=60.0),
|
| 55 |
+
Aircraft(id="AC5", aircraft_type=AircraftType.MEDIUM, priority=Priority.NORMAL,
|
| 56 |
+
status=AircraftStatus.INBOUND, distance_nm=32.0, speed_knots=200, fuel_remaining_min=55.0),
|
| 57 |
+
Aircraft(id="AC6", aircraft_type=AircraftType.LIGHT, priority=Priority.NORMAL,
|
| 58 |
+
status=AircraftStatus.INBOUND, distance_nm=38.0, speed_knots=230, fuel_remaining_min=55.0),
|
| 59 |
+
Aircraft(id="AC7", aircraft_type=AircraftType.HEAVY, priority=Priority.NORMAL,
|
| 60 |
+
status=AircraftStatus.INBOUND, distance_nm=42.0, speed_knots=165, fuel_remaining_min=58.0),
|
| 61 |
+
Aircraft(id="AC8", aircraft_type=AircraftType.MEDIUM, priority=Priority.NORMAL,
|
| 62 |
+
status=AircraftStatus.INBOUND, distance_nm=48.0, speed_knots=190, fuel_remaining_min=55.0),
|
| 63 |
+
Aircraft(id="AC9", aircraft_type=AircraftType.LIGHT, priority=Priority.NORMAL,
|
| 64 |
+
status=AircraftStatus.INBOUND, distance_nm=52.0, speed_knots=225, fuel_remaining_min=55.0),
|
| 65 |
+
# AC10: will become EMERGENCY at step 5 — closest aircraft, lands early
|
| 66 |
+
Aircraft(id="AC10", aircraft_type=AircraftType.HEAVY, priority=Priority.NORMAL,
|
| 67 |
+
status=AircraftStatus.INBOUND, distance_nm=8.0, speed_knots=180, fuel_remaining_min=52.0),
|
| 68 |
+
# BUG FIX: was fuel=35. Needs >= 42 to survive full 40 steps.
|
| 69 |
+
Aircraft(id="AC11", aircraft_type=AircraftType.MEDIUM, priority=Priority.NORMAL,
|
| 70 |
+
status=AircraftStatus.INBOUND, distance_nm=55.0, speed_knots=205, fuel_remaining_min=55.0),
|
| 71 |
+
# BUG FIX: was fuel=32. Needs >= 42 to survive full 40 steps.
|
| 72 |
+
Aircraft(id="AC12", aircraft_type=AircraftType.LIGHT, priority=Priority.NORMAL,
|
| 73 |
+
status=AircraftStatus.INBOUND, distance_nm=60.0, speed_knots=235, fuel_remaining_min=55.0),
|
| 74 |
+
Aircraft(id="AC13", aircraft_type=AircraftType.HEAVY, priority=Priority.NORMAL,
|
| 75 |
+
status=AircraftStatus.INBOUND, distance_nm=15.0, speed_knots=172, fuel_remaining_min=55.0),
|
| 76 |
+
# BUG FIX: was fuel=30. ETA ~20 steps + queue wait would exceed 30 fuel.
|
| 77 |
+
Aircraft(id="AC14", aircraft_type=AircraftType.MEDIUM, priority=Priority.NORMAL,
|
| 78 |
+
status=AircraftStatus.INBOUND, distance_nm=65.0, speed_knots=192, fuel_remaining_min=55.0),
|
| 79 |
+
# BUG FIX: was fuel=28. ETA ~18 steps + queue wait would exceed 28 fuel.
|
| 80 |
+
Aircraft(id="AC15", aircraft_type=AircraftType.LIGHT, priority=Priority.NORMAL,
|
| 81 |
+
status=AircraftStatus.INBOUND, distance_nm=70.0, speed_knots=228, fuel_remaining_min=55.0),
|
| 82 |
+
]
|
| 83 |
+
return aircraft
|
| 84 |
+
|
| 85 |
+
@staticmethod
|
| 86 |
+
def create_runways() -> List[Runway]:
|
| 87 |
+
return [
|
| 88 |
+
Runway(id="RW01", status=RunwayStatus.OPEN),
|
| 89 |
+
Runway(id="RW02", status=RunwayStatus.OPEN),
|
| 90 |
+
]
|
| 91 |
+
|
| 92 |
+
@staticmethod
|
| 93 |
+
def get_pending_arrivals() -> List[dict]:
|
| 94 |
+
"""4 batches of 2 aircraft arriving at steps 4, 8, 12, 16.
|
| 95 |
+
All have fuel >= 42 to survive until episode end at step 40.
|
| 96 |
+
"""
|
| 97 |
+
arrivals = []
|
| 98 |
+
for batch in range(4):
|
| 99 |
+
step = 4 + batch * 4
|
| 100 |
+
arrivals.extend([
|
| 101 |
+
{
|
| 102 |
+
"arrival_step": step,
|
| 103 |
+
"id": f"AC{16 + batch * 2}",
|
| 104 |
+
"aircraft_type": "MEDIUM",
|
| 105 |
+
"priority": "NORMAL",
|
| 106 |
+
"distance_nm": 75.0 + batch * 5,
|
| 107 |
+
"speed_knots": 200,
|
| 108 |
+
# Fuel = 45 - batch*3. Arrives at step 4,8,12,16.
|
| 109 |
+
# Worst case: arrives at step 16 with fuel=33, episode ends at 40 (24 more steps). 33>24 ✓
|
| 110 |
+
"fuel_remaining_min": 45.0 - batch * 3,
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"arrival_step": step,
|
| 114 |
+
"id": f"AC{17 + batch * 2}",
|
| 115 |
+
"aircraft_type": "LIGHT",
|
| 116 |
+
"priority": "NORMAL",
|
| 117 |
+
"distance_nm": 80.0 + batch * 5,
|
| 118 |
+
"speed_knots": 220,
|
| 119 |
+
# Fuel = 42 - batch*3. Worst: step 16 with fuel=30, 24 steps remain. 30>24 ✓
|
| 120 |
+
"fuel_remaining_min": 42.0 - batch * 3,
|
| 121 |
+
},
|
| 122 |
+
])
|
| 123 |
+
return arrivals
|
| 124 |
+
|
| 125 |
+
def process_step_event(self, env: "ATCEnv", step: int) -> None:
|
| 126 |
+
"""Handle dynamic events: runway closure at step 3, emergency declaration at step 5."""
|
| 127 |
+
if step == 3:
|
| 128 |
+
for runway in env._runways:
|
| 129 |
+
if runway.id == "RW02":
|
| 130 |
+
runway.close()
|
| 131 |
+
# BUG FIX (Bug 6): When RW02 closes, reset any aircraft ASSIGNED to it
|
| 132 |
+
# back to HOLDING so the controller can immediately reassign them to RW01.
|
| 133 |
+
# Without this, they are permanently stranded on the closed runway.
|
| 134 |
+
for aircraft in env._aircraft:
|
| 135 |
+
if (aircraft.assigned_runway == "RW02"
|
| 136 |
+
and aircraft.status == AircraftStatus.ASSIGNED):
|
| 137 |
+
aircraft.status = AircraftStatus.HOLDING
|
| 138 |
+
aircraft.assigned_runway = None
|
| 139 |
+
break
|
| 140 |
+
|
| 141 |
+
if step == 5:
|
| 142 |
+
for aircraft in env._aircraft:
|
| 143 |
+
if aircraft.id == "AC10":
|
| 144 |
+
aircraft.priority = Priority.EMERGENCY
|
| 145 |
+
break
|
atc-openenv/uv.lock
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version = 1
|
| 2 |
+
requires-python = ">=3.8"
|
| 3 |
+
|
| 4 |
+
[dependency-groups]
|
| 5 |
+
dev = []
|
atc-openenv/visualizer.py
ADDED
|
@@ -0,0 +1,430 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Professional ATC Visualization
|
| 3 |
+
Real Physics, Dynamic Radar, Conflict Lines, ICAO Logs
|
| 4 |
+
Run: python visualizer.py [task_level]
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import sys
|
| 8 |
+
import math
|
| 9 |
+
import argparse
|
| 10 |
+
|
| 11 |
+
import matplotlib
|
| 12 |
+
matplotlib.use("TkAgg") # Use TkAgg; falls back automatically on other platforms
|
| 13 |
+
import matplotlib.pyplot as plt
|
| 14 |
+
import matplotlib.animation as animation
|
| 15 |
+
from matplotlib.patches import Circle, Rectangle, FancyBboxPatch, Wedge
|
| 16 |
+
from matplotlib.collections import LineCollection
|
| 17 |
+
import matplotlib.gridspec as gridspec
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from runway_algorithm import run_simulation, Status
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# ─────────────────────────────────────────────
|
| 24 |
+
# Colour Palette
|
| 25 |
+
# ─────────────────────────────────────────────
|
| 26 |
+
class C:
|
| 27 |
+
BG = "#050A14"
|
| 28 |
+
PANEL = "#0F1724"
|
| 29 |
+
TEXT = "#E0E6ED"
|
| 30 |
+
MUTED = "#5C6B7F"
|
| 31 |
+
BORDER = "#1E2D40"
|
| 32 |
+
|
| 33 |
+
EMERGENCY = "#FF2A2A"
|
| 34 |
+
CRITICAL = "#FF8C00"
|
| 35 |
+
WARNING = "#FFD700"
|
| 36 |
+
NORMAL = "#00FF9D"
|
| 37 |
+
INFO = "#00BFFF"
|
| 38 |
+
LANDED = "#4CAF50"
|
| 39 |
+
|
| 40 |
+
RADAR_RING = "#0D1F33"
|
| 41 |
+
RUNWAY_OPEN = "#1A2E44"
|
| 42 |
+
RUNWAY_SHUT = "#3B1010"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# ─────────────────────────────────────────────
|
| 46 |
+
# Helpers
|
| 47 |
+
# ─────────────────────────────────────────────
|
| 48 |
+
def ac_color(ac: dict) -> str:
|
| 49 |
+
if ac.get("emergency"): return C.EMERGENCY
|
| 50 |
+
if ac.get("critical"): return C.CRITICAL
|
| 51 |
+
if ac.get("low_fuel"): return C.WARNING
|
| 52 |
+
st = ac.get("status", "")
|
| 53 |
+
if st in ("LANDED", "TAXIING", "EXITED"): return C.LANDED
|
| 54 |
+
return C.NORMAL
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def fmt_time(seconds: float) -> str:
|
| 58 |
+
m, s = divmod(int(seconds), 60)
|
| 59 |
+
return f"T+{m:02d}:{s:02d}"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# ─────────────────────────────────────────────
|
| 63 |
+
# Main Visualizer
|
| 64 |
+
# ─────────────────────────────────────────────
|
| 65 |
+
class ATCVisualizer:
|
| 66 |
+
RADAR_RANGE = 60 # NM radius displayed
|
| 67 |
+
|
| 68 |
+
def __init__(self, task_level: int):
|
| 69 |
+
self.task_level = task_level
|
| 70 |
+
print(f"[ATC] Running Task {task_level} simulation — please wait...")
|
| 71 |
+
result = run_simulation(task_level)
|
| 72 |
+
self.snapshots = result["snapshots"]
|
| 73 |
+
self.weather = result["weather"]
|
| 74 |
+
self.scores = result["scores"]
|
| 75 |
+
self.total_frames = len(self.snapshots)
|
| 76 |
+
self.frame_idx = 0
|
| 77 |
+
self.sweep_angle = 0.0
|
| 78 |
+
|
| 79 |
+
print(f"[ATC] Simulation complete — {self.total_frames} frames captured.")
|
| 80 |
+
print(f"[ATC] Final score: {self.scores['score']:.4f}")
|
| 81 |
+
|
| 82 |
+
# ── Figure Layout ──────────────────────────────────
|
| 83 |
+
self.fig = plt.figure(figsize=(22, 12), facecolor=C.BG)
|
| 84 |
+
self.fig.canvas.manager.set_window_title(f"AI ATC System — Task {task_level}")
|
| 85 |
+
|
| 86 |
+
gs = gridspec.GridSpec(
|
| 87 |
+
5, 12, figure=self.fig,
|
| 88 |
+
height_ratios=[0.7, 3, 3, 2.5, 0.5],
|
| 89 |
+
hspace=0.18, wspace=0.08,
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
self.ax_hdr = self.fig.add_subplot(gs[0, :8])
|
| 93 |
+
self.ax_wth = self.fig.add_subplot(gs[0, 8:])
|
| 94 |
+
self.ax_radar = self.fig.add_subplot(gs[1:3, :6])
|
| 95 |
+
self.ax_rwy = self.fig.add_subplot(gs[1:3, 6:9])
|
| 96 |
+
self.ax_tbl = self.fig.add_subplot(gs[1:3, 9:])
|
| 97 |
+
self.ax_timeline = self.fig.add_subplot(gs[3, :9])
|
| 98 |
+
self.ax_logs = self.fig.add_subplot(gs[3, 9:])
|
| 99 |
+
self.ax_stats = self.fig.add_subplot(gs[4, :])
|
| 100 |
+
self._style_all()
|
| 101 |
+
|
| 102 |
+
def _style_all(self):
|
| 103 |
+
for ax in (self.ax_hdr, self.ax_wth, self.ax_rwy, self.ax_tbl,
|
| 104 |
+
self.ax_logs, self.ax_stats):
|
| 105 |
+
ax.set_facecolor(C.PANEL)
|
| 106 |
+
ax.axis("off")
|
| 107 |
+
self.ax_radar.set_facecolor(C.BG)
|
| 108 |
+
self.ax_radar.axis("off")
|
| 109 |
+
self.ax_timeline.set_facecolor(C.PANEL)
|
| 110 |
+
for sp in self.ax_timeline.spines.values():
|
| 111 |
+
sp.set_edgecolor(C.BORDER)
|
| 112 |
+
|
| 113 |
+
# ── Draw helpers ──────────────────────────────────────
|
| 114 |
+
|
| 115 |
+
def _draw_header(self, snap: dict):
|
| 116 |
+
ax = self.ax_hdr
|
| 117 |
+
ax.clear(); ax.set_facecolor(C.BG); ax.axis("off")
|
| 118 |
+
t = fmt_time(snap["sim_time"])
|
| 119 |
+
pct = (self.frame_idx + 1) / max(1, self.total_frames) * 100
|
| 120 |
+
ax.text(0.02, 0.5, f"AI ATC CONTROL SYSTEM", color=C.INFO,
|
| 121 |
+
fontsize=15, fontweight="bold", va="center", transform=ax.transAxes)
|
| 122 |
+
ax.text(0.5, 0.5, f"TASK {self.task_level} | {t}",
|
| 123 |
+
color=C.TEXT, fontsize=13, ha="center", va="center", transform=ax.transAxes)
|
| 124 |
+
ax.text(0.98, 0.5, f"{pct:.0f}% complete",
|
| 125 |
+
color=C.MUTED, fontsize=10, ha="right", va="center", transform=ax.transAxes)
|
| 126 |
+
# Progress bar
|
| 127 |
+
bar_ax = self.fig.add_axes([0.015, 0.94, 0.65, 0.006])
|
| 128 |
+
bar_ax.set_facecolor(C.BORDER)
|
| 129 |
+
bar_ax.set_xlim(0, 1); bar_ax.set_ylim(0, 1); bar_ax.axis("off")
|
| 130 |
+
bar_ax.barh(0.5, pct / 100, height=1.0, color=C.INFO, align="center")
|
| 131 |
+
|
| 132 |
+
def _draw_weather(self, snap: dict):
|
| 133 |
+
ax = self.ax_wth
|
| 134 |
+
ax.clear(); ax.set_facecolor(C.PANEL); ax.axis("off")
|
| 135 |
+
w = self.weather
|
| 136 |
+
icon = {"CLEAR": "CLEAR SKY", "RAIN": "RAIN", "STORM": "STORM"}.get(w.condition, w.condition)
|
| 137 |
+
col = {"CLEAR": C.NORMAL, "RAIN": C.WARNING, "STORM": C.EMERGENCY}.get(w.condition, C.TEXT)
|
| 138 |
+
ax.text(0.5, 0.80, "WEATHER", color=C.MUTED, ha="center", fontsize=9, transform=ax.transAxes)
|
| 139 |
+
ax.text(0.5, 0.55, icon, color=col, ha="center", fontsize=11, fontweight="bold", transform=ax.transAxes)
|
| 140 |
+
ax.text(0.5, 0.28, f"Wind {w.wind_speed:.0f}kt / {w.wind_dir:.0f}deg", color=C.TEXT, ha="center", fontsize=9, transform=ax.transAxes)
|
| 141 |
+
ax.text(0.5, 0.08, f"Vis {w.visibility:.0f}km", color=C.TEXT, ha="center", fontsize=9, transform=ax.transAxes)
|
| 142 |
+
|
| 143 |
+
def _draw_radar(self, snap: dict):
|
| 144 |
+
ax = self.ax_radar
|
| 145 |
+
ax.clear()
|
| 146 |
+
ax.set_facecolor(C.BG)
|
| 147 |
+
R = self.RADAR_RANGE
|
| 148 |
+
ax.set_xlim(-R, R); ax.set_ylim(-R, R)
|
| 149 |
+
ax.set_aspect("equal"); ax.axis("off")
|
| 150 |
+
|
| 151 |
+
# Grid rings
|
| 152 |
+
for r in (10, 20, 30, 40, 50):
|
| 153 |
+
circle = Circle((0, 0), r, fill=False, edgecolor=C.RADAR_RING, linewidth=0.8, linestyle="--")
|
| 154 |
+
ax.add_patch(circle)
|
| 155 |
+
ax.text(0, r + 1.5, f"{r}nm", color=C.MUTED, ha="center", fontsize=6)
|
| 156 |
+
|
| 157 |
+
# Cardinal lines
|
| 158 |
+
for deg in (0, 90, 180, 270):
|
| 159 |
+
rad = math.radians(deg)
|
| 160 |
+
ax.plot([0, R * math.sin(rad)], [0, R * math.cos(rad)],
|
| 161 |
+
color=C.RADAR_RING, linewidth=0.5, linestyle=":")
|
| 162 |
+
|
| 163 |
+
# Rotating sweep
|
| 164 |
+
self.sweep_angle = (self.sweep_angle + 4.0) % 360
|
| 165 |
+
rad = math.radians(self.sweep_angle)
|
| 166 |
+
sx, sy = (R - 4) * math.sin(rad), (R - 4) * math.cos(rad)
|
| 167 |
+
ax.plot([0, sx], [0, sy], color=C.NORMAL, linewidth=1.2, alpha=0.75)
|
| 168 |
+
|
| 169 |
+
# Airport centre marker
|
| 170 |
+
ax.plot(0, 0, "+", color=C.INFO, markersize=14, markeredgewidth=2)
|
| 171 |
+
ax.text(0, -R + 3, "RADAR DISPLAY", color=C.TEXT, ha="center", fontsize=9, fontweight="bold")
|
| 172 |
+
|
| 173 |
+
# Conflict pairs
|
| 174 |
+
aircraft = snap["aircraft"]
|
| 175 |
+
conflict_segs = []
|
| 176 |
+
active = [a for a in aircraft if a["status"] not in ("EXITED", "CRASHED")]
|
| 177 |
+
for i, a1 in enumerate(active):
|
| 178 |
+
for a2 in active[i + 1:]:
|
| 179 |
+
dist = math.hypot(a1["x"] - a2["x"], a1["y"] - a2["y"])
|
| 180 |
+
if dist < 3.0:
|
| 181 |
+
conflict_segs.append(((a1["x"], a1["y"]), (a2["x"], a2["y"])))
|
| 182 |
+
|
| 183 |
+
if conflict_segs:
|
| 184 |
+
lc = LineCollection(conflict_segs, colors=C.EMERGENCY, linewidths=1.5, linestyles="dotted")
|
| 185 |
+
ax.add_collection(lc)
|
| 186 |
+
ax.text(R - 2, R - 5, "SEPARATION\nLOSS", color=C.EMERGENCY,
|
| 187 |
+
ha="right", fontsize=8, fontweight="bold")
|
| 188 |
+
|
| 189 |
+
# Aircraft blips
|
| 190 |
+
for ac in aircraft:
|
| 191 |
+
st = ac["status"]
|
| 192 |
+
if st == "EXITED":
|
| 193 |
+
continue
|
| 194 |
+
|
| 195 |
+
x, y = ac["x"], ac["y"]
|
| 196 |
+
col = ac_color(ac)
|
| 197 |
+
size = 6 if ac["wake"] == "HEAVY" else (4 if ac["wake"] == "MEDIUM" else 3)
|
| 198 |
+
|
| 199 |
+
# Faded pulse based on sweep proximity
|
| 200 |
+
ac_ang = math.degrees(math.atan2(ac["x"], ac["y"])) % 360
|
| 201 |
+
ang_diff = abs(ac_ang - self.sweep_angle)
|
| 202 |
+
if ang_diff > 180:
|
| 203 |
+
ang_diff = 360 - ang_diff
|
| 204 |
+
alpha = 1.0 if ang_diff < 20 else max(0.2, 1.0 - ang_diff / 100)
|
| 205 |
+
|
| 206 |
+
dot = Circle((x, y), size / 2.0, facecolor=col, edgecolor="white",
|
| 207 |
+
linewidth=0.5, alpha=alpha, zorder=3)
|
| 208 |
+
ax.add_patch(dot)
|
| 209 |
+
|
| 210 |
+
# Data tag
|
| 211 |
+
if alpha > 0.3:
|
| 212 |
+
tag = f"{ac['id']}\n{int(ac['altitude'])}ft {int(ac['speed'])}kt"
|
| 213 |
+
ax.text(x + size / 2 + 0.8, y + size / 2, tag,
|
| 214 |
+
color=col, fontsize=5.5, alpha=alpha, zorder=4)
|
| 215 |
+
# Velocity vector
|
| 216 |
+
hdg = math.radians(ac["heading"])
|
| 217 |
+
vx = x + 6 * math.sin(hdg)
|
| 218 |
+
vy = y + 6 * math.cos(hdg)
|
| 219 |
+
ax.plot([x, vx], [y, vy], color=col, linewidth=0.6, alpha=alpha * 0.6)
|
| 220 |
+
|
| 221 |
+
def _draw_runways(self, snap: dict):
|
| 222 |
+
ax = self.ax_rwy
|
| 223 |
+
ax.clear(); ax.set_facecolor(C.PANEL)
|
| 224 |
+
ax.set_xlim(0, 14); ax.set_ylim(0, 10)
|
| 225 |
+
ax.axis("off")
|
| 226 |
+
ax.text(7, 9.5, "RUNWAY STATUS", color=C.TEXT, ha="center", fontweight="bold", fontsize=11)
|
| 227 |
+
|
| 228 |
+
y_positions = [7.0, 3.5]
|
| 229 |
+
for i, rwy_snap in enumerate(snap["runways"]):
|
| 230 |
+
y = y_positions[i]
|
| 231 |
+
open_ = rwy_snap["is_active"]
|
| 232 |
+
col = C.RUNWAY_OPEN if open_ else C.RUNWAY_SHUT
|
| 233 |
+
edge = "#ffffff" if open_ else C.EMERGENCY
|
| 234 |
+
|
| 235 |
+
# Runway surface
|
| 236 |
+
rect = Rectangle((0.5, y - 0.45), 12, 0.9, facecolor=col, edgecolor=edge, linewidth=2)
|
| 237 |
+
ax.add_patch(rect)
|
| 238 |
+
|
| 239 |
+
# Centre-line dashes
|
| 240 |
+
if open_:
|
| 241 |
+
for xd in np.arange(1.5, 12, 1.5):
|
| 242 |
+
ax.plot([xd, xd + 0.7], [y, y], color=C.TEXT, linewidth=1.5, alpha=0.6)
|
| 243 |
+
|
| 244 |
+
# Threshold lights
|
| 245 |
+
if open_:
|
| 246 |
+
for xl in [0.7, 12.1]:
|
| 247 |
+
ax.plot(xl, y, "o", color=C.WARNING, markersize=6)
|
| 248 |
+
|
| 249 |
+
# Label
|
| 250 |
+
status_lbl = "OPEN" if open_ else "CLOSED"
|
| 251 |
+
lbl_col = C.NORMAL if open_ else C.EMERGENCY
|
| 252 |
+
ax.text(6.5, y + 1.1, f"{rwy_snap['name']} [{status_lbl}]",
|
| 253 |
+
color=lbl_col, ha="center", fontsize=10, fontweight="bold")
|
| 254 |
+
|
| 255 |
+
# Landing aircraft icon
|
| 256 |
+
prog = rwy_snap.get("progress")
|
| 257 |
+
occ = rwy_snap.get("occupant")
|
| 258 |
+
if open_ and occ and prog is not None:
|
| 259 |
+
rx = 0.5 + prog * 12.0
|
| 260 |
+
ax.text(rx, y, u"\u2708", fontsize=18, ha="center", va="center",
|
| 261 |
+
color=C.INFO, zorder=5)
|
| 262 |
+
ax.text(6.5, y - 0.9, f"ON RUNWAY: {occ}",
|
| 263 |
+
color=C.INFO, ha="center", fontsize=8, fontweight="bold")
|
| 264 |
+
elif open_:
|
| 265 |
+
ax.text(6.5, y - 0.9, "CLEAR", color=C.NORMAL, ha="center", fontsize=8)
|
| 266 |
+
|
| 267 |
+
def _draw_table(self, snap: dict):
|
| 268 |
+
ax = self.ax_tbl
|
| 269 |
+
ax.clear(); ax.set_facecolor(C.PANEL)
|
| 270 |
+
ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.axis("off")
|
| 271 |
+
|
| 272 |
+
ax.text(0.5, 0.96, "TRAFFIC LIST", color=C.TEXT, ha="center",
|
| 273 |
+
fontweight="bold", fontsize=10, transform=ax.transAxes)
|
| 274 |
+
|
| 275 |
+
hdrs = ["CALL", "FUEL", "ALT", "SPD", "STATE"]
|
| 276 |
+
xs = [0.10, 0.30, 0.50, 0.70, 0.90]
|
| 277 |
+
for h, x in zip(hdrs, xs):
|
| 278 |
+
ax.text(x, 0.90, h, color=C.MUTED, ha="center", fontsize=8, transform=ax.transAxes)
|
| 279 |
+
ax.axhline(y=0.89, color=C.BORDER, linewidth=0.8)
|
| 280 |
+
|
| 281 |
+
sorted_ac = sorted(snap["aircraft"], key=lambda a: a["priority_score"], reverse=True)
|
| 282 |
+
y = 0.83
|
| 283 |
+
for ac in sorted_ac[:9]:
|
| 284 |
+
if y < 0.05:
|
| 285 |
+
break
|
| 286 |
+
col = ac_color(ac)
|
| 287 |
+
fcol = C.CRITICAL if ac["fuel"] < 15 else (C.WARNING if ac["fuel"] < 25 else C.TEXT)
|
| 288 |
+
st = ac["status"]
|
| 289 |
+
scol = (C.EMERGENCY if st == "CRASHED" else
|
| 290 |
+
C.LANDED if st in ("LANDED", "EXITED") else C.INFO)
|
| 291 |
+
|
| 292 |
+
ax.text(xs[0], y, ac["id"], color=col, ha="center", fontsize=8, fontweight="bold", transform=ax.transAxes)
|
| 293 |
+
ax.text(xs[1], y, f"{ac['fuel']:.0f}m", color=fcol, ha="center", fontsize=8, transform=ax.transAxes)
|
| 294 |
+
ax.text(xs[2], y, f"{int(ac['altitude'])}", color=C.MUTED, ha="center", fontsize=7, transform=ax.transAxes)
|
| 295 |
+
ax.text(xs[3], y, f"{int(ac['speed'])}", color=C.MUTED, ha="center", fontsize=7, transform=ax.transAxes)
|
| 296 |
+
ax.text(xs[4], y, st[:8], color=scol, ha="center", fontsize=7, transform=ax.transAxes)
|
| 297 |
+
y -= 0.088
|
| 298 |
+
|
| 299 |
+
def _draw_timeline(self, snap: dict):
|
| 300 |
+
ax = self.ax_timeline
|
| 301 |
+
ax.clear(); ax.set_facecolor(C.PANEL)
|
| 302 |
+
max_t = max(3600.0, snap["sim_time"] + 600.0)
|
| 303 |
+
ax.set_xlim(0, max_t); ax.set_ylim(-0.5, len(snap["runways"]))
|
| 304 |
+
ax.set_xlabel("Simulation time (s)", color=C.MUTED, fontsize=8)
|
| 305 |
+
ax.tick_params(colors=C.MUTED, labelsize=7)
|
| 306 |
+
for sp in ax.spines.values():
|
| 307 |
+
sp.set_edgecolor(C.BORDER)
|
| 308 |
+
ax.set_facecolor(C.PANEL)
|
| 309 |
+
ax.set_title("RUNWAY OCCUPANCY TIMELINE", color=C.TEXT, fontsize=9, pad=4)
|
| 310 |
+
ax.xaxis.label.set_color(C.MUTED)
|
| 311 |
+
ax.tick_params(axis="both", colors=C.MUTED)
|
| 312 |
+
|
| 313 |
+
# Current time cursor
|
| 314 |
+
ax.axvline(snap["sim_time"], color=C.EMERGENCY, linewidth=1.2, linestyle="--", alpha=0.8)
|
| 315 |
+
|
| 316 |
+
for i, rwy_snap in enumerate(snap["runways"]):
|
| 317 |
+
col = C.INFO if rwy_snap["is_active"] else C.EMERGENCY
|
| 318 |
+
ax.text(-30, i, rwy_snap["name"], color=col, va="center", ha="right", fontsize=7)
|
| 319 |
+
for slot in rwy_snap["slots"]:
|
| 320 |
+
w = slot["end"] - slot["start"]
|
| 321 |
+
ax.barh(i, w, left=slot["start"], height=0.55, color=C.INFO,
|
| 322 |
+
alpha=0.35, edgecolor=C.INFO, linewidth=0.5)
|
| 323 |
+
mid = slot["start"] + w / 2
|
| 324 |
+
ax.text(mid, i, slot["id"][:5], color=C.TEXT, ha="center",
|
| 325 |
+
va="center", fontsize=6, zorder=5)
|
| 326 |
+
|
| 327 |
+
def _draw_logs(self, snap: dict):
|
| 328 |
+
ax = self.ax_logs
|
| 329 |
+
ax.clear(); ax.set_facecolor(C.PANEL)
|
| 330 |
+
ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.axis("off")
|
| 331 |
+
ax.text(0.5, 0.97, "ATC LOG", color=C.TEXT, ha="center",
|
| 332 |
+
fontweight="bold", fontsize=9, transform=ax.transAxes)
|
| 333 |
+
|
| 334 |
+
y = 0.88
|
| 335 |
+
for ev in reversed(snap["events"][-7:]):
|
| 336 |
+
col = C.EMERGENCY if "CONFLICT" in ev or "CRASH" in ev else (
|
| 337 |
+
C.WARNING if "FUEL" in ev else C.MUTED)
|
| 338 |
+
ax.text(0.05, y, ev, color=col, fontsize=7, va="top",
|
| 339 |
+
transform=ax.transAxes, wrap=True)
|
| 340 |
+
y -= 0.125
|
| 341 |
+
if y < 0.0:
|
| 342 |
+
break
|
| 343 |
+
|
| 344 |
+
def _draw_stats(self, snap: dict):
|
| 345 |
+
ax = self.ax_stats
|
| 346 |
+
ax.clear(); ax.set_facecolor(C.BG); ax.axis("off")
|
| 347 |
+
m = snap["metrics"]
|
| 348 |
+
sc = self.scores
|
| 349 |
+
|
| 350 |
+
parts = [
|
| 351 |
+
f"SCORE {sc['score']:.4f}",
|
| 352 |
+
f"REWARD {sc['reward']:.2f}",
|
| 353 |
+
f"CRASHES {m['crashes']}",
|
| 354 |
+
f"DELAY {m['total_delay']:.0f}s",
|
| 355 |
+
f"EFF {m['efficiency']:.0f}%",
|
| 356 |
+
]
|
| 357 |
+
cols = [C.NORMAL, C.INFO, C.EMERGENCY if m["crashes"] > 0 else C.TEXT, C.WARNING, C.LANDED]
|
| 358 |
+
x = 0.05
|
| 359 |
+
for part, col in zip(parts, cols):
|
| 360 |
+
ax.text(x, 0.5, part, color=col, fontsize=10, fontweight="bold",
|
| 361 |
+
va="center", transform=ax.transAxes, family="monospace")
|
| 362 |
+
x += 0.19
|
| 363 |
+
|
| 364 |
+
ax.text(0.99, 0.5, f"TASK {self.task_level} / {self.weather.condition}",
|
| 365 |
+
color=C.MUTED, fontsize=9, ha="right", va="center", transform=ax.transAxes)
|
| 366 |
+
|
| 367 |
+
# ── Animation ─────────────────────────────────────────
|
| 368 |
+
|
| 369 |
+
def update(self, frame: int):
|
| 370 |
+
"""Called each animation frame — advances through pre-computed snapshots."""
|
| 371 |
+
self.frame_idx = min(frame, self.total_frames - 1)
|
| 372 |
+
snap = self.snapshots[self.frame_idx]
|
| 373 |
+
self.sweep_angle = (self.sweep_angle + 3.0) % 360.0
|
| 374 |
+
|
| 375 |
+
self._draw_header(snap)
|
| 376 |
+
self._draw_weather(snap)
|
| 377 |
+
self._draw_radar(snap)
|
| 378 |
+
self._draw_runways(snap)
|
| 379 |
+
self._draw_table(snap)
|
| 380 |
+
self._draw_timeline(snap)
|
| 381 |
+
self._draw_logs(snap)
|
| 382 |
+
self._draw_stats(snap)
|
| 383 |
+
|
| 384 |
+
return []
|
| 385 |
+
|
| 386 |
+
def animate(self, interval_ms: int = 80):
|
| 387 |
+
anim = animation.FuncAnimation(
|
| 388 |
+
self.fig, self.update,
|
| 389 |
+
frames=self.total_frames,
|
| 390 |
+
interval=interval_ms,
|
| 391 |
+
blit=False,
|
| 392 |
+
repeat=True,
|
| 393 |
+
)
|
| 394 |
+
return anim
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
# ─────────────────────────────────────────────
|
| 398 |
+
# Entry Point
|
| 399 |
+
# ─────────────────────────────────────────────
|
| 400 |
+
|
| 401 |
+
def main():
|
| 402 |
+
parser = argparse.ArgumentParser(description="ATC Visualizer")
|
| 403 |
+
parser.add_argument("task", nargs="?", type=int, default=None,
|
| 404 |
+
help="Task level 1-3 (prompt if omitted)")
|
| 405 |
+
args = parser.parse_args()
|
| 406 |
+
|
| 407 |
+
if args.task in (1, 2, 3):
|
| 408 |
+
task = args.task
|
| 409 |
+
else:
|
| 410 |
+
print("Select task level:")
|
| 411 |
+
print(" 1 — Clear Skies (5 aircraft, good conditions)")
|
| 412 |
+
print(" 2 — Fuel Pressure (10 aircraft, rain, fuel-critical aircraft)")
|
| 413 |
+
print(" 3 — Full Emergency (15 aircraft, storm, runway closure, emergency)")
|
| 414 |
+
try:
|
| 415 |
+
task = int(input("Task [1-3]: ").strip() or "1")
|
| 416 |
+
except (ValueError, EOFError):
|
| 417 |
+
task = 1
|
| 418 |
+
task = max(1, min(3, task))
|
| 419 |
+
|
| 420 |
+
viz = ATCVisualizer(task)
|
| 421 |
+
anim = viz.animate()
|
| 422 |
+
# plt.tight_layout(pad=0.5) # Can cause warnings with custom gridspecs
|
| 423 |
+
plt.show()
|
| 424 |
+
|
| 425 |
+
print(f"\nFinal Score: {viz.scores['score']:.4f}")
|
| 426 |
+
print(f"Reward: {viz.scores['reward']:.2f}")
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
if __name__ == "__main__":
|
| 430 |
+
main()
|