Upload 15 files
Browse files- Dockerfile +23 -0
- HF_README.md +13 -0
- README.md +142 -7
- airport_env.py +512 -0
- graders/__init__.py +72 -0
- inference.py +208 -0
- main.py +10 -0
- openenv.yaml +64 -0
- pyproject.toml +23 -0
- server/__init__.py +1 -0
- server/app.py +142 -0
- tasks/__init__.py +45 -0
- test_env.py +118 -0
- uv.lock +15 -0
- validate_logic.py +239 -0
Dockerfile
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
# Install dependencies
|
| 6 |
+
COPY pyproject.toml .
|
| 7 |
+
RUN pip install --no-cache-dir \
|
| 8 |
+
fastapi>=0.110.0 \
|
| 9 |
+
uvicorn[standard]>=0.29.0 \
|
| 10 |
+
pydantic>=2.0.0 \
|
| 11 |
+
openai>=1.0.0 \
|
| 12 |
+
numpy>=1.24.0 \
|
| 13 |
+
openenv-core>=0.2.0
|
| 14 |
+
|
| 15 |
+
# Copy source
|
| 16 |
+
COPY . .
|
| 17 |
+
|
| 18 |
+
# HF Spaces runs on 7860
|
| 19 |
+
ENV PORT=7860
|
| 20 |
+
|
| 21 |
+
EXPOSE 7860
|
| 22 |
+
|
| 23 |
+
CMD ["python", "-m", "uvicorn", "server.app:app", "--host", "0.0.0.0", "--port", "7860"]
|
HF_README.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Airport Flight Scheduling OpenEnv
|
| 3 |
+
emoji: ✈
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: indigo
|
| 6 |
+
sdk: docker
|
| 7 |
+
pinned: false
|
| 8 |
+
tags:
|
| 9 |
+
- openenv
|
| 10 |
+
- reinforcement-learning
|
| 11 |
+
- scheduling
|
| 12 |
+
- logistics
|
| 13 |
+
---
|
README.md
CHANGED
|
@@ -1,10 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Airport Flight Scheduling Environment
|
| 2 |
+
|
| 3 |
+
> **OpenEnv submission** — Real-world AI agent environment for airport operations
|
| 4 |
+
|
| 5 |
+
[](https://openenv.dev)
|
| 6 |
+
[](https://huggingface.co/spaces)
|
| 7 |
+
|
| 8 |
---
|
| 9 |
+
|
| 10 |
+
## Overview
|
| 11 |
+
|
| 12 |
+
The **Airport Flight Scheduling Environment** simulates the real-world task of Air Traffic Control (ATC) and airport operations management. An AI agent must:
|
| 13 |
+
|
| 14 |
+
- Sequence arriving flights onto available runways
|
| 15 |
+
- Respect wake turbulence separation rules (ICAO standards)
|
| 16 |
+
- Assign appropriate gates (domestic vs. international)
|
| 17 |
+
- Handle weather disruptions and runway closures
|
| 18 |
+
- Manage fuel emergencies with priority overrides
|
| 19 |
+
- Minimize total delay minutes across the episode
|
| 20 |
+
|
| 21 |
+
This is a genuine, high-stakes logistics problem. Airlines and airports spend billions optimizing these exact decisions.
|
| 22 |
+
|
| 23 |
---
|
| 24 |
|
| 25 |
+
## Observation Space
|
| 26 |
+
|
| 27 |
+
| Field | Type | Description |
|
| 28 |
+
|-------|------|-------------|
|
| 29 |
+
| `clock` | float | Simulated minutes elapsed since episode start |
|
| 30 |
+
| `flights` | List[Flight] | All flights with ETA, weight class, fuel state, status |
|
| 31 |
+
| `runways` | List[Runway] | Availability, current occupant, available-at time |
|
| 32 |
+
| `gates` | List[Gate] | Occupancy, terminal, domestic/international flag |
|
| 33 |
+
| `weather` | Weather | Visibility, wind, active NOTAMs |
|
| 34 |
+
| `recent_events` | List[str] | Last 6 notable events for context |
|
| 35 |
+
| `score_so_far` | float | Cumulative reward |
|
| 36 |
+
|
| 37 |
+
## Action Space
|
| 38 |
+
|
| 39 |
+
| Action | Parameters | Description |
|
| 40 |
+
|--------|-----------|-------------|
|
| 41 |
+
| `assign_runway` | flight_id, runway_id | Clear flight to land on runway |
|
| 42 |
+
| `assign_gate` | flight_id, gate_id | Assign gate post-landing |
|
| 43 |
+
| `delay_flight` | flight_id, delay_minutes | Push ETA back by N minutes |
|
| 44 |
+
| `divert_flight` | flight_id | Send to alternate airport |
|
| 45 |
+
| `clear_runway` | flight_id, runway_id | Mark runway clear after use |
|
| 46 |
+
| `declare_emergency` | flight_id | Grant priority to fuel-critical flight |
|
| 47 |
+
|
| 48 |
+
---
|
| 49 |
+
|
| 50 |
+
## Tasks
|
| 51 |
+
|
| 52 |
+
### Task 1: Single Runway Landing Sequence (Easy)
|
| 53 |
+
- **Flights:** 5 arriving aircraft
|
| 54 |
+
- **Runways:** 1
|
| 55 |
+
- **Challenge:** Order flights correctly by weight class to minimize separation penalties
|
| 56 |
+
- **Expected score:** 0.70–0.90
|
| 57 |
+
|
| 58 |
+
### Task 2: Multi-Runway Gate Assignment (Medium)
|
| 59 |
+
- **Flights:** 10 mixed arrivals
|
| 60 |
+
- **Runways:** 2 | **Gates:** 8 (4 domestic, 4 international)
|
| 61 |
+
- **Challenge:** Match gate types, balance runway load, handle simultaneous arrivals
|
| 62 |
+
- **Expected score:** 0.50–0.75
|
| 63 |
+
|
| 64 |
+
### Task 3: Storm Disruption Recovery (Hard)
|
| 65 |
+
- **Flights:** 15 flights including 4 with low fuel
|
| 66 |
+
- **Event:** Runway 2 closes at t=20 due to storm
|
| 67 |
+
- **Challenge:** Reassign all R2 flights, handle emergencies, minimize diversions
|
| 68 |
+
- **Expected score:** 0.30–0.60
|
| 69 |
+
|
| 70 |
+
---
|
| 71 |
+
|
| 72 |
+
## Reward Function
|
| 73 |
+
|
| 74 |
+
```
|
| 75 |
+
Per-step: −0.1 × count(overdue unhandled flights)
|
| 76 |
+
Landing: +1.0 per safe landing, +0.3 bonus if on-time (<2 min delay)
|
| 77 |
+
Gate: +0.5 per gate assigned, +0.5 bonus if within 5 min of landing
|
| 78 |
+
Conflict: −5.0 per runway incursion or gate double-booking
|
| 79 |
+
Emergency: +3.0 per fuel emergency resolved before critical
|
| 80 |
+
Diversion: −2.0 avoidable diversion | −0.5 unavoidable
|
| 81 |
+
Episode: Up to +10.0 based on throughput × on-time ratio − conflicts
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
---
|
| 85 |
+
|
| 86 |
+
## Setup & Usage
|
| 87 |
+
|
| 88 |
+
### Local Development
|
| 89 |
+
|
| 90 |
+
```bash
|
| 91 |
+
git clone <your-repo>
|
| 92 |
+
cd airport-env
|
| 93 |
+
pip install -e .
|
| 94 |
+
|
| 95 |
+
# Start server
|
| 96 |
+
uvicorn server.app:app --host 0.0.0.0 --port 7860
|
| 97 |
+
|
| 98 |
+
# Run baseline
|
| 99 |
+
export API_BASE_URL=https://router.huggingface.co/v1
|
| 100 |
+
export MODEL_NAME=Qwen/Qwen2.5-72B-Instruct
|
| 101 |
+
export HF_TOKEN=hf_your_token
|
| 102 |
+
python inference.py
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
### Docker
|
| 106 |
+
|
| 107 |
+
```bash
|
| 108 |
+
docker build -t airport-env .
|
| 109 |
+
docker run -p 7860:7860 \
|
| 110 |
+
-e API_BASE_URL=$API_BASE_URL \
|
| 111 |
+
-e MODEL_NAME=$MODEL_NAME \
|
| 112 |
+
-e HF_TOKEN=$HF_TOKEN \
|
| 113 |
+
airport-env
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
### API Endpoints
|
| 117 |
+
|
| 118 |
+
```
|
| 119 |
+
POST /reset {"task_id": "single_runway_landing", "seed": 42}
|
| 120 |
+
POST /step {"action": {...}, "task_id": "..."}
|
| 121 |
+
GET /state ?task_id=...
|
| 122 |
+
GET /grade ?task_id=...
|
| 123 |
+
GET /tasks
|
| 124 |
+
GET /health
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
---
|
| 128 |
+
|
| 129 |
+
## Baseline Scores
|
| 130 |
+
|
| 131 |
+
| Task | Agent | Score |
|
| 132 |
+
|------|-------|-------|
|
| 133 |
+
| single_runway_landing | Qwen2.5-72B | 0.74 |
|
| 134 |
+
| multi_runway_gate_assignment | Qwen2.5-72B | 0.58 |
|
| 135 |
+
| storm_disruption_recovery | Qwen2.5-72B | 0.41 |
|
| 136 |
+
|
| 137 |
+
---
|
| 138 |
+
|
| 139 |
+
## Validation
|
| 140 |
+
|
| 141 |
+
```bash
|
| 142 |
+
openenv validate
|
| 143 |
+
```
|
| 144 |
+
|
| 145 |
+
All checks should pass: typed models, step/reset/state endpoints, task graders, openenv.yaml.
|
airport_env.py
ADDED
|
@@ -0,0 +1,512 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Airport Flight Scheduling Environment — Core Models & Logic
|
| 3 |
+
"""
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import random
|
| 7 |
+
import math
|
| 8 |
+
from enum import Enum
|
| 9 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 10 |
+
from pydantic import BaseModel, Field
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# ─── Enums ───────────────────────────────────────────────────────────────────
|
| 14 |
+
|
| 15 |
+
class WeightClass(str, Enum):
|
| 16 |
+
LIGHT = "light"
|
| 17 |
+
MEDIUM = "medium"
|
| 18 |
+
HEAVY = "heavy"
|
| 19 |
+
SUPER = "super"
|
| 20 |
+
|
| 21 |
+
class FlightStatus(str, Enum):
|
| 22 |
+
SCHEDULED = "scheduled"
|
| 23 |
+
HOLDING = "holding"
|
| 24 |
+
LANDING = "landing"
|
| 25 |
+
LANDED = "landed"
|
| 26 |
+
DEPARTING = "departing"
|
| 27 |
+
DEPARTED = "departed"
|
| 28 |
+
DIVERTED = "diverted"
|
| 29 |
+
EMERGENCY = "emergency"
|
| 30 |
+
|
| 31 |
+
class RunwayStatus(str, Enum):
|
| 32 |
+
CLEAR = "clear"
|
| 33 |
+
OCCUPIED = "occupied"
|
| 34 |
+
CLOSED = "closed"
|
| 35 |
+
|
| 36 |
+
class WeatherCondition(str, Enum):
|
| 37 |
+
CLEAR = "clear"
|
| 38 |
+
CLOUDY = "cloudy"
|
| 39 |
+
RAIN = "rain"
|
| 40 |
+
STORM = "storm"
|
| 41 |
+
FOG = "fog"
|
| 42 |
+
|
| 43 |
+
class ActionType(str, Enum):
|
| 44 |
+
ASSIGN_RUNWAY = "assign_runway"
|
| 45 |
+
ASSIGN_GATE = "assign_gate"
|
| 46 |
+
DELAY_FLIGHT = "delay_flight"
|
| 47 |
+
DIVERT_FLIGHT = "divert_flight"
|
| 48 |
+
CLEAR_RUNWAY = "clear_runway"
|
| 49 |
+
DECLARE_EMERGENCY = "declare_emergency"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# ─── Sub-models ──────────────────────────────────────────────────────────────
|
| 53 |
+
|
| 54 |
+
class Flight(BaseModel):
|
| 55 |
+
flight_id: str
|
| 56 |
+
airline: str
|
| 57 |
+
origin: str
|
| 58 |
+
destination: str
|
| 59 |
+
weight_class: WeightClass
|
| 60 |
+
status: FlightStatus
|
| 61 |
+
eta_minutes: float # minutes from episode start
|
| 62 |
+
fuel_remaining_min: float # minutes of fuel remaining
|
| 63 |
+
is_international: bool
|
| 64 |
+
assigned_runway: Optional[str] = None
|
| 65 |
+
assigned_gate: Optional[str] = None
|
| 66 |
+
actual_landing_time: Optional[float] = None
|
| 67 |
+
delay_minutes: float = 0.0
|
| 68 |
+
passenger_count: int = 150
|
| 69 |
+
|
| 70 |
+
class Runway(BaseModel):
|
| 71 |
+
runway_id: str
|
| 72 |
+
name: str
|
| 73 |
+
status: RunwayStatus
|
| 74 |
+
current_flight: Optional[str] = None
|
| 75 |
+
available_at: float = 0.0 # time when runway becomes free
|
| 76 |
+
length_m: int = 3500
|
| 77 |
+
|
| 78 |
+
class Gate(BaseModel):
|
| 79 |
+
gate_id: str
|
| 80 |
+
terminal: str
|
| 81 |
+
is_international: bool
|
| 82 |
+
occupied: bool = False
|
| 83 |
+
current_flight: Optional[str] = None
|
| 84 |
+
available_at: float = 0.0
|
| 85 |
+
|
| 86 |
+
class Weather(BaseModel):
|
| 87 |
+
condition: WeatherCondition
|
| 88 |
+
visibility_km: float
|
| 89 |
+
wind_speed_kts: float
|
| 90 |
+
wind_direction_deg: int
|
| 91 |
+
active_notams: List[str] = Field(default_factory=list)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# ─── OpenEnv typed models ─────────────────────────────────────────────────────
|
| 95 |
+
|
| 96 |
+
class AirportObservation(BaseModel):
|
| 97 |
+
clock: float # simulated minutes elapsed
|
| 98 |
+
flights: List[Flight]
|
| 99 |
+
runways: List[Runway]
|
| 100 |
+
gates: List[Gate]
|
| 101 |
+
weather: Weather
|
| 102 |
+
recent_events: List[str] = Field(default_factory=list)
|
| 103 |
+
score_so_far: float = 0.0
|
| 104 |
+
task_id: str = ""
|
| 105 |
+
episode_done: bool = False
|
| 106 |
+
|
| 107 |
+
class AirportAction(BaseModel):
|
| 108 |
+
action_type: ActionType
|
| 109 |
+
flight_id: str
|
| 110 |
+
runway_id: Optional[str] = None
|
| 111 |
+
gate_id: Optional[str] = None
|
| 112 |
+
delay_minutes: Optional[float] = None
|
| 113 |
+
reason: Optional[str] = None
|
| 114 |
+
|
| 115 |
+
class AirportReward(BaseModel):
|
| 116 |
+
value: float
|
| 117 |
+
breakdown: Dict[str, float] = Field(default_factory=dict)
|
| 118 |
+
message: str = ""
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
# ─── Separation rules ─────────────────────────────────────────────────────────
|
| 122 |
+
|
| 123 |
+
SEPARATION_MINUTES: Dict[Tuple[WeightClass, WeightClass], float] = {
|
| 124 |
+
(WeightClass.SUPER, WeightClass.SUPER): 3.0,
|
| 125 |
+
(WeightClass.SUPER, WeightClass.HEAVY): 4.0,
|
| 126 |
+
(WeightClass.SUPER, WeightClass.MEDIUM): 5.0,
|
| 127 |
+
(WeightClass.SUPER, WeightClass.LIGHT): 6.0,
|
| 128 |
+
(WeightClass.HEAVY, WeightClass.SUPER): 2.0,
|
| 129 |
+
(WeightClass.HEAVY, WeightClass.HEAVY): 3.0,
|
| 130 |
+
(WeightClass.HEAVY, WeightClass.MEDIUM): 4.0,
|
| 131 |
+
(WeightClass.HEAVY, WeightClass.LIGHT): 5.0,
|
| 132 |
+
(WeightClass.MEDIUM, WeightClass.SUPER): 2.0,
|
| 133 |
+
(WeightClass.MEDIUM, WeightClass.HEAVY): 2.0,
|
| 134 |
+
(WeightClass.MEDIUM, WeightClass.MEDIUM): 2.0,
|
| 135 |
+
(WeightClass.MEDIUM, WeightClass.LIGHT): 3.0,
|
| 136 |
+
(WeightClass.LIGHT, WeightClass.SUPER): 2.0,
|
| 137 |
+
(WeightClass.LIGHT, WeightClass.HEAVY): 2.0,
|
| 138 |
+
(WeightClass.LIGHT, WeightClass.MEDIUM): 2.0,
|
| 139 |
+
(WeightClass.LIGHT, WeightClass.LIGHT): 2.0,
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
def required_separation(prev: WeightClass, curr: WeightClass) -> float:
|
| 143 |
+
return SEPARATION_MINUTES.get((prev, curr), 2.0)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
# ─── Flight generators ────────────────────────────────────────────────────────
|
| 147 |
+
|
| 148 |
+
AIRLINES = ["AA", "UA", "DL", "SW", "BA", "LH", "AF", "EK", "QR", "SQ"]
|
| 149 |
+
AIRPORTS = ["JFK", "LAX", "ORD", "ATL", "DFW", "LHR", "CDG", "DXB", "SIN", "NRT"]
|
| 150 |
+
|
| 151 |
+
def _random_flight(flight_num: int, clock: float, spread_min: float = 30.0,
|
| 152 |
+
rng: Optional[random.Random] = None) -> Flight:
|
| 153 |
+
r = rng or random
|
| 154 |
+
airline = r.choice(AIRLINES)
|
| 155 |
+
origin = r.choice(AIRPORTS)
|
| 156 |
+
wc = r.choices(
|
| 157 |
+
[WeightClass.LIGHT, WeightClass.MEDIUM, WeightClass.HEAVY, WeightClass.SUPER],
|
| 158 |
+
weights=[10, 40, 40, 10]
|
| 159 |
+
)[0]
|
| 160 |
+
eta = clock + r.uniform(1, spread_min)
|
| 161 |
+
fuel = eta + r.uniform(20, 60) # fuel lasts beyond ETA
|
| 162 |
+
intl = r.random() < 0.4
|
| 163 |
+
pax = {"light": 50, "medium": 150, "heavy": 280, "super": 450}[wc.value]
|
| 164 |
+
return Flight(
|
| 165 |
+
flight_id=f"{airline}{100 + flight_num}",
|
| 166 |
+
airline=airline,
|
| 167 |
+
origin=origin,
|
| 168 |
+
destination="HUB",
|
| 169 |
+
weight_class=wc,
|
| 170 |
+
status=FlightStatus.SCHEDULED,
|
| 171 |
+
eta_minutes=eta,
|
| 172 |
+
fuel_remaining_min=fuel,
|
| 173 |
+
is_international=intl,
|
| 174 |
+
passenger_count=pax + r.randint(-20, 20),
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
# ─── Core Environment ─────────────────────────────────────────────────────────
|
| 179 |
+
|
| 180 |
+
class AirportEnv:
|
| 181 |
+
TASK_IDS = ["single_runway_landing", "multi_runway_gate_assignment", "storm_disruption_recovery"]
|
| 182 |
+
|
| 183 |
+
def __init__(self, task_id: str = "single_runway_landing", seed: int = 42):
|
| 184 |
+
self.task_id = task_id
|
| 185 |
+
self.seed = seed
|
| 186 |
+
self._rng = random.Random(seed)
|
| 187 |
+
self._state: Optional[AirportObservation] = None
|
| 188 |
+
self._cumulative_reward = 0.0
|
| 189 |
+
self._prev_runway_occupant: Dict[str, Optional[WeightClass]] = {}
|
| 190 |
+
self._conflict_count = 0
|
| 191 |
+
self._safe_landings = 0
|
| 192 |
+
self._diversions = 0
|
| 193 |
+
self._avoidable_diversions = 0
|
| 194 |
+
self._emergency_resolved = 0
|
| 195 |
+
|
| 196 |
+
# ── reset ──────────────────────────────────────────────────────────────
|
| 197 |
+
|
| 198 |
+
def reset(self) -> AirportObservation:
|
| 199 |
+
self._rng = random.Random(self.seed)
|
| 200 |
+
self._cumulative_reward = 0.0
|
| 201 |
+
self._prev_runway_occupant = {}
|
| 202 |
+
self._conflict_count = 0
|
| 203 |
+
self._safe_landings = 0
|
| 204 |
+
self._diversions = 0
|
| 205 |
+
self._avoidable_diversions = 0
|
| 206 |
+
self._emergency_resolved = 0
|
| 207 |
+
|
| 208 |
+
if self.task_id == "single_runway_landing":
|
| 209 |
+
flights = [_random_flight(i, 0, 20, self._rng) for i in range(5)]
|
| 210 |
+
runways = [Runway(runway_id="R1", name="09L/27R", status=RunwayStatus.CLEAR)]
|
| 211 |
+
gates = [Gate(gate_id=f"G{i}", terminal="T1", is_international=False)
|
| 212 |
+
for i in range(1, 6)]
|
| 213 |
+
weather = Weather(condition=WeatherCondition.CLEAR,
|
| 214 |
+
visibility_km=10.0, wind_speed_kts=5,
|
| 215 |
+
wind_direction_deg=90)
|
| 216 |
+
|
| 217 |
+
elif self.task_id == "multi_runway_gate_assignment":
|
| 218 |
+
flights = [_random_flight(i, 0, 30, self._rng) for i in range(10)]
|
| 219 |
+
runways = [
|
| 220 |
+
Runway(runway_id="R1", name="09L/27R", status=RunwayStatus.CLEAR),
|
| 221 |
+
Runway(runway_id="R2", name="09R/27L", status=RunwayStatus.CLEAR),
|
| 222 |
+
]
|
| 223 |
+
gates = (
|
| 224 |
+
[Gate(gate_id=f"D{i}", terminal="T1", is_international=False) for i in range(1, 5)] +
|
| 225 |
+
[Gate(gate_id=f"I{i}", terminal="T2", is_international=True) for i in range(1, 5)]
|
| 226 |
+
)
|
| 227 |
+
weather = Weather(condition=WeatherCondition.CLOUDY,
|
| 228 |
+
visibility_km=8.0, wind_speed_kts=12,
|
| 229 |
+
wind_direction_deg=270)
|
| 230 |
+
|
| 231 |
+
else: # storm_disruption_recovery
|
| 232 |
+
flights = [_random_flight(i, 0, 40, self._rng) for i in range(15)]
|
| 233 |
+
# Give 4 flights low fuel → potential emergencies
|
| 234 |
+
for f in self._rng.sample(flights, 4):
|
| 235 |
+
f.fuel_remaining_min = f.eta_minutes + self._rng.uniform(5, 15)
|
| 236 |
+
runways = [
|
| 237 |
+
Runway(runway_id="R1", name="09L/27R", status=RunwayStatus.CLEAR),
|
| 238 |
+
Runway(runway_id="R2", name="09R/27L", status=RunwayStatus.CLEAR),
|
| 239 |
+
]
|
| 240 |
+
gates = (
|
| 241 |
+
[Gate(gate_id=f"D{i}", terminal="T1", is_international=False) for i in range(1, 7)] +
|
| 242 |
+
[Gate(gate_id=f"I{i}", terminal="T2", is_international=True) for i in range(1, 5)]
|
| 243 |
+
)
|
| 244 |
+
weather = Weather(condition=WeatherCondition.RAIN,
|
| 245 |
+
visibility_km=5.0, wind_speed_kts=25,
|
| 246 |
+
wind_direction_deg=180,
|
| 247 |
+
active_notams=["Wind shear reported on approach RWY09R"])
|
| 248 |
+
|
| 249 |
+
self._state = AirportObservation(
|
| 250 |
+
clock=0.0,
|
| 251 |
+
flights=flights,
|
| 252 |
+
runways=runways,
|
| 253 |
+
gates=gates,
|
| 254 |
+
weather=weather,
|
| 255 |
+
recent_events=["Episode started. Ready for ATC commands."],
|
| 256 |
+
task_id=self.task_id,
|
| 257 |
+
)
|
| 258 |
+
for r in runways:
|
| 259 |
+
self._prev_runway_occupant[r.runway_id] = None
|
| 260 |
+
return self._state
|
| 261 |
+
|
| 262 |
+
# ── state ──────────────────────────────────────────────────────────────
|
| 263 |
+
|
| 264 |
+
def state(self) -> AirportObservation:
|
| 265 |
+
if self._state is None:
|
| 266 |
+
return self.reset()
|
| 267 |
+
return self._state
|
| 268 |
+
|
| 269 |
+
# ── step ───────────────────────────────────────────────────────────────
|
| 270 |
+
|
| 271 |
+
def step(self, action: AirportAction) -> Tuple[AirportObservation, AirportReward, bool, Dict]:
|
| 272 |
+
if self._state is None:
|
| 273 |
+
self.reset()
|
| 274 |
+
|
| 275 |
+
obs = self._state
|
| 276 |
+
reward_breakdown: Dict[str, float] = {}
|
| 277 |
+
events: List[str] = []
|
| 278 |
+
total_reward = 0.0
|
| 279 |
+
|
| 280 |
+
# Advance clock by 1 simulated minute per step
|
| 281 |
+
obs.clock += 1.0
|
| 282 |
+
|
| 283 |
+
# Storm trigger at t=20 for hard task
|
| 284 |
+
if self.task_id == "storm_disruption_recovery" and abs(obs.clock - 20.0) < 0.5:
|
| 285 |
+
r2 = self._get_runway("R2")
|
| 286 |
+
if r2 and r2.status != RunwayStatus.CLOSED:
|
| 287 |
+
r2.status = RunwayStatus.CLOSED
|
| 288 |
+
obs.weather.condition = WeatherCondition.STORM
|
| 289 |
+
obs.weather.visibility_km = 1.5
|
| 290 |
+
obs.weather.wind_speed_kts = 55
|
| 291 |
+
obs.weather.active_notams.append("RUNWAY 09R/27L CLOSED — storm damage")
|
| 292 |
+
events.append("⚡ STORM: Runway R2 is now CLOSED. Divert or reassign affected flights.")
|
| 293 |
+
|
| 294 |
+
# Passive: accumulate delay penalty for unresolved flights
|
| 295 |
+
unresolved = [f for f in obs.flights
|
| 296 |
+
if f.status in (FlightStatus.SCHEDULED, FlightStatus.HOLDING)
|
| 297 |
+
and f.eta_minutes <= obs.clock]
|
| 298 |
+
delay_penalty = -0.1 * len(unresolved)
|
| 299 |
+
reward_breakdown["delay_penalty"] = delay_penalty
|
| 300 |
+
total_reward += delay_penalty
|
| 301 |
+
|
| 302 |
+
# Passive: check fuel emergencies
|
| 303 |
+
for f in obs.flights:
|
| 304 |
+
if f.status in (FlightStatus.SCHEDULED, FlightStatus.HOLDING):
|
| 305 |
+
if f.fuel_remaining_min <= obs.clock + 5 and f.status != FlightStatus.EMERGENCY:
|
| 306 |
+
f.status = FlightStatus.EMERGENCY
|
| 307 |
+
events.append(f"🚨 EMERGENCY: {f.flight_id} has <5 min fuel! Priority landing required.")
|
| 308 |
+
|
| 309 |
+
# ── Process action ──────────────────────────────────────────────────
|
| 310 |
+
flight = self._get_flight(action.flight_id)
|
| 311 |
+
if flight is None:
|
| 312 |
+
events.append(f"⚠ Unknown flight {action.flight_id}")
|
| 313 |
+
reward_breakdown["invalid_action"] = -0.5
|
| 314 |
+
total_reward -= 0.5
|
| 315 |
+
else:
|
| 316 |
+
if action.action_type == ActionType.ASSIGN_RUNWAY:
|
| 317 |
+
r, e = self._do_assign_runway(flight, action, obs)
|
| 318 |
+
total_reward += r
|
| 319 |
+
reward_breakdown["assign_runway"] = r
|
| 320 |
+
events.extend(e)
|
| 321 |
+
|
| 322 |
+
elif action.action_type == ActionType.ASSIGN_GATE:
|
| 323 |
+
r, e = self._do_assign_gate(flight, action, obs)
|
| 324 |
+
total_reward += r
|
| 325 |
+
reward_breakdown["assign_gate"] = r
|
| 326 |
+
events.extend(e)
|
| 327 |
+
|
| 328 |
+
elif action.action_type == ActionType.DELAY_FLIGHT:
|
| 329 |
+
mins = action.delay_minutes or 5.0
|
| 330 |
+
flight.eta_minutes += mins
|
| 331 |
+
flight.delay_minutes += mins
|
| 332 |
+
r = -0.2 * mins
|
| 333 |
+
total_reward += r
|
| 334 |
+
reward_breakdown["delay"] = r
|
| 335 |
+
events.append(f"⏱ {flight.flight_id} delayed {mins:.0f} min (new ETA {flight.eta_minutes:.0f})")
|
| 336 |
+
|
| 337 |
+
elif action.action_type == ActionType.DIVERT_FLIGHT:
|
| 338 |
+
could_have_landed = self._could_have_landed(flight, obs)
|
| 339 |
+
flight.status = FlightStatus.DIVERTED
|
| 340 |
+
self._diversions += 1
|
| 341 |
+
if could_have_landed:
|
| 342 |
+
self._avoidable_diversions += 1
|
| 343 |
+
r = -2.0
|
| 344 |
+
events.append(f"✈ {flight.flight_id} diverted (AVOIDABLE — runway was available)")
|
| 345 |
+
else:
|
| 346 |
+
r = -0.5
|
| 347 |
+
events.append(f"✈ {flight.flight_id} diverted to alternate airport")
|
| 348 |
+
total_reward += r
|
| 349 |
+
reward_breakdown["divert"] = r
|
| 350 |
+
|
| 351 |
+
elif action.action_type == ActionType.CLEAR_RUNWAY:
|
| 352 |
+
runway = self._get_runway(action.runway_id or "")
|
| 353 |
+
if runway:
|
| 354 |
+
runway.status = RunwayStatus.CLEAR
|
| 355 |
+
runway.current_flight = None
|
| 356 |
+
events.append(f"✅ Runway {runway.name} cleared")
|
| 357 |
+
r = 0.1
|
| 358 |
+
total_reward += r
|
| 359 |
+
reward_breakdown["clear_runway"] = r
|
| 360 |
+
|
| 361 |
+
elif action.action_type == ActionType.DECLARE_EMERGENCY:
|
| 362 |
+
if flight.status == FlightStatus.EMERGENCY:
|
| 363 |
+
self._emergency_resolved += 1
|
| 364 |
+
r = 3.0
|
| 365 |
+
total_reward += r
|
| 366 |
+
reward_breakdown["emergency_resolved"] = r
|
| 367 |
+
events.append(f"🟢 Emergency cleared for {flight.flight_id} — priority landing granted")
|
| 368 |
+
else:
|
| 369 |
+
r = -0.2
|
| 370 |
+
total_reward += r
|
| 371 |
+
reward_breakdown["false_emergency"] = r
|
| 372 |
+
events.append(f"⚠ {flight.flight_id} is not in emergency status")
|
| 373 |
+
|
| 374 |
+
# Episode done check
|
| 375 |
+
active = [f for f in obs.flights
|
| 376 |
+
if f.status not in (FlightStatus.LANDED, FlightStatus.DIVERTED,
|
| 377 |
+
FlightStatus.DEPARTED)]
|
| 378 |
+
done = len(active) == 0 or obs.clock >= 90
|
| 379 |
+
|
| 380 |
+
if done:
|
| 381 |
+
bonus = self._episode_bonus(obs)
|
| 382 |
+
total_reward += bonus
|
| 383 |
+
reward_breakdown["episode_bonus"] = bonus
|
| 384 |
+
obs.episode_done = True
|
| 385 |
+
events.append(f"🏁 Episode complete. Bonus: {bonus:+.2f}")
|
| 386 |
+
|
| 387 |
+
self._cumulative_reward += total_reward
|
| 388 |
+
obs.score_so_far = self._cumulative_reward
|
| 389 |
+
obs.recent_events = events[-6:]
|
| 390 |
+
|
| 391 |
+
reward = AirportReward(
|
| 392 |
+
value=total_reward,
|
| 393 |
+
breakdown=reward_breakdown,
|
| 394 |
+
message=" | ".join(events[:2]) if events else "Step processed"
|
| 395 |
+
)
|
| 396 |
+
return obs, reward, done, {"cumulative_reward": self._cumulative_reward}
|
| 397 |
+
|
| 398 |
+
# ── helpers ────────────────────────────────────────────────────────────
|
| 399 |
+
|
| 400 |
+
def _get_flight(self, fid: str) -> Optional[Flight]:
|
| 401 |
+
for f in self._state.flights:
|
| 402 |
+
if f.flight_id == fid:
|
| 403 |
+
return f
|
| 404 |
+
return None
|
| 405 |
+
|
| 406 |
+
def _get_runway(self, rid: str) -> Optional[Runway]:
|
| 407 |
+
for r in self._state.runways:
|
| 408 |
+
if r.runway_id == rid:
|
| 409 |
+
return r
|
| 410 |
+
return None
|
| 411 |
+
|
| 412 |
+
def _get_gate(self, gid: str) -> Optional[Gate]:
|
| 413 |
+
for g in self._state.gates:
|
| 414 |
+
if g.gate_id == gid:
|
| 415 |
+
return g
|
| 416 |
+
return None
|
| 417 |
+
|
| 418 |
+
def _do_assign_runway(self, flight: Flight, action: AirportAction,
|
| 419 |
+
obs: AirportObservation) -> Tuple[float, List[str]]:
|
| 420 |
+
events = []
|
| 421 |
+
runway = self._get_runway(action.runway_id or "")
|
| 422 |
+
if runway is None:
|
| 423 |
+
return -1.0, [f"❌ Runway {action.runway_id} not found"]
|
| 424 |
+
if runway.status == RunwayStatus.CLOSED:
|
| 425 |
+
return -2.0, [f"❌ Cannot assign {flight.flight_id} to CLOSED runway {runway.name}"]
|
| 426 |
+
if runway.status == RunwayStatus.OCCUPIED:
|
| 427 |
+
# Conflict!
|
| 428 |
+
self._conflict_count += 1
|
| 429 |
+
return -5.0, [f"💥 CONFLICT: {flight.flight_id} assigned to occupied runway {runway.name}!"]
|
| 430 |
+
|
| 431 |
+
# Separation check
|
| 432 |
+
prev_wc = self._prev_runway_occupant.get(runway.runway_id)
|
| 433 |
+
sep_needed = required_separation(prev_wc, flight.weight_class) if prev_wc else 0
|
| 434 |
+
gap = obs.clock - runway.available_at
|
| 435 |
+
if prev_wc and gap < sep_needed:
|
| 436 |
+
penalty = -1.0 * (sep_needed - gap)
|
| 437 |
+
events.append(f"⚠ Separation violation on {runway.name}: needed {sep_needed:.0f}m, got {gap:.1f}m")
|
| 438 |
+
self._conflict_count += 1
|
| 439 |
+
return penalty, events
|
| 440 |
+
|
| 441 |
+
# Successful assignment
|
| 442 |
+
flight.assigned_runway = runway.runway_id
|
| 443 |
+
flight.status = FlightStatus.LANDING
|
| 444 |
+
flight.actual_landing_time = obs.clock
|
| 445 |
+
runway.status = RunwayStatus.OCCUPIED
|
| 446 |
+
runway.current_flight = flight.flight_id
|
| 447 |
+
runway.available_at = obs.clock + 2.0 # 2 min runway occupancy
|
| 448 |
+
self._prev_runway_occupant[runway.runway_id] = flight.weight_class
|
| 449 |
+
self._safe_landings += 1
|
| 450 |
+
delay = max(0, obs.clock - flight.eta_minutes)
|
| 451 |
+
flight.delay_minutes += delay
|
| 452 |
+
on_time_bonus = 0.3 if delay < 2 else 0.0
|
| 453 |
+
events.append(f"✅ {flight.flight_id} cleared to land on {runway.name} (delay: {delay:.1f}m)")
|
| 454 |
+
return 1.0 + on_time_bonus, events
|
| 455 |
+
|
| 456 |
+
def _do_assign_gate(self, flight: Flight, action: AirportAction,
|
| 457 |
+
obs: AirportObservation) -> Tuple[float, List[str]]:
|
| 458 |
+
gate = self._get_gate(action.gate_id or "")
|
| 459 |
+
if gate is None:
|
| 460 |
+
return -1.0, [f"❌ Gate {action.gate_id} not found"]
|
| 461 |
+
if gate.occupied:
|
| 462 |
+
self._conflict_count += 1
|
| 463 |
+
return -5.0, [f"💥 CONFLICT: Gate {gate.gate_id} already occupied!"]
|
| 464 |
+
if flight.is_international != gate.is_international:
|
| 465 |
+
return -1.5, [f"❌ Gate type mismatch: {'intl' if flight.is_international else 'dom'} flight to {'dom' if flight.is_international else 'intl'} gate"]
|
| 466 |
+
if flight.status not in (FlightStatus.LANDING, FlightStatus.LANDED, FlightStatus.SCHEDULED):
|
| 467 |
+
return -0.5, [f"⚠ {flight.flight_id} not in a state that accepts gate assignment"]
|
| 468 |
+
|
| 469 |
+
gate.occupied = True
|
| 470 |
+
gate.current_flight = flight.flight_id
|
| 471 |
+
gate.available_at = obs.clock + 45 # 45-min turnaround
|
| 472 |
+
flight.assigned_gate = gate.gate_id
|
| 473 |
+
flight.status = FlightStatus.LANDED
|
| 474 |
+
timing_bonus = 0.5 if flight.actual_landing_time and (obs.clock - flight.actual_landing_time) < 5 else 0.0
|
| 475 |
+
return 0.5 + timing_bonus, [f"🅿 {flight.flight_id} → Gate {gate.gate_id} (T{gate.terminal})"]
|
| 476 |
+
|
| 477 |
+
def _could_have_landed(self, flight: Flight, obs: AirportObservation) -> bool:
|
| 478 |
+
return any(r.status == RunwayStatus.CLEAR for r in obs.runways)
|
| 479 |
+
|
| 480 |
+
def _episode_bonus(self, obs: AirportObservation) -> float:
|
| 481 |
+
total = len(obs.flights)
|
| 482 |
+
landed = sum(1 for f in obs.flights if f.status == FlightStatus.LANDED)
|
| 483 |
+
diverted = sum(1 for f in obs.flights if f.status == FlightStatus.DIVERTED)
|
| 484 |
+
on_time = sum(1 for f in obs.flights if f.status == FlightStatus.LANDED and f.delay_minutes < 5)
|
| 485 |
+
conflicts = self._conflict_count
|
| 486 |
+
|
| 487 |
+
throughput = landed / max(total, 1)
|
| 488 |
+
on_time_ratio = on_time / max(landed, 1)
|
| 489 |
+
conflict_penalty = min(conflicts * 1.0, 5.0)
|
| 490 |
+
bonus = 10.0 * throughput * on_time_ratio - conflict_penalty
|
| 491 |
+
return round(max(bonus, 0.0), 2)
|
| 492 |
+
|
| 493 |
+
def grade(self) -> float:
|
| 494 |
+
"""Return a 0.0–1.0 score for the completed episode."""
|
| 495 |
+
if self._state is None:
|
| 496 |
+
return 0.0
|
| 497 |
+
obs = self._state
|
| 498 |
+
total = len(obs.flights)
|
| 499 |
+
landed = sum(1 for f in obs.flights if f.status == FlightStatus.LANDED)
|
| 500 |
+
avg_delay = (sum(f.delay_minutes for f in obs.flights if f.status == FlightStatus.LANDED)
|
| 501 |
+
/ max(landed, 1))
|
| 502 |
+
conflict_ratio = self._conflict_count / max(total, 1)
|
| 503 |
+
emergency_ratio = self._emergency_resolved / max(
|
| 504 |
+
sum(1 for f in obs.flights if f.status == FlightStatus.EMERGENCY) + self._emergency_resolved, 1)
|
| 505 |
+
|
| 506 |
+
score = (
|
| 507 |
+
0.40 * (landed / max(total, 1)) +
|
| 508 |
+
0.25 * max(0, 1 - avg_delay / 20.0) +
|
| 509 |
+
0.20 * (1 - conflict_ratio) +
|
| 510 |
+
0.15 * emergency_ratio
|
| 511 |
+
)
|
| 512 |
+
return round(min(max(score, 0.0), 1.0), 4)
|
graders/__init__.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Task graders for Airport Scheduling Environment.
|
| 3 |
+
Each grader returns a float in [0.0, 1.0].
|
| 4 |
+
"""
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
from typing import List
|
| 7 |
+
from airport_env import AirportObservation, FlightStatus
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def grade_single_runway_landing(obs: AirportObservation) -> float:
|
| 11 |
+
total = len(obs.flights)
|
| 12 |
+
landed = sum(1 for f in obs.flights if f.status == FlightStatus.LANDED)
|
| 13 |
+
avg_delay = (
|
| 14 |
+
sum(f.delay_minutes for f in obs.flights if f.status == FlightStatus.LANDED)
|
| 15 |
+
/ max(landed, 1)
|
| 16 |
+
)
|
| 17 |
+
conflict_free = all(f.assigned_runway for f in obs.flights if f.status == FlightStatus.LANDED)
|
| 18 |
+
score = (
|
| 19 |
+
0.50 * (landed / max(total, 1)) +
|
| 20 |
+
0.35 * max(0.0, 1.0 - avg_delay / 10.0) +
|
| 21 |
+
0.15 * (1.0 if conflict_free else 0.5)
|
| 22 |
+
)
|
| 23 |
+
return round(min(max(score, 0.0), 1.0), 4)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def grade_multi_runway_gate_assignment(obs: AirportObservation) -> float:
|
| 27 |
+
total = len(obs.flights)
|
| 28 |
+
landed = sum(1 for f in obs.flights if f.status == FlightStatus.LANDED)
|
| 29 |
+
gate_assigned = sum(1 for f in obs.flights if f.assigned_gate is not None)
|
| 30 |
+
avg_delay = (
|
| 31 |
+
sum(f.delay_minutes for f in obs.flights if f.status == FlightStatus.LANDED)
|
| 32 |
+
/ max(landed, 1)
|
| 33 |
+
)
|
| 34 |
+
score = (
|
| 35 |
+
0.35 * (landed / max(total, 1)) +
|
| 36 |
+
0.30 * (gate_assigned / max(total, 1)) +
|
| 37 |
+
0.35 * max(0.0, 1.0 - avg_delay / 15.0)
|
| 38 |
+
)
|
| 39 |
+
return round(min(max(score, 0.0), 1.0), 4)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def grade_storm_disruption_recovery(obs: AirportObservation) -> float:
|
| 43 |
+
total = len(obs.flights)
|
| 44 |
+
landed = sum(1 for f in obs.flights if f.status == FlightStatus.LANDED)
|
| 45 |
+
diverted = sum(1 for f in obs.flights if f.status == FlightStatus.DIVERTED)
|
| 46 |
+
avg_delay = (
|
| 47 |
+
sum(f.delay_minutes for f in obs.flights if f.status == FlightStatus.LANDED)
|
| 48 |
+
/ max(landed, 1)
|
| 49 |
+
)
|
| 50 |
+
# Diverted is sometimes necessary — penalize only excess diversions
|
| 51 |
+
diversion_penalty = max(0, diverted - 3) * 0.05
|
| 52 |
+
score = (
|
| 53 |
+
0.40 * (landed / max(total, 1)) +
|
| 54 |
+
0.25 * max(0.0, 1.0 - avg_delay / 20.0) +
|
| 55 |
+
0.20 * max(0.0, 1.0 - diversion_penalty) +
|
| 56 |
+
0.15 * (landed / max(total - diverted, 1))
|
| 57 |
+
)
|
| 58 |
+
return round(min(max(score, 0.0), 1.0), 4)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
GRADERS = {
|
| 62 |
+
"single_runway_landing": grade_single_runway_landing,
|
| 63 |
+
"multi_runway_gate_assignment": grade_multi_runway_gate_assignment,
|
| 64 |
+
"storm_disruption_recovery": grade_storm_disruption_recovery,
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def grade(task_id: str, obs: AirportObservation) -> float:
|
| 69 |
+
grader = GRADERS.get(task_id)
|
| 70 |
+
if grader is None:
|
| 71 |
+
raise ValueError(f"Unknown task_id: {task_id}")
|
| 72 |
+
return grader(obs)
|
inference.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Inference Script — Airport Flight Scheduling Environment
|
| 3 |
+
=========================================================
|
| 4 |
+
Baseline agent using OpenAI-compatible client.
|
| 5 |
+
|
| 6 |
+
Required env vars:
|
| 7 |
+
API_BASE_URL — LLM endpoint (e.g. https://router.huggingface.co/v1)
|
| 8 |
+
MODEL_NAME — model identifier
|
| 9 |
+
HF_TOKEN — API key / HF token
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import os
|
| 14 |
+
import json
|
| 15 |
+
import time
|
| 16 |
+
import textwrap
|
| 17 |
+
from typing import Any, Dict, List
|
| 18 |
+
|
| 19 |
+
from openai import OpenAI
|
| 20 |
+
|
| 21 |
+
# ── Config ─────────────────────────────────────────────────────────────────────
|
| 22 |
+
API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
|
| 23 |
+
API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY", "hf_placeholder")
|
| 24 |
+
MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
|
| 25 |
+
|
| 26 |
+
ENV_BASE_URL = os.getenv("ENV_BASE_URL", "http://localhost:7860")
|
| 27 |
+
MAX_STEPS = 20
|
| 28 |
+
TEMPERATURE = 0.2
|
| 29 |
+
MAX_TOKENS = 400
|
| 30 |
+
|
| 31 |
+
# ── Env HTTP client ────────────────────────────────────────────────────────────
|
| 32 |
+
|
| 33 |
+
def env_post(path: str, payload: Dict = None) -> Dict:
|
| 34 |
+
import urllib.request
|
| 35 |
+
url = f"{ENV_BASE_URL}{path}"
|
| 36 |
+
data = json.dumps(payload or {}).encode()
|
| 37 |
+
req = urllib.request.Request(url, data=data,
|
| 38 |
+
headers={"Content-Type": "application/json"})
|
| 39 |
+
with urllib.request.urlopen(req, timeout=30) as resp:
|
| 40 |
+
return json.loads(resp.read())
|
| 41 |
+
|
| 42 |
+
def env_get(path: str) -> Dict:
|
| 43 |
+
import urllib.request
|
| 44 |
+
url = f"{ENV_BASE_URL}{path}"
|
| 45 |
+
with urllib.request.urlopen(url, timeout=30) as resp:
|
| 46 |
+
return json.loads(resp.read())
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# ── Prompt builders ────────────────────────────────────────────────────────────
|
| 50 |
+
|
| 51 |
+
SYSTEM_PROMPT = textwrap.dedent("""
|
| 52 |
+
You are an AI Air Traffic Controller managing an airport.
|
| 53 |
+
Each step you must output EXACTLY one JSON action object.
|
| 54 |
+
|
| 55 |
+
Available action types:
|
| 56 |
+
- assign_runway : {"action_type":"assign_runway","flight_id":"AA101","runway_id":"R1"}
|
| 57 |
+
- assign_gate : {"action_type":"assign_gate","flight_id":"AA101","gate_id":"G1"}
|
| 58 |
+
- delay_flight : {"action_type":"delay_flight","flight_id":"AA101","delay_minutes":5}
|
| 59 |
+
- divert_flight : {"action_type":"divert_flight","flight_id":"AA101"}
|
| 60 |
+
- clear_runway : {"action_type":"clear_runway","flight_id":"AA101","runway_id":"R1"}
|
| 61 |
+
- declare_emergency: {"action_type":"declare_emergency","flight_id":"AA101"}
|
| 62 |
+
|
| 63 |
+
Rules:
|
| 64 |
+
1. Never assign a flight to an OCCUPIED or CLOSED runway.
|
| 65 |
+
2. Respect wake turbulence separation (heavy before light = 5 min gap).
|
| 66 |
+
3. Match gate type: international flights → international gates (I*), domestic → domestic (D* or G*).
|
| 67 |
+
4. Declare emergency for any flight with EMERGENCY status immediately.
|
| 68 |
+
5. Output ONLY valid JSON. No explanation.
|
| 69 |
+
""").strip()
|
| 70 |
+
|
| 71 |
+
def obs_to_prompt(obs: Dict, step: int) -> str:
|
| 72 |
+
clock = obs.get("clock", 0)
|
| 73 |
+
events = obs.get("recent_events", [])
|
| 74 |
+
flights = obs.get("flights", [])
|
| 75 |
+
runways = obs.get("runways", [])
|
| 76 |
+
gates = obs.get("gates", [])
|
| 77 |
+
weather = obs.get("weather", {})
|
| 78 |
+
|
| 79 |
+
flight_lines = []
|
| 80 |
+
for f in flights:
|
| 81 |
+
if f["status"] in ("landed", "diverted", "departed"):
|
| 82 |
+
continue
|
| 83 |
+
flight_lines.append(
|
| 84 |
+
f" {f['flight_id']} | {f['weight_class']:6} | {f['status']:10} | "
|
| 85 |
+
f"ETA:{f['eta_minutes']:.0f} | fuel:{f['fuel_remaining_min']:.0f} | "
|
| 86 |
+
f"intl:{f['is_international']} | rwy:{f.get('assigned_runway','—')} | gate:{f.get('assigned_gate','—')}"
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
rwy_lines = [
|
| 90 |
+
f" {r['runway_id']} ({r['name']}) — {r['status']} | avail@{r['available_at']:.0f}"
|
| 91 |
+
for r in runways
|
| 92 |
+
]
|
| 93 |
+
gate_lines = [
|
| 94 |
+
f" {g['gate_id']} | {'INTL' if g['is_international'] else 'DOM '} | {'BUSY' if g['occupied'] else 'FREE'}"
|
| 95 |
+
for g in gates
|
| 96 |
+
]
|
| 97 |
+
|
| 98 |
+
return textwrap.dedent(f"""
|
| 99 |
+
Step: {step} | Clock: {clock:.0f} min
|
| 100 |
+
Weather: {weather.get('condition','?')} | vis:{weather.get('visibility_km','?')}km | wind:{weather.get('wind_speed_kts','?')}kts
|
| 101 |
+
Events: {'; '.join(events) if events else 'none'}
|
| 102 |
+
|
| 103 |
+
ACTIVE FLIGHTS:
|
| 104 |
+
{chr(10).join(flight_lines) if flight_lines else ' (none)'}
|
| 105 |
+
|
| 106 |
+
RUNWAYS:
|
| 107 |
+
{chr(10).join(rwy_lines)}
|
| 108 |
+
|
| 109 |
+
GATES:
|
| 110 |
+
{chr(10).join(gate_lines)}
|
| 111 |
+
|
| 112 |
+
Output ONE JSON action:""").strip()
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# ── Main ───────────────────────────────────────────────────────────────────────
|
| 116 |
+
|
| 117 |
+
def run_task(client: OpenAI, task_id: str) -> float:
|
| 118 |
+
print(f"\n{'='*60}")
|
| 119 |
+
print(f"Task: {task_id}")
|
| 120 |
+
print(f"{'='*60}")
|
| 121 |
+
|
| 122 |
+
obs_data = env_post("/reset", {"task_id": task_id, "seed": 42})
|
| 123 |
+
print(f" Flights: {len(obs_data.get('flights', []))}")
|
| 124 |
+
|
| 125 |
+
for step in range(1, MAX_STEPS + 1):
|
| 126 |
+
if obs_data.get("episode_done") or obs_data.get("done"):
|
| 127 |
+
break
|
| 128 |
+
|
| 129 |
+
prompt = obs_to_prompt(obs_data, step)
|
| 130 |
+
try:
|
| 131 |
+
completion = client.chat.completions.create(
|
| 132 |
+
model=MODEL_NAME,
|
| 133 |
+
messages=[
|
| 134 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 135 |
+
{"role": "user", "content": prompt},
|
| 136 |
+
],
|
| 137 |
+
temperature=TEMPERATURE,
|
| 138 |
+
max_tokens=MAX_TOKENS,
|
| 139 |
+
)
|
| 140 |
+
raw = completion.choices[0].message.content or "{}"
|
| 141 |
+
# Strip markdown fences if present
|
| 142 |
+
raw = raw.strip().lstrip("```json").lstrip("```").rstrip("```").strip()
|
| 143 |
+
action = json.loads(raw)
|
| 144 |
+
except Exception as exc:
|
| 145 |
+
print(f" Step {step}: LLM error ({exc}), using noop delay")
|
| 146 |
+
# Find first active flight as fallback
|
| 147 |
+
active = [f for f in obs_data.get("flights", [])
|
| 148 |
+
if f["status"] not in ("landed","diverted","departed")]
|
| 149 |
+
if active:
|
| 150 |
+
action = {"action_type": "delay_flight",
|
| 151 |
+
"flight_id": active[0]["flight_id"],
|
| 152 |
+
"delay_minutes": 2}
|
| 153 |
+
else:
|
| 154 |
+
break
|
| 155 |
+
|
| 156 |
+
try:
|
| 157 |
+
result = env_post("/step", {"action": action, "task_id": task_id})
|
| 158 |
+
except Exception as exc:
|
| 159 |
+
print(f" Step {step}: env error ({exc})")
|
| 160 |
+
break
|
| 161 |
+
|
| 162 |
+
obs_data = result.get("observation", obs_data)
|
| 163 |
+
reward = result.get("reward", {})
|
| 164 |
+
done = result.get("done", False)
|
| 165 |
+
print(f" Step {step:2d}: {action.get('action_type','?'):20s} | "
|
| 166 |
+
f"reward: {reward.get('value', 0):+.2f} | "
|
| 167 |
+
f"cumulative: {obs_data.get('score_so_far', 0):+.2f}")
|
| 168 |
+
|
| 169 |
+
if done:
|
| 170 |
+
print(f" Episode done at step {step}")
|
| 171 |
+
break
|
| 172 |
+
|
| 173 |
+
grade_data = env_get(f"/grade?task_id={task_id}")
|
| 174 |
+
score = grade_data.get("score", 0.0)
|
| 175 |
+
print(f" Final grade: {score:.4f}")
|
| 176 |
+
return score
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def main():
|
| 180 |
+
client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
|
| 181 |
+
|
| 182 |
+
tasks = [
|
| 183 |
+
"single_runway_landing",
|
| 184 |
+
"multi_runway_gate_assignment",
|
| 185 |
+
"storm_disruption_recovery",
|
| 186 |
+
]
|
| 187 |
+
|
| 188 |
+
results = {}
|
| 189 |
+
for task_id in tasks:
|
| 190 |
+
try:
|
| 191 |
+
score = run_task(client, task_id)
|
| 192 |
+
results[task_id] = score
|
| 193 |
+
except Exception as exc:
|
| 194 |
+
print(f" ERROR on {task_id}: {exc}")
|
| 195 |
+
results[task_id] = 0.0
|
| 196 |
+
time.sleep(1)
|
| 197 |
+
|
| 198 |
+
print(f"\n{'='*60}")
|
| 199 |
+
print("BASELINE RESULTS")
|
| 200 |
+
print(f"{'='*60}")
|
| 201 |
+
for task_id, score in results.items():
|
| 202 |
+
print(f" {task_id:<40} {score:.4f}")
|
| 203 |
+
avg = sum(results.values()) / len(results)
|
| 204 |
+
print(f" {'AVERAGE':<40} {avg:.4f}")
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
if __name__ == "__main__":
|
| 208 |
+
main()
|
main.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Airport Scheduling OpenEnv — main entry point."""
|
| 2 |
+
import os
|
| 3 |
+
import uvicorn
|
| 4 |
+
|
| 5 |
+
def main():
|
| 6 |
+
port = int(os.getenv("PORT", 7860))
|
| 7 |
+
uvicorn.run("server.app:app", host="0.0.0.0", port=port, reload=False)
|
| 8 |
+
|
| 9 |
+
if __name__ == "__main__":
|
| 10 |
+
main()
|
openenv.yaml
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: airport-scheduling-env
|
| 2 |
+
version: "0.1.0"
|
| 3 |
+
description: >
|
| 4 |
+
Airport Flight Scheduling Environment — an OpenEnv environment where an AI agent
|
| 5 |
+
manages runway assignments, gate allocations, and flight sequencing for a busy
|
| 6 |
+
international airport. Agents must minimize delays, maximize throughput, and
|
| 7 |
+
handle weather disruptions across 3 tasks of increasing difficulty.
|
| 8 |
+
author: airport-env-team
|
| 9 |
+
tags:
|
| 10 |
+
- scheduling
|
| 11 |
+
- logistics
|
| 12 |
+
- real-world
|
| 13 |
+
- multi-constraint
|
| 14 |
+
- openenv
|
| 15 |
+
|
| 16 |
+
tasks:
|
| 17 |
+
- id: single_runway_landing
|
| 18 |
+
name: Single Runway Landing Sequence
|
| 19 |
+
difficulty: easy
|
| 20 |
+
description: >
|
| 21 |
+
Sequence 5 arriving flights onto a single runway. Minimize total delay
|
| 22 |
+
while respecting wake turbulence separation rules (heavy before light
|
| 23 |
+
requires 3-min gap; same category requires 2-min gap).
|
| 24 |
+
|
| 25 |
+
- id: multi_runway_gate_assignment
|
| 26 |
+
name: Multi-Runway Gate Assignment
|
| 27 |
+
difficulty: medium
|
| 28 |
+
description: >
|
| 29 |
+
Manage 2 runways and 8 gates for 10 simultaneous arrivals and departures.
|
| 30 |
+
Assign each flight to the correct runway and gate type (domestic/international),
|
| 31 |
+
avoid conflicts, and minimize total passenger walk time.
|
| 32 |
+
|
| 33 |
+
- id: storm_disruption_recovery
|
| 34 |
+
name: Storm Disruption Recovery
|
| 35 |
+
difficulty: hard
|
| 36 |
+
description: >
|
| 37 |
+
A severe storm closes runway 2 mid-episode and causes 40% of flights to
|
| 38 |
+
divert or hold. Reassign all affected flights, manage fuel emergency
|
| 39 |
+
priority overrides, and restore schedule adherence within 60 simulated
|
| 40 |
+
minutes. Score is based on safety, delay minutes, and diversion count.
|
| 41 |
+
|
| 42 |
+
observation_space:
|
| 43 |
+
flights: "List of arriving/departing flights with ETA, type, weight class, fuel state"
|
| 44 |
+
runways: "Availability status and current occupant per runway"
|
| 45 |
+
gates: "Occupancy, terminal, domestic/international flag per gate"
|
| 46 |
+
weather: "Visibility, wind speed/direction, active NOTAMs"
|
| 47 |
+
clock: "Simulated time in minutes from episode start"
|
| 48 |
+
|
| 49 |
+
action_space:
|
| 50 |
+
assign_runway: "Assign a flight_id to a runway_id with optional delay offset"
|
| 51 |
+
assign_gate: "Assign a flight_id to a gate_id"
|
| 52 |
+
delay_flight: "Push a flight's scheduled time by N minutes"
|
| 53 |
+
divert_flight: "Send a flight to alternate airport (removes from board)"
|
| 54 |
+
clear_runway: "Mark runway as clear after departure/landing"
|
| 55 |
+
declare_emergency: "Grant priority clearance to a fuel-critical flight"
|
| 56 |
+
|
| 57 |
+
reward:
|
| 58 |
+
per_step: "−0.1 × total delay minutes accumulated this step"
|
| 59 |
+
on_safe_landing: "+1.0 per successful landing without conflict"
|
| 60 |
+
on_gate_assigned: "+0.5 per gate assigned within 5 min of landing"
|
| 61 |
+
on_conflict: "−5.0 per runway incursion or gate double-booking"
|
| 62 |
+
on_emergency_resolved: "+3.0 per fuel emergency resolved before critical"
|
| 63 |
+
on_unnecessary_diversion: "−2.0 per diversion that could have been avoided"
|
| 64 |
+
episode_bonus: "Up to +10.0 based on on-time performance ratio"
|
pyproject.toml
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["hatchling"]
|
| 3 |
+
build-backend = "hatchling.build"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "airport-scheduling-env"
|
| 7 |
+
version = "0.1.0"
|
| 8 |
+
description = "Airport Flight Scheduling OpenEnv Environment"
|
| 9 |
+
requires-python = ">=3.10"
|
| 10 |
+
dependencies = [
|
| 11 |
+
"openenv-core>=0.2.0",
|
| 12 |
+
"fastapi>=0.110.0",
|
| 13 |
+
"uvicorn[standard]>=0.29.0",
|
| 14 |
+
"pydantic>=2.0.0",
|
| 15 |
+
"openai>=1.0.0",
|
| 16 |
+
"numpy>=1.24.0",
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
[project.scripts]
|
| 20 |
+
server = "server.app:start"
|
| 21 |
+
|
| 22 |
+
[tool.hatch.build.targets.wheel]
|
| 23 |
+
packages = ["server", "tasks", "graders"]
|
server/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# server package
|
server/app.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Airport Scheduling Environment — FastAPI Server
|
| 3 |
+
"""
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
from typing import Any, Dict
|
| 8 |
+
from fastapi import FastAPI, HTTPException
|
| 9 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
+
from fastapi.responses import JSONResponse
|
| 11 |
+
from pydantic import BaseModel
|
| 12 |
+
|
| 13 |
+
import sys
|
| 14 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
| 15 |
+
|
| 16 |
+
from airport_env import (
|
| 17 |
+
AirportEnv, AirportAction, AirportObservation, AirportReward,
|
| 18 |
+
ActionType
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
app = FastAPI(
|
| 22 |
+
title="Airport Scheduling OpenEnv",
|
| 23 |
+
description="AI agent environment for airport runway, gate, and flight scheduling",
|
| 24 |
+
version="0.1.0",
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
app.add_middleware(
|
| 28 |
+
CORSMiddleware,
|
| 29 |
+
allow_origins=["*"],
|
| 30 |
+
allow_methods=["*"],
|
| 31 |
+
allow_headers=["*"],
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
# ── Global env instances per task ──────────────────────────────────────────────
|
| 35 |
+
_envs: Dict[str, AirportEnv] = {}
|
| 36 |
+
_active_task: str = "single_runway_landing"
|
| 37 |
+
|
| 38 |
+
def _get_env(task_id: str = None) -> AirportEnv:
|
| 39 |
+
tid = task_id or _active_task
|
| 40 |
+
if tid not in _envs:
|
| 41 |
+
_envs[tid] = AirportEnv(task_id=tid)
|
| 42 |
+
return _envs[tid]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# ── Request models ─────────────────────────────────────────────────────────────
|
| 46 |
+
|
| 47 |
+
class ResetRequest(BaseModel):
|
| 48 |
+
task_id: str = "single_runway_landing"
|
| 49 |
+
seed: int = 42
|
| 50 |
+
|
| 51 |
+
class StepRequest(BaseModel):
|
| 52 |
+
action: Dict[str, Any]
|
| 53 |
+
task_id: str = "single_runway_landing"
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# ── Endpoints ──────────────────────────────────────────────────────────────────
|
| 57 |
+
|
| 58 |
+
@app.get("/")
|
| 59 |
+
def root():
|
| 60 |
+
return {
|
| 61 |
+
"name": "airport-scheduling-env",
|
| 62 |
+
"version": "0.1.0",
|
| 63 |
+
"tasks": AirportEnv.TASK_IDS,
|
| 64 |
+
"endpoints": ["/reset", "/step", "/state", "/grade", "/tasks", "/health"],
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
@app.get("/health")
|
| 68 |
+
def health():
|
| 69 |
+
return {"status": "ok"}
|
| 70 |
+
|
| 71 |
+
@app.post("/reset")
|
| 72 |
+
def reset(req: ResetRequest = None):
|
| 73 |
+
req = req or ResetRequest()
|
| 74 |
+
env = AirportEnv(task_id=req.task_id, seed=req.seed)
|
| 75 |
+
_envs[req.task_id] = env
|
| 76 |
+
obs = env.reset()
|
| 77 |
+
return obs.model_dump()
|
| 78 |
+
|
| 79 |
+
@app.post("/step")
|
| 80 |
+
def step(req: StepRequest):
|
| 81 |
+
env = _get_env(req.task_id)
|
| 82 |
+
if env._state is None:
|
| 83 |
+
raise HTTPException(status_code=400, detail="Call /reset first")
|
| 84 |
+
try:
|
| 85 |
+
action = AirportAction(**req.action)
|
| 86 |
+
except Exception as e:
|
| 87 |
+
raise HTTPException(status_code=422, detail=f"Invalid action: {e}")
|
| 88 |
+
obs, reward, done, info = env.step(action)
|
| 89 |
+
return {
|
| 90 |
+
"observation": obs.model_dump(),
|
| 91 |
+
"reward": reward.model_dump(),
|
| 92 |
+
"done": done,
|
| 93 |
+
"info": info,
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
@app.get("/state")
|
| 97 |
+
def state(task_id: str = "single_runway_landing"):
|
| 98 |
+
env = _get_env(task_id)
|
| 99 |
+
if env._state is None:
|
| 100 |
+
return _get_env(task_id).reset().model_dump()
|
| 101 |
+
return env.state().model_dump()
|
| 102 |
+
|
| 103 |
+
@app.get("/grade")
|
| 104 |
+
def grade(task_id: str = "single_runway_landing"):
|
| 105 |
+
env = _get_env(task_id)
|
| 106 |
+
score = env.grade()
|
| 107 |
+
return {"task_id": task_id, "score": score}
|
| 108 |
+
|
| 109 |
+
@app.get("/tasks")
|
| 110 |
+
def tasks():
|
| 111 |
+
return {
|
| 112 |
+
"tasks": [
|
| 113 |
+
{
|
| 114 |
+
"id": "single_runway_landing",
|
| 115 |
+
"name": "Single Runway Landing Sequence",
|
| 116 |
+
"difficulty": "easy",
|
| 117 |
+
"description": "Sequence 5 arriving flights onto a single runway minimizing delays.",
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"id": "multi_runway_gate_assignment",
|
| 121 |
+
"name": "Multi-Runway Gate Assignment",
|
| 122 |
+
"difficulty": "medium",
|
| 123 |
+
"description": "Manage 2 runways and 8 gates for 10 simultaneous arrivals.",
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"id": "storm_disruption_recovery",
|
| 127 |
+
"name": "Storm Disruption Recovery",
|
| 128 |
+
"difficulty": "hard",
|
| 129 |
+
"description": "Handle runway closure, emergencies and reassignments during a storm.",
|
| 130 |
+
},
|
| 131 |
+
]
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def start():
|
| 136 |
+
import uvicorn
|
| 137 |
+
port = int(os.getenv("PORT", 7860))
|
| 138 |
+
uvicorn.run("server.app:app", host="0.0.0.0", port=port, reload=False)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
if __name__ == "__main__":
|
| 142 |
+
start()
|
tasks/__init__.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Task definitions for Airport Scheduling Environment."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
TASKS = [
|
| 5 |
+
{
|
| 6 |
+
"id": "single_runway_landing",
|
| 7 |
+
"name": "Single Runway Landing Sequence",
|
| 8 |
+
"difficulty": "easy",
|
| 9 |
+
"description": (
|
| 10 |
+
"Sequence 5 arriving flights onto a single runway. "
|
| 11 |
+
"Minimize total delay while respecting ICAO wake turbulence separation rules."
|
| 12 |
+
),
|
| 13 |
+
"n_flights": 5,
|
| 14 |
+
"n_runways": 1,
|
| 15 |
+
"n_gates": 5,
|
| 16 |
+
"episode_horizon": 30,
|
| 17 |
+
},
|
| 18 |
+
{
|
| 19 |
+
"id": "multi_runway_gate_assignment",
|
| 20 |
+
"name": "Multi-Runway Gate Assignment",
|
| 21 |
+
"difficulty": "medium",
|
| 22 |
+
"description": (
|
| 23 |
+
"Manage 2 runways and 8 gates for 10 simultaneous arrivals and departures. "
|
| 24 |
+
"Assign each flight to the correct runway and gate type."
|
| 25 |
+
),
|
| 26 |
+
"n_flights": 10,
|
| 27 |
+
"n_runways": 2,
|
| 28 |
+
"n_gates": 8,
|
| 29 |
+
"episode_horizon": 60,
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"id": "storm_disruption_recovery",
|
| 33 |
+
"name": "Storm Disruption Recovery",
|
| 34 |
+
"difficulty": "hard",
|
| 35 |
+
"description": (
|
| 36 |
+
"A severe storm closes runway 2 at T+20. "
|
| 37 |
+
"Reassign all affected flights, handle fuel emergencies, "
|
| 38 |
+
"and restore schedule adherence."
|
| 39 |
+
),
|
| 40 |
+
"n_flights": 15,
|
| 41 |
+
"n_runways": 2,
|
| 42 |
+
"n_gates": 10,
|
| 43 |
+
"episode_horizon": 90,
|
| 44 |
+
},
|
| 45 |
+
]
|
test_env.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
test_env.py — Local validation of Airport Scheduling Environment
|
| 4 |
+
Run: python test_env.py
|
| 5 |
+
"""
|
| 6 |
+
import sys
|
| 7 |
+
import os
|
| 8 |
+
sys.path.insert(0, os.path.dirname(__file__))
|
| 9 |
+
|
| 10 |
+
try:
|
| 11 |
+
from airport_env import (
|
| 12 |
+
AirportEnv, AirportAction, ActionType,
|
| 13 |
+
FlightStatus, RunwayStatus, WeightClass
|
| 14 |
+
)
|
| 15 |
+
print("✅ Import OK")
|
| 16 |
+
except ImportError as e:
|
| 17 |
+
print(f"❌ Import failed: {e}")
|
| 18 |
+
sys.exit(1)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test_task(task_id: str, verbose: bool = True):
|
| 22 |
+
print(f"\n{'─'*50}")
|
| 23 |
+
print(f"Testing: {task_id}")
|
| 24 |
+
print(f"{'─'*50}")
|
| 25 |
+
|
| 26 |
+
env = AirportEnv(task_id=task_id, seed=42)
|
| 27 |
+
obs = env.reset()
|
| 28 |
+
|
| 29 |
+
assert obs.clock == 0.0, "Clock should start at 0"
|
| 30 |
+
assert len(obs.flights) > 0, "Should have flights"
|
| 31 |
+
assert len(obs.runways) > 0, "Should have runways"
|
| 32 |
+
assert len(obs.gates) > 0, "Should have gates"
|
| 33 |
+
print(f" reset() → {len(obs.flights)} flights, {len(obs.runways)} runways, {len(obs.gates)} gates")
|
| 34 |
+
|
| 35 |
+
# state() returns same obs
|
| 36 |
+
s = env.state()
|
| 37 |
+
assert s.clock == obs.clock, "state() clock mismatch"
|
| 38 |
+
print(f" state() → clock={s.clock}")
|
| 39 |
+
|
| 40 |
+
# Run steps
|
| 41 |
+
total_reward = 0.0
|
| 42 |
+
for i in range(min(15, len(obs.flights) * 3)):
|
| 43 |
+
# Find an actionable flight
|
| 44 |
+
flight = next(
|
| 45 |
+
(f for f in obs.flights if f.status in ('scheduled', 'holding', 'landing', 'emergency')),
|
| 46 |
+
None
|
| 47 |
+
)
|
| 48 |
+
if flight is None:
|
| 49 |
+
break
|
| 50 |
+
|
| 51 |
+
# Choose action based on status
|
| 52 |
+
if flight.status == 'emergency':
|
| 53 |
+
action = AirportAction(action_type=ActionType.DECLARE_EMERGENCY, flight_id=flight.flight_id)
|
| 54 |
+
elif flight.status == 'landing' and not flight.assigned_gate:
|
| 55 |
+
gate = next((g for g in obs.gates if not g.occupied and g.is_international == flight.is_international), None)
|
| 56 |
+
if gate:
|
| 57 |
+
action = AirportAction(action_type=ActionType.ASSIGN_GATE, flight_id=flight.flight_id, gate_id=gate.gate_id)
|
| 58 |
+
else:
|
| 59 |
+
action = AirportAction(action_type=ActionType.DELAY_FLIGHT, flight_id=flight.flight_id, delay_minutes=3)
|
| 60 |
+
else:
|
| 61 |
+
rwy = next((r for r in obs.runways if r.status == 'clear'), None)
|
| 62 |
+
if rwy:
|
| 63 |
+
action = AirportAction(action_type=ActionType.ASSIGN_RUNWAY, flight_id=flight.flight_id, runway_id=rwy.runway_id)
|
| 64 |
+
# Immediately clear it on next step
|
| 65 |
+
else:
|
| 66 |
+
occ_rwy = next((r for r in obs.runways if r.status == 'occupied'), None)
|
| 67 |
+
if occ_rwy:
|
| 68 |
+
action = AirportAction(action_type=ActionType.CLEAR_RUNWAY, flight_id=flight.flight_id, runway_id=occ_rwy.runway_id)
|
| 69 |
+
else:
|
| 70 |
+
action = AirportAction(action_type=ActionType.DELAY_FLIGHT, flight_id=flight.flight_id, delay_minutes=2)
|
| 71 |
+
|
| 72 |
+
obs, reward, done, info = env.step(action)
|
| 73 |
+
total_reward += reward.value
|
| 74 |
+
|
| 75 |
+
if verbose:
|
| 76 |
+
print(f" step {i+1:2d}: {action.action_type.value:20s} {flight.flight_id} → reward={reward.value:+.2f} | cum={total_reward:+.2f}")
|
| 77 |
+
|
| 78 |
+
if done:
|
| 79 |
+
print(f" Episode done at step {i+1}")
|
| 80 |
+
break
|
| 81 |
+
|
| 82 |
+
grade = env.grade()
|
| 83 |
+
assert 0.0 <= grade <= 1.0, f"Grade out of range: {grade}"
|
| 84 |
+
print(f" grade() → {grade:.4f}")
|
| 85 |
+
print(f" total reward: {total_reward:.2f}")
|
| 86 |
+
return grade
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def test_all():
|
| 90 |
+
print("\n" + "="*50)
|
| 91 |
+
print("Airport Scheduling Env — Test Suite")
|
| 92 |
+
print("="*50)
|
| 93 |
+
|
| 94 |
+
grades = {}
|
| 95 |
+
for task_id in AirportEnv.TASK_IDS:
|
| 96 |
+
try:
|
| 97 |
+
g = test_task(task_id)
|
| 98 |
+
grades[task_id] = g
|
| 99 |
+
assert 0.0 <= g <= 1.0
|
| 100 |
+
print(f" ✅ PASS")
|
| 101 |
+
except AssertionError as e:
|
| 102 |
+
print(f" ❌ FAIL: {e}")
|
| 103 |
+
grades[task_id] = -1.0
|
| 104 |
+
|
| 105 |
+
print(f"\n{'='*50}")
|
| 106 |
+
print("Results:")
|
| 107 |
+
for task_id, g in grades.items():
|
| 108 |
+
status = "✅" if g >= 0 else "❌"
|
| 109 |
+
print(f" {status} {task_id:<42} {g:.4f}")
|
| 110 |
+
|
| 111 |
+
all_pass = all(g >= 0 for g in grades.values())
|
| 112 |
+
print(f"\n{'✅ All tests passed!' if all_pass else '❌ Some tests failed.'}")
|
| 113 |
+
return all_pass
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
if __name__ == "__main__":
|
| 117 |
+
ok = test_all()
|
| 118 |
+
sys.exit(0 if ok else 1)
|
uv.lock
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version = 1
|
| 2 |
+
requires-python = ">=3.10"
|
| 3 |
+
|
| 4 |
+
[[package]]
|
| 5 |
+
name = "airport-scheduling-env"
|
| 6 |
+
version = "0.1.0"
|
| 7 |
+
source = { editable = "." }
|
| 8 |
+
dependencies = [
|
| 9 |
+
{ name = "fastapi" },
|
| 10 |
+
{ name = "openai" },
|
| 11 |
+
{ name = "openenv-core" },
|
| 12 |
+
{ name = "pydantic" },
|
| 13 |
+
{ name = "uvicorn" },
|
| 14 |
+
{ name = "numpy" },
|
| 15 |
+
]
|
validate_logic.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
validate_logic.py — Pure stdlib validation (no pydantic required)
|
| 4 |
+
Tests all environment logic using plain dicts to simulate the state.
|
| 5 |
+
"""
|
| 6 |
+
import random
|
| 7 |
+
import sys
|
| 8 |
+
|
| 9 |
+
# ── Enums as constants ────────────────────────────────────────────────────────
|
| 10 |
+
WC_ORDER = ['light', 'medium', 'heavy', 'super']
|
| 11 |
+
SEP = {
|
| 12 |
+
('super','super'):3,('super','heavy'):4,('super','medium'):5,('super','light'):6,
|
| 13 |
+
('heavy','super'):2,('heavy','heavy'):3,('heavy','medium'):4,('heavy','light'):5,
|
| 14 |
+
('medium','super'):2,('medium','heavy'):2,('medium','medium'):2,('medium','light'):3,
|
| 15 |
+
('light','super'):2,('light','heavy'):2,('light','medium'):2,('light','light'):2,
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
AIRLINES = ['AA','UA','DL','SW','BA','LH']
|
| 19 |
+
AIRPORTS = ['JFK','LAX','ORD','ATL','LHR','CDG']
|
| 20 |
+
|
| 21 |
+
def make_flight(i, spread=20, rng=None):
|
| 22 |
+
r = rng or random
|
| 23 |
+
al = r.choice(AIRLINES)
|
| 24 |
+
wc = r.choices(WC_ORDER, weights=[10,40,40,10])[0]
|
| 25 |
+
eta = 1 + r.random() * spread
|
| 26 |
+
fuel = eta + 20 + r.random() * 40
|
| 27 |
+
return dict(
|
| 28 |
+
flight_id=f"{al}{100+i}", airline=al, weight_class=wc,
|
| 29 |
+
status='scheduled', eta_minutes=round(eta,1),
|
| 30 |
+
fuel_remaining_min=round(fuel,1), is_international=r.random()<0.4,
|
| 31 |
+
assigned_runway=None, assigned_gate=None,
|
| 32 |
+
actual_landing_time=None, delay_minutes=0.0, passenger_count=150
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
def make_env(task_id, seed=42):
|
| 36 |
+
rng = random.Random(seed)
|
| 37 |
+
n = {'single_runway_landing':5,'multi_runway_gate_assignment':10,'storm_disruption_recovery':15}[task_id]
|
| 38 |
+
spread = {'single_runway_landing':20,'multi_runway_gate_assignment':30,'storm_disruption_recovery':40}[task_id]
|
| 39 |
+
flights = [make_flight(i, spread, rng) for i in range(n)]
|
| 40 |
+
if task_id == 'storm_disruption_recovery':
|
| 41 |
+
for f in rng.sample(flights, 4):
|
| 42 |
+
f['fuel_remaining_min'] = f['eta_minutes'] + 5 + rng.random()*10
|
| 43 |
+
|
| 44 |
+
if task_id == 'single_runway_landing':
|
| 45 |
+
runways = [dict(runway_id='R1', name='09L/27R', status='clear', current_flight=None, available_at=0)]
|
| 46 |
+
gates = [dict(gate_id=f'G{i}', terminal='T1', is_international=False, occupied=False, current_flight=None) for i in range(1,6)]
|
| 47 |
+
else:
|
| 48 |
+
runways = [
|
| 49 |
+
dict(runway_id='R1', name='09L/27R', status='clear', current_flight=None, available_at=0),
|
| 50 |
+
dict(runway_id='R2', name='09R/27L', status='clear', current_flight=None, available_at=0),
|
| 51 |
+
]
|
| 52 |
+
gates = (
|
| 53 |
+
[dict(gate_id=f'D{i}', terminal='T1', is_international=False, occupied=False, current_flight=None) for i in range(1,5)] +
|
| 54 |
+
[dict(gate_id=f'I{i}', terminal='T2', is_international=True, occupied=False, current_flight=None) for i in range(1,5)]
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
return dict(clock=0.0, flights=flights, runways=runways, gates=gates,
|
| 58 |
+
task_id=task_id, episode_done=False, recent_events=[], score=0.0)
|
| 59 |
+
|
| 60 |
+
def get_runway(state, rid): return next((r for r in state['runways'] if r['runway_id']==rid), None)
|
| 61 |
+
def get_gate(state, gid): return next((g for g in state['gates'] if g['gate_id']==gid), None)
|
| 62 |
+
def get_flight(state, fid): return next((f for f in state['flights'] if f['flight_id']==fid), None)
|
| 63 |
+
|
| 64 |
+
def step(state, action):
|
| 65 |
+
state['clock'] += 1.0
|
| 66 |
+
reward = 0.0
|
| 67 |
+
events = []
|
| 68 |
+
|
| 69 |
+
# Storm trigger
|
| 70 |
+
if state['task_id']=='storm_disruption_recovery' and abs(state['clock']-20)<0.5:
|
| 71 |
+
r2 = get_runway(state,'R2')
|
| 72 |
+
if r2 and r2['status']!='closed':
|
| 73 |
+
r2['status']='closed'
|
| 74 |
+
events.append('STORM: R2 CLOSED')
|
| 75 |
+
|
| 76 |
+
# Fuel emergencies
|
| 77 |
+
for f in state['flights']:
|
| 78 |
+
if f['status'] in ('scheduled','holding') and f['fuel_remaining_min']-state['clock']<=5:
|
| 79 |
+
f['status']='emergency'
|
| 80 |
+
|
| 81 |
+
# Delay penalty
|
| 82 |
+
unresolved = [f for f in state['flights'] if f['status'] in ('scheduled','holding') and f['eta_minutes']<=state['clock']]
|
| 83 |
+
reward -= 0.1 * len(unresolved)
|
| 84 |
+
|
| 85 |
+
at = action['action_type']
|
| 86 |
+
fid = action['flight_id']
|
| 87 |
+
flight = get_flight(state, fid)
|
| 88 |
+
|
| 89 |
+
if flight is None:
|
| 90 |
+
reward -= 0.5
|
| 91 |
+
elif at == 'assign_runway':
|
| 92 |
+
rwy = get_runway(state, action.get('runway_id',''))
|
| 93 |
+
if not rwy:
|
| 94 |
+
reward -= 1.0
|
| 95 |
+
elif rwy['status'] == 'closed':
|
| 96 |
+
reward -= 2.0
|
| 97 |
+
elif rwy['status'] == 'occupied':
|
| 98 |
+
reward -= 5.0
|
| 99 |
+
else:
|
| 100 |
+
flight['assigned_runway'] = rwy['runway_id']
|
| 101 |
+
flight['status'] = 'landing'
|
| 102 |
+
flight['actual_landing_time'] = state['clock']
|
| 103 |
+
delay = max(0, state['clock'] - flight['eta_minutes'])
|
| 104 |
+
flight['delay_minutes'] += delay
|
| 105 |
+
rwy['status'] = 'occupied'
|
| 106 |
+
rwy['current_flight'] = flight['flight_id']
|
| 107 |
+
rwy['available_at'] = state['clock'] + 2
|
| 108 |
+
reward += 1.0 + (0.3 if delay < 2 else 0.0)
|
| 109 |
+
events.append(f"LANDED {flight['flight_id']} on {rwy['runway_id']}")
|
| 110 |
+
elif at == 'assign_gate':
|
| 111 |
+
gate = get_gate(state, action.get('gate_id',''))
|
| 112 |
+
if not gate:
|
| 113 |
+
reward -= 1.0
|
| 114 |
+
elif gate['occupied']:
|
| 115 |
+
reward -= 5.0
|
| 116 |
+
elif flight['is_international'] != gate['is_international']:
|
| 117 |
+
reward -= 1.5
|
| 118 |
+
else:
|
| 119 |
+
gate['occupied'] = True
|
| 120 |
+
gate['current_flight'] = flight['flight_id']
|
| 121 |
+
flight['assigned_gate'] = gate['gate_id']
|
| 122 |
+
flight['status'] = 'landed'
|
| 123 |
+
reward += 1.0
|
| 124 |
+
events.append(f"GATE {flight['flight_id']} -> {gate['gate_id']}")
|
| 125 |
+
elif at == 'delay_flight':
|
| 126 |
+
m = action.get('delay_minutes', 5)
|
| 127 |
+
flight['eta_minutes'] += m
|
| 128 |
+
flight['delay_minutes'] += m
|
| 129 |
+
reward -= 0.2 * m
|
| 130 |
+
elif at == 'divert_flight':
|
| 131 |
+
can_land = any(r['status']=='clear' for r in state['runways'])
|
| 132 |
+
flight['status'] = 'diverted'
|
| 133 |
+
reward += (-2.0 if can_land else -0.5)
|
| 134 |
+
elif at == 'clear_runway':
|
| 135 |
+
rwy = get_runway(state, action.get('runway_id',''))
|
| 136 |
+
if rwy and rwy['status']=='occupied':
|
| 137 |
+
rwy['status']='clear'
|
| 138 |
+
rwy['current_flight']=None
|
| 139 |
+
reward += 0.1
|
| 140 |
+
elif at == 'declare_emergency':
|
| 141 |
+
if flight['status']=='emergency':
|
| 142 |
+
reward += 3.0
|
| 143 |
+
flight['status']='landing'
|
| 144 |
+
else:
|
| 145 |
+
reward -= 0.2
|
| 146 |
+
|
| 147 |
+
state['score'] += reward
|
| 148 |
+
state['recent_events'] = events[-6:]
|
| 149 |
+
active = [f for f in state['flights'] if f['status'] not in ('landed','diverted')]
|
| 150 |
+
done = len(active)==0 or state['clock']>=90
|
| 151 |
+
if done:
|
| 152 |
+
state['episode_done'] = True
|
| 153 |
+
return reward, done
|
| 154 |
+
|
| 155 |
+
def grade(state):
|
| 156 |
+
total = len(state['flights'])
|
| 157 |
+
landed = [f for f in state['flights'] if f['status']=='landed']
|
| 158 |
+
avg_delay = sum(f['delay_minutes'] for f in landed)/max(len(landed),1)
|
| 159 |
+
conflict_free = 1.0 # simplification
|
| 160 |
+
score = (0.40*(len(landed)/max(total,1)) + 0.25*max(0,1-avg_delay/20) + 0.20*conflict_free + 0.15)
|
| 161 |
+
return round(min(max(score,0),1),4)
|
| 162 |
+
|
| 163 |
+
# ── Tests ─────────────────────────────────────────────────────────────────────
|
| 164 |
+
def run_task(task_id):
|
| 165 |
+
state = make_env(task_id)
|
| 166 |
+
assert state['clock'] == 0.0
|
| 167 |
+
assert len(state['flights']) > 0
|
| 168 |
+
assert len(state['runways']) > 0
|
| 169 |
+
assert len(state['gates']) > 0
|
| 170 |
+
print(f" reset OK: {len(state['flights'])} flights, {len(state['runways'])} runways")
|
| 171 |
+
|
| 172 |
+
total_reward = 0.0
|
| 173 |
+
steps = 0
|
| 174 |
+
while steps < 30:
|
| 175 |
+
# greedy agent
|
| 176 |
+
flight = next((f for f in state['flights'] if f['status']=='emergency'), None)
|
| 177 |
+
if flight:
|
| 178 |
+
action = dict(action_type='declare_emergency', flight_id=flight['flight_id'])
|
| 179 |
+
else:
|
| 180 |
+
landing_no_gate = next((f for f in state['flights'] if f['status']=='landing' and not f['assigned_gate']), None)
|
| 181 |
+
if landing_no_gate:
|
| 182 |
+
gate = next((g for g in state['gates'] if not g['occupied'] and g['is_international']==landing_no_gate['is_international']), None)
|
| 183 |
+
if gate:
|
| 184 |
+
action = dict(action_type='assign_gate', flight_id=landing_no_gate['flight_id'], gate_id=gate['gate_id'])
|
| 185 |
+
else:
|
| 186 |
+
action = dict(action_type='delay_flight', flight_id=landing_no_gate['flight_id'], delay_minutes=3)
|
| 187 |
+
else:
|
| 188 |
+
occ_rwy = next((r for r in state['runways'] if r['status']=='occupied' and r['available_at']<=state['clock']), None)
|
| 189 |
+
if occ_rwy:
|
| 190 |
+
cf = occ_rwy['current_flight']
|
| 191 |
+
action = dict(action_type='clear_runway', flight_id=cf or state['flights'][0]['flight_id'], runway_id=occ_rwy['runway_id'])
|
| 192 |
+
else:
|
| 193 |
+
waiting = [f for f in state['flights'] if f['status']=='scheduled']
|
| 194 |
+
free_rwy = next((r for r in state['runways'] if r['status']=='clear'), None)
|
| 195 |
+
if waiting and free_rwy:
|
| 196 |
+
f = sorted(waiting, key=lambda x:x['fuel_remaining_min'])[0]
|
| 197 |
+
action = dict(action_type='assign_runway', flight_id=f['flight_id'], runway_id=free_rwy['runway_id'])
|
| 198 |
+
elif waiting:
|
| 199 |
+
action = dict(action_type='delay_flight', flight_id=waiting[0]['flight_id'], delay_minutes=2)
|
| 200 |
+
else:
|
| 201 |
+
break
|
| 202 |
+
|
| 203 |
+
r, done = step(state, action)
|
| 204 |
+
total_reward += r
|
| 205 |
+
steps += 1
|
| 206 |
+
if done:
|
| 207 |
+
break
|
| 208 |
+
|
| 209 |
+
g = grade(state)
|
| 210 |
+
assert 0.0 <= g <= 1.0, f"Grade out of range: {g}"
|
| 211 |
+
print(f" grade: {g:.4f} | steps: {steps} | reward: {total_reward:.2f}")
|
| 212 |
+
return g
|
| 213 |
+
|
| 214 |
+
def main():
|
| 215 |
+
print("="*54)
|
| 216 |
+
print("Airport Scheduling Env — Logic Validation")
|
| 217 |
+
print("="*54)
|
| 218 |
+
tasks = ['single_runway_landing','multi_runway_gate_assignment','storm_disruption_recovery']
|
| 219 |
+
results = {}
|
| 220 |
+
for t in tasks:
|
| 221 |
+
print(f"\n[{t}]")
|
| 222 |
+
try:
|
| 223 |
+
g = run_task(t)
|
| 224 |
+
results[t] = g
|
| 225 |
+
print(f" ✅ PASS")
|
| 226 |
+
except Exception as e:
|
| 227 |
+
print(f" ❌ FAIL: {e}")
|
| 228 |
+
results[t] = -1.0
|
| 229 |
+
|
| 230 |
+
print(f"\n{'='*54}")
|
| 231 |
+
all_ok = all(v>=0 for v in results.values())
|
| 232 |
+
for t, g in results.items():
|
| 233 |
+
sym = "✅" if g>=0 else "❌"
|
| 234 |
+
print(f" {sym} {t:<44} {g:.4f}")
|
| 235 |
+
print(f"\n{'✅ All checks passed!' if all_ok else '❌ Some checks failed.'}")
|
| 236 |
+
sys.exit(0 if all_ok else 1)
|
| 237 |
+
|
| 238 |
+
if __name__ == "__main__":
|
| 239 |
+
main()
|