souvik0306 commited on
Commit
8ac0324
·
1 Parent(s): 30a7a75

weather and optimizer operational

Browse files
Files changed (4) hide show
  1. flight_distance.py +4 -0
  2. main.py +15 -5
  3. optimizer.py +48 -40
  4. weather.py +20 -19
flight_distance.py CHANGED
@@ -101,6 +101,10 @@ def calculate_distances(airport_identifiers):
101
  # aircraft_specs = get_aircraft_details(aircraft_type)
102
  # print(aircraft_specs)
103
 
 
 
 
 
104
  # fuel_burn_rate = aircraft_specs['Fuel_Consumption_kg/hr']
105
  # cruising_speed = aircraft_specs['Max_Fuel_Capacity_kg']
106
  # max_fuel_capacity = aircraft_specs['Speed_kmh']
 
101
  # aircraft_specs = get_aircraft_details(aircraft_type)
102
  # print(aircraft_specs)
103
 
104
+ # airport_list = ['SIN','CDG']
105
+ # print(get_airport_lat_long(airport_list))
106
+ # print(calculate_distances(airport_list))
107
+
108
  # fuel_burn_rate = aircraft_specs['Fuel_Consumption_kg/hr']
109
  # cruising_speed = aircraft_specs['Max_Fuel_Capacity_kg']
110
  # max_fuel_capacity = aircraft_specs['Speed_kmh']
main.py CHANGED
@@ -1,9 +1,9 @@
1
  import pandas as pd
2
  from flight_distance import *
3
- # from optimizer import *
4
  from weather import *
5
 
6
- airport_identifiers = ['SIN', 'LAX', 'JFK', 'CDG', 'LHR'] # Replace with actual identifiers
7
 
8
  #Get Airport Coordinates
9
  lat_long_dict = get_airport_lat_long(airport_identifiers)
@@ -14,15 +14,25 @@ trip_distance = calculate_distances(airport_identifiers)
14
  print("Distance b/w Airports: \n",trip_distance)
15
 
16
  #Get onroute weather
17
- weather = fetch_weather_for_all_routes(airport_identifiers,lat_long_dict)
18
- print("On Route weather: \n", weather)
 
19
 
20
  # # Ensure the graph is bidirectional (undirected)
21
  # for (a, b), dist in list(trip_distance.items()):
22
  # trip_distance[(b, a)] = dist
23
 
24
  # # Find the optimal route with the new cost metric
25
- # optimal_route, optimal_distance = find_optimal_route(airport_identifiers, trip_distance)
 
 
 
 
 
 
 
 
 
26
 
27
  # print("Optimal Route:", " -> ".join(optimal_route) + f" -> {optimal_route[0]}")
28
  # print("Total Adjusted Distance/Cost:", optimal_distance)
 
1
  import pandas as pd
2
  from flight_distance import *
3
+ from optimizer import *
4
  from weather import *
5
 
6
+ airport_identifiers = ['BOM', 'CCU', 'DEL'] # Replace with actual identifiers
7
 
8
  #Get Airport Coordinates
9
  lat_long_dict = get_airport_lat_long(airport_identifiers)
 
14
  print("Distance b/w Airports: \n",trip_distance)
15
 
16
  #Get onroute weather
17
+ raw_weather = fetch_weather_for_all_routes(airport_identifiers, lat_long_dict)
18
+ route_factors = extract_route_factors(raw_weather)
19
+ print("On Route weather: \n", raw_weather)
20
 
21
  # # Ensure the graph is bidirectional (undirected)
22
  # for (a, b), dist in list(trip_distance.items()):
23
  # trip_distance[(b, a)] = dist
24
 
25
  # # Find the optimal route with the new cost metric
26
+ # Ensure the graph is bidirectional (undirected)
27
+ for (a, b), dist in list(trip_distance.items()):
28
+ trip_distance[(b, a)] = dist
29
+
30
+ # Find the optimal route with the new cost metric
31
+ optimal_route, optimal_distance = find_optimal_route(airport_identifiers, trip_distance, route_factors)
32
+
33
+ # Display the optimal route and the total adjusted distance/cost
34
+ print("Optimal Route:", " -> ".join(optimal_route) + f" -> {optimal_route[0]}")
35
+ print("Total Adjusted Distance/Cost:", optimal_distance)
36
 
37
  # print("Optimal Route:", " -> ".join(optimal_route) + f" -> {optimal_route[0]}")
38
  # print("Total Adjusted Distance/Cost:", optimal_distance)
optimizer.py CHANGED
@@ -1,24 +1,27 @@
1
  import itertools
2
 
3
- # Define the distances between the airports
4
- distances = {
5
- ('SIN', 'LAX'): 14101.48,
6
- ('LAX', 'JFK'): 3974.20,
7
- ('JFK', 'CDG'): 5833.66,
8
- }
9
 
10
- # Define the factors for each route segment
11
- route_factors = {('SIN', 'LAX'): {'weather': 'clear sky', 'temperature': 27.18}, ('LAX', 'JFK'): {'weather': 'clear sky', 'temperature': 25.37}, ('JFK',
12
- 'CDG'): {'weather': 'clear sky', 'temperature': 21.18}}
13
 
14
- # Ensure the graph is bidirectional (undirected)
15
- for (a, b), dist in list(distances.items()):
16
- distances[(b, a)] = dist
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- for (a, b), factors in list(route_factors.items()):
19
- route_factors[(b, a)] = factors
20
-
21
- # Function to assign a risk factor based on weather
22
  def weather_risk(weather):
23
  risk_factors = {
24
  "clear sky": 0.1,
@@ -40,20 +43,30 @@ def temperature_impact(temperature):
40
  return 0.1 # Low impact in the ideal range
41
 
42
  # Calculate the adjusted cost for each route segment
43
- def calculate_adjusted_cost(segment, base_distance):
44
- if segment not in route_factors:
45
- segment = (segment[1], segment[0]) # Check the reversed segment
46
- weather = route_factors[segment]["weather"]
47
- temperature = route_factors[segment]["temperature"]
 
 
 
 
 
 
 
 
 
 
48
 
49
- weather_cost = weather_risk(weather) * 100 # Weight for weather impact
50
- temperature_cost = temperature_impact(temperature) * 50 # Weight for temperature impact
51
 
52
  total_cost = base_distance + weather_cost + temperature_cost
53
  return total_cost
54
 
55
  # Update the distance function to include additional factors
56
- def calculate_route_distance(route, distances):
57
  """Calculate the total cost for a given route, including additional factors."""
58
  total_distance = 0
59
  for i in range(len(route) - 1):
@@ -61,35 +74,30 @@ def calculate_route_distance(route, distances):
61
  if segment not in distances:
62
  segment = (route[i + 1], route[i])
63
  base_distance = distances[segment]
64
- total_distance += calculate_adjusted_cost(segment, base_distance)
 
65
  # Add distance to return to the starting point
66
  last_segment = (route[-1], route[0])
67
  if last_segment not in distances:
68
  last_segment = (route[0], route[-1])
69
  base_distance = distances[last_segment]
70
- total_distance += calculate_adjusted_cost(last_segment, base_distance)
71
 
72
  return total_distance
73
 
74
- def find_optimal_route(airports, distances):
75
  """Find the optimal route that covers all airports."""
76
  best_route = None
77
  min_distance = float('inf')
78
 
79
  # Generate all possible permutations of the route
80
  for route in itertools.permutations(airports):
81
- current_distance = calculate_route_distance(route, distances)
82
- if current_distance < min_distance:
83
- min_distance = current_distance
84
- best_route = route
 
 
 
85
 
86
  return best_route, min_distance
87
-
88
- # List of all airports
89
- airports = ['SIN', 'LAX', 'JFK', 'CDG']
90
-
91
- # Find the optimal route with the new cost metric
92
- optimal_route, optimal_distance = find_optimal_route(airports, distances)
93
-
94
- print("Optimal Route:", " -> ".join(optimal_route) + f" -> {optimal_route[0]}")
95
- print("Total Adjusted Distance/Cost:", optimal_distance)
 
1
  import itertools
2
 
3
+ def extract_route_factors(raw_weather):
4
+ """
5
+ Extracts route factors from raw weather data by breaking down routes into individual segments.
 
 
 
6
 
7
+ Parameters:
8
+ - raw_weather (dict): The raw weather data with routes and corresponding weather details.
 
9
 
10
+ Returns:
11
+ - dict: A dictionary with segments as keys (in tuple format) and a list of weather and temperature data.
12
+ """
13
+ route_factors = {}
14
+ for route, segments in raw_weather.items():
15
+ for segment in segments:
16
+ segment_key = tuple(segment['segment'].split(' -> '))
17
+ if segment_key not in route_factors:
18
+ route_factors[segment_key] = []
19
+ route_factors[segment_key].append({
20
+ 'weather': segment['weather'],
21
+ 'temperature': segment['temperature']
22
+ })
23
+ return route_factors
24
 
 
 
 
 
25
  def weather_risk(weather):
26
  risk_factors = {
27
  "clear sky": 0.1,
 
43
  return 0.1 # Low impact in the ideal range
44
 
45
  # Calculate the adjusted cost for each route segment
46
+ def calculate_adjusted_cost(segment, base_distance, route_factors):
47
+ # Handle both directions of the segment
48
+ if segment in route_factors:
49
+ factors = route_factors[segment]
50
+ elif (segment[1], segment[0]) in route_factors:
51
+ factors = route_factors[(segment[1], segment[0])]
52
+ else:
53
+ raise ValueError(f"Segment {segment} not found in route factors.")
54
+
55
+ # Aggregate weather and temperature data if there are multiple entries for the segment
56
+ weather_descriptions = [factor["weather"] for factor in factors]
57
+ temperatures = [factor["temperature"] for factor in factors]
58
+
59
+ most_common_weather = max(set(weather_descriptions), key=weather_descriptions.count)
60
+ avg_temperature = sum(temperatures) / len(temperatures)
61
 
62
+ weather_cost = weather_risk(most_common_weather) * 100 # Weight for weather impact
63
+ temperature_cost = temperature_impact(avg_temperature) * 50 # Weight for temperature impact
64
 
65
  total_cost = base_distance + weather_cost + temperature_cost
66
  return total_cost
67
 
68
  # Update the distance function to include additional factors
69
+ def calculate_route_distance(route, distances, route_factors):
70
  """Calculate the total cost for a given route, including additional factors."""
71
  total_distance = 0
72
  for i in range(len(route) - 1):
 
74
  if segment not in distances:
75
  segment = (route[i + 1], route[i])
76
  base_distance = distances[segment]
77
+ total_distance += calculate_adjusted_cost(segment, base_distance, route_factors)
78
+
79
  # Add distance to return to the starting point
80
  last_segment = (route[-1], route[0])
81
  if last_segment not in distances:
82
  last_segment = (route[0], route[-1])
83
  base_distance = distances[last_segment]
84
+ total_distance += calculate_adjusted_cost(last_segment, base_distance, route_factors)
85
 
86
  return total_distance
87
 
88
+ def find_optimal_route(airports, distances, route_factors):
89
  """Find the optimal route that covers all airports."""
90
  best_route = None
91
  min_distance = float('inf')
92
 
93
  # Generate all possible permutations of the route
94
  for route in itertools.permutations(airports):
95
+ try:
96
+ current_distance = calculate_route_distance(route, distances, route_factors)
97
+ if current_distance < min_distance:
98
+ min_distance = current_distance
99
+ best_route = route
100
+ except ValueError as e:
101
+ print(e) # Log the error to debug missing segments
102
 
103
  return best_route, min_distance
 
 
 
 
 
 
 
 
 
weather.py CHANGED
@@ -1,12 +1,13 @@
1
  import requests
2
  import itertools
3
  from geopy.distance import geodesic
 
4
 
5
  # Replace with your OpenWeather API key
6
  API_KEY = '9811dd1481209c64fba6cb2c90f27140'
7
 
8
  # Interpolation function to get intermediate points between airports
9
- def get_intermediate_points(start, end, num_points=4):
10
  points = []
11
  lat_step = (end[0] - start[0]) / (num_points + 1)
12
  lon_step = (end[1] - start[1]) / (num_points + 1)
@@ -18,6 +19,7 @@ def get_intermediate_points(start, end, num_points=4):
18
  return points
19
 
20
  # Fetch weather data for a given coordinate
 
21
  def fetch_weather(lat, lon):
22
  url = f'http://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API_KEY}&units=metric'
23
  response = requests.get(url)
@@ -65,26 +67,25 @@ def fetch_weather_for_all_routes(airport_identifiers, airports):
65
  "weather": most_common_weather,
66
  "temperature": round(avg_temperature, 2)
67
  })
68
-
69
  return route_factors
70
 
71
- # Example airport coordinates
72
- airports = {
73
- 'SIN': (1.3644, 103.9915), # Singapore Changi Airport
74
- 'LAX': (33.9416, -118.4085), # Los Angeles International Airport
75
- 'JFK': (40.6413, -73.7781), # John F. Kennedy International Airport
76
- 'CDG': (49.0097, 2.5479), # Charles de Gaulle Airport
77
- 'LHR': (51.4700, -0.4543) # London Heathrow Airport
78
- }
79
 
80
- airport_identifiers = ['SIN', 'LAX', 'JFK', 'CDG', 'LHR'] # Replace with actual identifiers
81
 
82
- # Fetch the weather along all possible routes
83
- route_weather = fetch_weather_for_all_routes(airport_identifiers, airports)
84
 
85
- # Display the weather data for each route
86
- for route, factors in route_weather.items():
87
- print(f"Route: {route}")
88
- for factor in factors:
89
- print(f" Segment: {factor['segment']}, Weather: {factor['weather']}, Temperature: {factor['temperature']} °C")
90
- print()
 
1
  import requests
2
  import itertools
3
  from geopy.distance import geodesic
4
+ from functools import lru_cache
5
 
6
  # Replace with your OpenWeather API key
7
  API_KEY = '9811dd1481209c64fba6cb2c90f27140'
8
 
9
  # Interpolation function to get intermediate points between airports
10
+ def get_intermediate_points(start, end, num_points=2):
11
  points = []
12
  lat_step = (end[0] - start[0]) / (num_points + 1)
13
  lon_step = (end[1] - start[1]) / (num_points + 1)
 
19
  return points
20
 
21
  # Fetch weather data for a given coordinate
22
+ @lru_cache(maxsize=128)
23
  def fetch_weather(lat, lon):
24
  url = f'http://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API_KEY}&units=metric'
25
  response = requests.get(url)
 
67
  "weather": most_common_weather,
68
  "temperature": round(avg_temperature, 2)
69
  })
 
70
  return route_factors
71
 
72
+ # # Example airport coordinates
73
+ # airports = {
74
+ # 'SIN': (1.3644, 103.9915), # Singapore Changi Airport
75
+ # 'LAX': (33.9416, -118.4085), # Los Angeles International Airport
76
+ # 'JFK': (40.6413, -73.7781), # John F. Kennedy International Airport
77
+ # 'CDG': (49.0097, 2.5479), # Charles de Gaulle Airport
78
+ # 'LHR': (51.4700, -0.4543) # London Heathrow Airport
79
+ # }
80
 
81
+ # airport_identifiers = ['SIN', 'LAX', 'JFK', 'CDG', 'LHR'] # Replace with actual identifiers
82
 
83
+ # # Fetch the weather along all possible routes
84
+ # route_weather = fetch_weather_for_all_routes(airport_identifiers, airports)
85
 
86
+ # # Display the weather data for each route
87
+ # for route, factors in route_weather.items():
88
+ # print(f"Route: {route}")
89
+ # for factor in factors:
90
+ # print(f" Segment: {factor['segment']}, Weather: {factor['weather']}, Temperature: {factor['temperature']} °C")
91
+ # print()