Collision Detection Function
Overview
The detect_collisions function takes a list of aircraft dictionaries as input and returns a list of tuples, where each tuple contains the IDs of two aircraft that will come within 1 km of each other at any time within the next 30 minutes.
Code
import numpy as np
from typing import List, Dict, Tuple
def detect_collisions(aircraft: List[Dict]) -> List[Tuple[str, str]]:
"""
Detects all aircraft pairs that will come within 1 km of each other at any time within the next 30 minutes.
Args:
aircraft (List[Dict]): A list of aircraft dictionaries, each containing 'id', 'position', and 'velocity' keys.
Returns:
List[Tuple[str, str]]: A list of tuples, where each tuple contains the IDs of two aircraft that will collide.
"""
collisions = []
for i in range(len(aircraft)):
for j in range(i + 1, len(aircraft)):
# Calculate the relative position and velocity of the two aircraft
rel_pos = np.array(aircraft[j]['position']) - np.array(aircraft[i]['position'])
rel_vel = np.array(aircraft[j]['velocity']) - np.array(aircraft[i]['velocity'])
# Calculate the time of closest approach
t_ca = -np.dot(rel_pos, rel_vel) / np.dot(rel_vel, rel_vel) if np.dot(rel_vel, rel_vel) != 0 else 0
# Check if the time of closest approach is within the 30-minute window
if 0 <= t_ca <= 30:
# Calculate the distance at the time of closest approach
dist_ca = np.linalg.norm(rel_pos + t_ca * rel_vel)
# Check if the distance is within 1 km
if dist_ca <= 1:
collisions.append((aircraft[i]['id'], aircraft[j]['id']))
return collisions
Explanation
- The function iterates over all pairs of aircraft using nested loops.
- For each pair, it calculates the relative position and velocity of the two aircraft.
- It then calculates the time of closest approach using the dot product of the relative position and velocity.
- If the time of closest approach is within the 30-minute window, it calculates the distance at that time using the Euclidean norm.
- If the distance is within 1 km, it adds the IDs of the two aircraft to the
collisions list.
- Finally, it returns the list of collisions.
Example Use Case
aircraft = [
{'id': 'A', 'position': [0, 0, 0], 'velocity': [1, 0, 0]},
{'id': 'B', 'position': [10, 0, 0], 'velocity': [-1, 0, 0]},
{'id': 'C', 'position': [0, 10, 0], 'velocity': [0, 0, 0]}
]
collisions = detect_collisions(aircraft)
print(collisions) # Output: [('A', 'B')]
In this example, aircraft A and B will collide within the 30-minute window, while aircraft C will not collide with either A or B.