Spaces:
Sleeping
Sleeping
Update route_optimizer/green_route_optimizer.py
Browse files
route_optimizer/green_route_optimizer.py
CHANGED
|
@@ -1,55 +1,53 @@
|
|
| 1 |
-
# In: src/route_optimizer/green_route_optimizer.py
|
| 2 |
-
|
| 3 |
-
from geopy.geocoders import Nominatim
|
| 4 |
import math
|
|
|
|
| 5 |
|
| 6 |
class GreenRouteOptimizer:
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
self.geolocator = Nominatim(user_agent=user_agent)
|
| 9 |
-
#
|
| 10 |
-
self.emission_factors = {"road": 0.21, "rail": 0.041, "ship": 0.014}
|
| 11 |
-
|
| 12 |
-
self.
|
| 13 |
-
# --- ADDED: Carbon tax rate for cost calculation ($ per tonne) ---
|
| 14 |
-
self.carbon_tax_rate = 50.0
|
| 15 |
|
| 16 |
def geocode(self, place_name):
|
|
|
|
| 17 |
try:
|
| 18 |
location = self.geolocator.geocode(place_name, timeout=10)
|
| 19 |
-
|
|
|
|
| 20 |
except Exception:
|
| 21 |
return None
|
|
|
|
| 22 |
|
| 23 |
-
def
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
dlat = math.radians(lat2 - lat1)
|
| 29 |
-
dlon = math.radians(lon2 - lon1)
|
| 30 |
-
a = math.sin(dlat / 2)**2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2)**2
|
| 31 |
-
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
|
| 32 |
-
distance_km = R * c
|
| 33 |
-
|
| 34 |
-
co2_emissions_kg = distance_km * self.emission_factors[mode] * weight_tonnes
|
| 35 |
-
|
| 36 |
-
# --- ADDED: Calculation for new metrics ---
|
| 37 |
-
travel_time_hours = distance_km / self.avg_speeds[mode]
|
| 38 |
-
carbon_tax_cost = (co2_emissions_kg / 1000) * self.carbon_tax_rate
|
| 39 |
|
| 40 |
return {
|
| 41 |
"transport_mode": mode,
|
| 42 |
-
"co2_emissions_kg":
|
| 43 |
"estimated_travel_time_hours": travel_time_hours,
|
| 44 |
-
"carbon_tax_cost_usd":
|
| 45 |
}
|
| 46 |
|
| 47 |
def recommend_green_routes(self, start_place, end_place, weight_tonnes):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
if not start_place or not start_place.strip():
|
| 49 |
-
return {"error": "
|
| 50 |
if not end_place or not end_place.strip():
|
| 51 |
-
return {"error": "
|
| 52 |
|
|
|
|
| 53 |
start_coords = self.geocode(start_place)
|
| 54 |
if start_coords is None:
|
| 55 |
return {"error": f"Could not find location: '{start_place}'"}
|
|
@@ -58,26 +56,38 @@ class GreenRouteOptimizer:
|
|
| 58 |
if end_coords is None:
|
| 59 |
return {"error": f"Could not find location: '{end_place}'"}
|
| 60 |
|
| 61 |
-
# ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
all_routes = []
|
| 63 |
for mode in self.emission_factors:
|
| 64 |
-
|
| 65 |
-
all_routes.append(
|
| 66 |
|
|
|
|
| 67 |
if not all_routes:
|
| 68 |
return {"error": "Could not calculate any routes."}
|
| 69 |
|
| 70 |
-
#
|
| 71 |
-
|
| 72 |
|
| 73 |
-
# Calculate emission reduction vs the worst option
|
| 74 |
-
worst_emission = all_routes[-1]['co2_emissions_kg'] if all_routes else 0
|
| 75 |
for route in all_routes:
|
| 76 |
if worst_emission > 0:
|
| 77 |
reduction = (worst_emission - route['co2_emissions_kg']) / worst_emission * 100
|
| 78 |
route['emission_reduction_percent'] = reduction
|
| 79 |
else:
|
| 80 |
route['emission_reduction_percent'] = 0
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
-
# ---
|
| 83 |
-
return {"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import math
|
| 2 |
+
from geopy.geocoders import Nominatim
|
| 3 |
|
| 4 |
class GreenRouteOptimizer:
|
| 5 |
+
"""
|
| 6 |
+
Calculates and compares green routes for shipments, providing data on emissions,
|
| 7 |
+
travel time, and costs, formatted for the GreenPath Streamlit app.
|
| 8 |
+
"""
|
| 9 |
+
def __init__(self, user_agent="green_path_app"):
|
| 10 |
self.geolocator = Nominatim(user_agent=user_agent)
|
| 11 |
+
# Constants used for calculations
|
| 12 |
+
self.emission_factors = {"road": 0.21, "rail": 0.041, "ship": 0.014} # kg CO₂/tonne-km
|
| 13 |
+
self.avg_speeds_kmh = {"road": 80, "rail": 100, "ship": 30} # km/h
|
| 14 |
+
self.carbon_tax_rate_usd = 50.0 # $ per tonne of CO₂
|
|
|
|
|
|
|
| 15 |
|
| 16 |
def geocode(self, place_name):
|
| 17 |
+
"""Geocodes a place name, returning (lat, lon) or None on failure."""
|
| 18 |
try:
|
| 19 |
location = self.geolocator.geocode(place_name, timeout=10)
|
| 20 |
+
if location:
|
| 21 |
+
return (location.latitude, location.longitude)
|
| 22 |
except Exception:
|
| 23 |
return None
|
| 24 |
+
return None
|
| 25 |
|
| 26 |
+
def calculate_route_metrics(self, distance_km, mode, weight_tonnes):
|
| 27 |
+
"""Calculates all metrics for a single route."""
|
| 28 |
+
emissions_kg = distance_km * self.emission_factors[mode] * weight_tonnes
|
| 29 |
+
travel_time_hours = distance_km / self.avg_speeds_kmh[mode]
|
| 30 |
+
carbon_tax_usd = (emissions_kg / 1000) * self.carbon_tax_rate_usd
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
return {
|
| 33 |
"transport_mode": mode,
|
| 34 |
+
"co2_emissions_kg": emissions_kg,
|
| 35 |
"estimated_travel_time_hours": travel_time_hours,
|
| 36 |
+
"carbon_tax_cost_usd": carbon_tax_usd,
|
| 37 |
}
|
| 38 |
|
| 39 |
def recommend_green_routes(self, start_place, end_place, weight_tonnes):
|
| 40 |
+
"""
|
| 41 |
+
The main method that finds and processes route recommendations.
|
| 42 |
+
Returns a dictionary compatible with the Streamlit frontend.
|
| 43 |
+
"""
|
| 44 |
+
# --- 1. Input Validation ---
|
| 45 |
if not start_place or not start_place.strip():
|
| 46 |
+
return {"error": "Origin location cannot be empty."}
|
| 47 |
if not end_place or not end_place.strip():
|
| 48 |
+
return {"error": "Destination location cannot be empty."}
|
| 49 |
|
| 50 |
+
# --- 2. Geocoding ---
|
| 51 |
start_coords = self.geocode(start_place)
|
| 52 |
if start_coords is None:
|
| 53 |
return {"error": f"Could not find location: '{start_place}'"}
|
|
|
|
| 56 |
if end_coords is None:
|
| 57 |
return {"error": f"Could not find location: '{end_place}'"}
|
| 58 |
|
| 59 |
+
# --- 3. Calculate Distance (Haversine Formula) ---
|
| 60 |
+
R = 6371 # Radius of Earth in km
|
| 61 |
+
lat1, lon1 = start_coords
|
| 62 |
+
lat2, lon2 = end_coords
|
| 63 |
+
dlat = math.radians(lat2 - lat1)
|
| 64 |
+
dlon = math.radians(lon2 - lon1)
|
| 65 |
+
a = math.sin(dlat / 2)**2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2)**2
|
| 66 |
+
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
|
| 67 |
+
distance_km = R * c
|
| 68 |
+
|
| 69 |
+
# --- 4. Calculate Metrics for All Modes ---
|
| 70 |
all_routes = []
|
| 71 |
for mode in self.emission_factors:
|
| 72 |
+
route_metrics = self.calculate_route_metrics(distance_km, mode, weight_tonnes)
|
| 73 |
+
all_routes.append(route_metrics)
|
| 74 |
|
| 75 |
+
# --- 5. Post-Processing for Comparison Metrics ---
|
| 76 |
if not all_routes:
|
| 77 |
return {"error": "Could not calculate any routes."}
|
| 78 |
|
| 79 |
+
# Find the worst emission value to calculate savings against it
|
| 80 |
+
worst_emission = max(route['co2_emissions_kg'] for route in all_routes)
|
| 81 |
|
|
|
|
|
|
|
| 82 |
for route in all_routes:
|
| 83 |
if worst_emission > 0:
|
| 84 |
reduction = (worst_emission - route['co2_emissions_kg']) / worst_emission * 100
|
| 85 |
route['emission_reduction_percent'] = reduction
|
| 86 |
else:
|
| 87 |
route['emission_reduction_percent'] = 0
|
| 88 |
+
|
| 89 |
+
# Sort routes by emissions (best first)
|
| 90 |
+
all_routes.sort(key=lambda x: x['co2_emissions_kg'])
|
| 91 |
|
| 92 |
+
# --- 6. Return Data in the Exact Format the App Expects ---
|
| 93 |
+
return {"recommendations": all_routes}
|