Spaces:
Sleeping
Sleeping
File size: 11,966 Bytes
43bbf9a 73dbcfd 43bbf9a 73dbcfd 43bbf9a 73dbcfd d6b41a8 43bbf9a d6b41a8 43bbf9a 149cb7a 43bbf9a 149cb7a 43bbf9a 80b0537 43bbf9a 149cb7a 43bbf9a 149cb7a 43bbf9a 80b0537 43bbf9a 80b0537 43bbf9a d6b41a8 43bbf9a 80b0537 43bbf9a 149cb7a 43bbf9a d6b41a8 43bbf9a d6b41a8 43bbf9a 38a1e2b 43bbf9a d6b41a8 80b0537 43bbf9a d6b41a8 43bbf9a d6b41a8 43bbf9a 80b0537 43bbf9a d6b41a8 43bbf9a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | """Operational simulator and reward shaping for ATC optimization."""
from __future__ import annotations
from collections import defaultdict
from dataclasses import dataclass
from statistics import pstdev
from typing import Dict, Iterable, List, Tuple
# Import models with automatic relative/absolute fallback
try:
from .models import (
FlightRecord,
PriorityClass,
RunwaySpec,
SlotAssignment,
TaskDefinition,
TaskMetrics,
)
from .constants import (
SEPARATION_BY_WAKE,
SCORE_WEIGHTS,
METRIC_PRECISION,
FUEL_PRECISION,
AIRLINE_DELAY_PRECISION,
MAX_DIAGNOSTICS,
MAX_RECOMMENDATIONS,
)
except ImportError:
from models import (
FlightRecord,
PriorityClass,
RunwaySpec,
SlotAssignment,
TaskDefinition,
TaskMetrics,
)
from constants import (
SEPARATION_BY_WAKE,
SCORE_WEIGHTS,
METRIC_PRECISION,
FUEL_PRECISION,
AIRLINE_DELAY_PRECISION,
MAX_DIAGNOSTICS,
MAX_RECOMMENDATIONS,
)
# Build priority delay tolerance dynamically from models
PRIORITY_DELAY_TOLERANCE: Dict[PriorityClass, int] = {
PriorityClass.NORMAL: 35,
PriorityClass.CONNECTION: 20,
PriorityClass.MEDICAL: 10,
PriorityClass.EMERGENCY: 5,
}
@dataclass
class SimulationOutcome:
"""Full simulator output used by the environment and graders."""
metrics: TaskMetrics
diagnostics: List[str]
recommendations: List[str]
normalized_score: float
def empty_metrics() -> TaskMetrics:
"""Return a zeroed metric object."""
return TaskMetrics()
def _capacity_spacing(runway: RunwaySpec) -> int:
base_gap = max(2, round(60 / runway.hourly_capacity))
return max(2, round(base_gap * runway.weather_penalty))
def _delay_for(flight: FlightRecord, assigned_minute: int) -> int:
return abs(assigned_minute - flight.scheduled_minute)
def simulate_plan(task: TaskDefinition, proposal: Iterable[SlotAssignment]) -> SimulationOutcome:
"""Evaluate a candidate runway plan for a task."""
flights_by_id = {flight.flight_id: flight for flight in task.flights}
runways_by_id = {runway.runway_id: runway for runway in task.runways}
assignments = list(proposal)
diagnostics: List[str] = []
recommendations: List[str] = []
unknown_assignments = 0
invalid_assignments = 0
assignment_map: Dict[str, SlotAssignment] = {}
duplicate_assignments = max(0, len(assignments) - len({item.flight_id for item in assignments}))
for assignment in assignments:
if assignment.flight_id in assignment_map:
diagnostics.append(
f"{assignment.flight_id} appears more than once; only the last assignment is used."
)
assignment_map[assignment.flight_id] = assignment
if duplicate_assignments:
invalid_assignments += duplicate_assignments
scheduled_by_runway: Dict[str, List[Tuple[int, SlotAssignment, FlightRecord]]] = defaultdict(list)
delays: Dict[str, int] = {}
per_airline_delays: Dict[str, List[int]] = defaultdict(list)
fuel_burn = 0.0
priority_violations = 0
emergency_violations = 0
medical_violations = 0
connection_violations = 0
capacity_violations = 0
for assignment in assignment_map.values():
flight = flights_by_id.get(assignment.flight_id)
if flight is None:
unknown_assignments += 1
diagnostics.append(f"Unknown flight id {assignment.flight_id} in proposal.")
continue
if assignment.runway not in flight.allowed_runways:
invalid_assignments += 1
diagnostics.append(
f"{flight.flight_id} cannot use runway {assignment.runway}; allowed runways are {', '.join(flight.allowed_runways)}."
)
continue
if assignment.runway not in runways_by_id:
invalid_assignments += 1
diagnostics.append(f"Runway {assignment.runway} is not available in this task.")
continue
runway = runways_by_id[assignment.runway]
if flight.operation not in runway.allowed_operations:
invalid_assignments += 1
diagnostics.append(
f"Runway {assignment.runway} cannot handle {flight.operation.value} operations for {flight.flight_id}."
)
continue
if assignment.assigned_minute < flight.earliest_minute or assignment.assigned_minute > flight.latest_minute:
invalid_assignments += 1
diagnostics.append(
f"{flight.flight_id} is assigned outside its feasible window [{flight.earliest_minute}, {flight.latest_minute}]."
)
continue
delay = _delay_for(flight, assignment.assigned_minute)
if assignment.hold_minutes > 0 and abs(assignment.hold_minutes - delay) > 5:
diagnostics.append(
f"{flight.flight_id} declares hold_minutes={assignment.hold_minutes}, but the actual delay is {delay}."
)
delays[flight.flight_id] = delay
per_airline_delays[flight.airline].append(delay)
fuel_burn += delay * flight.fuel_burn_per_minute
scheduled_by_runway[assignment.runway].append((assignment.assigned_minute, assignment, flight))
tolerance = PRIORITY_DELAY_TOLERANCE[flight.priority]
if delay > tolerance:
priority_violations += 1
if flight.priority == PriorityClass.EMERGENCY:
emergency_violations += 1
elif flight.priority == PriorityClass.MEDICAL:
medical_violations += 1
elif flight.priority == PriorityClass.CONNECTION:
connection_violations += 1
diagnostics.append(
f"{flight.flight_id} exceeds the {flight.priority.value} delay tolerance of {tolerance} minutes."
)
missing_assignments = max(0, len(task.flights) - len(delays))
for flight in task.flights:
if flight.flight_id not in delays:
diagnostics.append(f"{flight.flight_id} has no valid runway assignment.")
conflict_count = 0
for runway_id, runway_items in scheduled_by_runway.items():
runway_spec = runways_by_id[runway_id]
runway_items.sort(key=lambda item: item[0])
required_gap_floor = _capacity_spacing(runway_spec)
for idx in range(1, len(runway_items)):
prev_time, _, prev_flight = runway_items[idx - 1]
curr_time, _, curr_flight = runway_items[idx]
wake_gap = SEPARATION_BY_WAKE[(prev_flight.wake_class.value, curr_flight.wake_class.value)]
required_gap = max(required_gap_floor, wake_gap)
actual_gap = curr_time - prev_time
if actual_gap < required_gap:
conflict_count += 1
capacity_violations += 1
diagnostics.append(
f"Runway {runway_id} has {prev_flight.flight_id}->{curr_flight.flight_id} spaced {actual_gap} minutes apart; needs {required_gap}."
)
total_delay = sum(delays.values())
max_delay = max(delays.values(), default=0)
completeness = max(
0.0,
min(
1.0,
len(delays) / max(1, len(task.flights)),
),
)
conflict_free_ratio = max(
0.0,
1.0 - (conflict_count / max(1, len(task.flights) - 1)),
)
priority_handling = max(
0.0,
1.0 - (priority_violations / max(1, sum(1 for flight in task.flights if flight.priority != PriorityClass.NORMAL))),
)
delay_efficiency = max(0.0, 1.0 - (total_delay / task.delay_budget))
fuel_efficiency = max(0.0, 1.0 - (fuel_burn / task.fuel_budget))
airline_averages = {
airline: round(sum(values) / len(values), AIRLINE_DELAY_PRECISION)
for airline, values in per_airline_delays.items()
if values
}
spread = pstdev(list(airline_averages.values())) if len(airline_averages) > 1 else 0.0
fairness = max(0.0, 1.0 - (spread / task.fairness_tolerance))
# Connection impact: risk-weighted delay score for CONNECTION flights
connection_flights = [
f for f in task.flights if f.priority == PriorityClass.CONNECTION and f.connection_risk > 0
]
if connection_flights:
# Budget: each connection flight is expected to tolerate up to its delay tolerance
weighted_actual = sum(
delays.get(f.flight_id, PRIORITY_DELAY_TOLERANCE[PriorityClass.CONNECTION]) * f.connection_risk
for f in connection_flights
)
weighted_budget = sum(
PRIORITY_DELAY_TOLERANCE[PriorityClass.CONNECTION] * f.connection_risk
for f in connection_flights
)
connection_impact_score = max(0.0, 1.0 - weighted_actual / max(1.0, weighted_budget))
else:
connection_impact_score = 1.0
if completeness < 1.0:
recommendations.append("Cover every flight in the scenario before refining the sequence.")
if conflict_count > 0:
recommendations.append("Increase spacing on the affected runway or move some flights to a parallel runway.")
if duplicate_assignments > 0:
recommendations.append("Avoid duplicate flight entries; submit one definitive assignment per flight.")
if priority_violations > 0:
recommendations.append("Pull medical, emergency, and connection-sensitive flights closer to the front of the sequence.")
if fairness < 0.7:
recommendations.append("Redistribute delay so one airline is not absorbing most of the disruption.")
if fuel_efficiency < 0.7:
recommendations.append("Reduce airborne or taxi delay on the highest-burn arrivals and heavy aircraft.")
if not recommendations:
recommendations.append("The plan is operationally strong; minor gains remain in passenger delay reduction.")
# Calculate normalized score using defined weights
normalized_score = (
SCORE_WEIGHTS["completeness"] * completeness
+ SCORE_WEIGHTS["conflict_free"] * conflict_free_ratio
+ SCORE_WEIGHTS["priority"] * priority_handling
+ SCORE_WEIGHTS["delay"] * delay_efficiency
+ SCORE_WEIGHTS["fairness"] * fairness
+ SCORE_WEIGHTS["fuel"] * fuel_efficiency
)
normalized_score *= completeness
if conflict_count > 0:
normalized_score *= conflict_free_ratio
normalized_score = max(0.01, min(0.99, normalized_score))
metrics = TaskMetrics(
schedule_completeness=round(completeness, METRIC_PRECISION),
conflict_free_ratio=round(conflict_free_ratio, METRIC_PRECISION),
priority_handling=round(priority_handling, METRIC_PRECISION),
delay_efficiency=round(delay_efficiency, METRIC_PRECISION),
fairness=round(fairness, METRIC_PRECISION),
fuel_efficiency=round(fuel_efficiency, METRIC_PRECISION),
connection_impact_score=round(connection_impact_score, METRIC_PRECISION),
agent_judgment=0.0,
overall_score=round(normalized_score, METRIC_PRECISION),
total_delay_minutes=total_delay,
max_delay_minutes=max_delay,
estimated_fuel_burn=round(fuel_burn, FUEL_PRECISION),
conflict_count=conflict_count,
capacity_violations=capacity_violations,
priority_violations=priority_violations,
emergency_violations=emergency_violations,
medical_violations=medical_violations,
connection_violations=connection_violations,
missing_assignments=missing_assignments,
invalid_assignments=invalid_assignments + unknown_assignments,
per_airline_average_delay=airline_averages,
)
return SimulationOutcome(
metrics=metrics,
diagnostics=diagnostics[:MAX_DIAGNOSTICS],
recommendations=recommendations[:MAX_RECOMMENDATIONS],
normalized_score=normalized_score,
)
|