Spaces:
Build error
Build error
Update route_optimizer/green_route_optimizer.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354552 unmodified lines5859606162636465666768697071727374757677787980818283# In: src/route_optimizer/green_route_optimizer.pyfrom geopy.geocoders import Nominatimimport mathclass GreenRouteOptimizer:def __init__(self, user_agent="green_route_app"):self.geolocator = Nominatim(user_agent=user_agent)# kg CO₂ per tonne-kmself.emission_factors = {"road": 0.21, "rail": 0.041, "ship": 0.014}# --- ADDED: Average speeds for time calculation (km/h) ---self.avg_speeds = {"road": 80, "rail": 100, "ship": 30}# --- ADDED: Carbon tax rate for cost calculation ($ per tonne) ---self.carbon_tax_rate = 50.0def geocode(self, place_name):try:location = self.geolocator.geocode(place_name, timeout=10)return (location.latitude, location.longitude) if location else Noneexcept Exception:return Nonedef calculate_route_data(self, start_coords, end_coords, mode, weight_tonnes):R = 6371 # Earth radius in kmlat1, lon1 = start_coordslat2, lon2 = end_coordsdlat = math.radians(lat2 - lat1)dlon = math.radians(lon2 - lon1)a = math.sin(dlat / 2)**2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2)**2c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))distance_km = R * cco2_emissions_kg = distance_km * self.emission_factors[mode] * weight_tonnes# --- ADDED: Calculation for new metrics ---travel_time_hours = distance_km / self.avg_speeds[mode]carbon_tax_cost = (co2_emissions_kg / 1000) * self.carbon_tax_ratereturn {"transport_mode": mode,"co2_emissions_kg": co2_emissions_kg,"estimated_travel_time_hours": travel_time_hours,"carbon_tax_cost_usd": carbon_tax_cost,}def recommend_green_routes(self, start_place, end_place, weight_tonnes):if not start_place or not start_place.strip():return {"error": "Start place cannot be empty."}if not end_place or not end_place.strip():return {"error": "End place cannot be empty."}start_coords = self.geocode(start_place)if start_coords is None:return {"error": f"Could not find location: '{start_place}'"}2 unmodified linesif end_coords is None:return {"error": f"Could not find location: '{end_place}'"}# --- ADDED: Logic to calculate all routes and then add reduction stats ---all_routes = []for mode in self.emission_factors:route_info = self.calculate_route_data(start_coords, end_coords, mode, weight_tonnes)all_routes.append(route_info)if not all_routes:return {"error": "Could not calculate any routes."}# Sort by emissions to find the best routeall_routes.sort(key=lambda x: x['co2_emissions_kg'])# Calculate emission reduction vs the worst optionworst_emission = all_routes[-1]['co2_emissions_kg'] if all_routes else 0for route in all_routes:if worst_emission > 0:reduction = (worst_emission - route['co2_emissions_kg']) / worst_emission * 100route['emission_reduction_percent'] = reductionelse:route['emission_reduction_percent'] = 0# --- CHANGED: Return a structured success dictionary ---return {"success": True, "recommendations": all_routes}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152532 unmodified lines5657585960616263646566676869707172737475767778798081828384858687888990919293import mathfrom geopy.geocoders import Nominatimclass GreenRouteOptimizer:"""Calculates and compares green routes for shipments, providing data on emissions,travel time, and costs, formatted for the GreenPath Streamlit app."""def __init__(self, user_agent="green_path_app"):self.geolocator = Nominatim(user_agent=user_agent)# Constants used for calculationsself.emission_factors = {"road": 0.21, "rail": 0.041, "ship": 0.014} # kg CO₂/tonne-kmself.avg_speeds_kmh = {"road": 80, "rail": 100, "ship": 30} # km/hself.carbon_tax_rate_usd = 50.0 # $ per tonne of CO₂def geocode(self, place_name):"""Geocodes a place name, returning (lat, lon) or None on failure."""try:location = self.geolocator.geocode(place_name, timeout=10)if location:return (location.latitude, location.longitude)except Exception:return Nonereturn Nonedef calculate_route_metrics(self, distance_km, mode, weight_tonnes):"""Calculates all metrics for a single route."""emissions_kg = distance_km * self.emission_factors[mode] * weight_tonnestravel_time_hours = distance_km / self.avg_speeds_kmh[mode]carbon_tax_usd = (emissions_kg / 1000) * self.carbon_tax_rate_usdreturn {"transport_mode": mode,"co2_emissions_kg": emissions_kg,"estimated_travel_time_hours": travel_time_hours,"carbon_tax_cost_usd": carbon_tax_usd,}def recommend_green_routes(self, start_place, end_place, weight_tonnes):"""The main method that finds and processes route recommendations.Returns a dictionary compatible with the Streamlit frontend."""# --- 1. Input Validation ---if not start_place or not start_place.strip():return {"error": "Origin location cannot be empty."}if not end_place or not end_place.strip():return {"error": "Destination location cannot be empty."}# --- 2. Geocoding ---start_coords = self.geocode(start_place)if start_coords is None:return {"error": f"Could not find location: '{start_place}'"}2 unmodified linesif end_coords is None:return {"error": f"Could not find location: '{end_place}'"}# --- 3. Calculate Distance (Haversine Formula) ---R = 6371 # Radius of Earth in kmlat1, lon1 = start_coordslat2, lon2 = end_coordsdlat = math.radians(lat2 - lat1)dlon = math.radians(lon2 - lon1)a = math.sin(dlat / 2)**2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2)**2c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))distance_km = R * c# --- 4. Calculate Metrics for All Modes ---all_routes = []for mode in self.emission_factors:route_metrics = self.calculate_route_metrics(distance_km, mode, weight_tonnes)all_routes.append(route_metrics)# --- 5. Post-Processing for Comparison Metrics ---if not all_routes:return {"error": "Could not calculate any routes."}# Find the worst emission value to calculate savings against itworst_emission = max(route['co2_emissions_kg'] for route in all_routes)for route in all_routes:if worst_emission > 0:reduction = (worst_emission - route['co2_emissions_kg']) / worst_emission * 100route['emission_reduction_percent'] = reductionelse:route['emission_reduction_percent'] = 0# Sort routes by emissions (best first)all_routes.sort(key=lambda x: x['co2_emissions_kg'])# --- 6. Return Data in the Exact Format the App Expects ---return {"recommendations": all_routes}
route_optimizer/green_route_optimizer.py+50-40