From 87aaba64b225c0ac30cedc2d75ad85068db6b9ca Mon Sep 17 00:00:00 2001 From: Edward Betts Date: Sat, 6 Apr 2024 09:25:32 +0200 Subject: [PATCH] Calculate flight distances --- agenda/travel.py | 29 +++++++++++++++++++++++++---- agenda/trip.py | 4 ++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/agenda/travel.py b/agenda/travel.py index 6e3d2c9..9299408 100644 --- a/agenda/travel.py +++ b/agenda/travel.py @@ -14,6 +14,31 @@ Leg = dict[str, str] TravelList = list[dict[str, typing.Any]] +RouteDistances = dict[tuple[str, str], float] + + +def coords(airport: StrDict) -> tuple[float, float]: + """Longitude / Latitude as coordinate tuples.""" + # return (airport["longitude"], airport["latitude"]) + return (airport["latitude"], airport["longitude"]) + + +def flight_distance(f: StrDict) -> float: + """Distance of flight.""" + return float(geodesic(coords(f["from_airport"]), coords(f["to_airport"])).km) + + +def route_distances_as_json(route_distances: RouteDistances) -> str: + """Format route distances as JSON string.""" + return ( + "[\n" + + ",\n".join( + " " + json.dumps([s1, s2, dist]) + for (s1, s2), dist in route_distances.items() + ) + + "\n]" + ) + def parse_yaml(travel_type: str, data_dir: str) -> TravelList: """Parse flights YAML and return list of travel.""" @@ -67,9 +92,6 @@ def all_events(data_dir: str) -> list[Event]: return get_trains(data_dir) + get_flights(data_dir) -RouteDistances = dict[tuple[str, str], float] - - def train_leg_distance(geojson_data: StrDict) -> float: """Calculate the total length of a LineString in kilometers from GeoJSON data.""" # Extract coordinates @@ -81,7 +103,6 @@ def train_leg_distance(geojson_data: StrDict) -> float: else: first_object["type"] == "MultiLineString" coord_list = first_object["coordinates"] - # pprint(coordinates) total_length_km = 0.0 diff --git a/agenda/trip.py b/agenda/trip.py index d0767e6..fad4c4b 100644 --- a/agenda/trip.py +++ b/agenda/trip.py @@ -1,3 +1,5 @@ +"""Trips.""" + import os from datetime import date, datetime, time from zoneinfo import ZoneInfo @@ -73,6 +75,8 @@ def load_flights(data_dir: str) -> list[StrDict]: flight["to_airport"] = airports[flight["to"]] if "airline" in flight: flight["airline_name"] = airlines.get(flight["airline"], "[unknown]") + + flight["distance"] = travel.flight_distance(flight) return flights