compute_trips.py (2706B)
1 #!/usr/bin/env python3 2 import csv 3 import sys 4 import math 5 from geopy.geocoders import Nominatim 6 from functools import cache 7 8 # Define carbon emissions data for each mode of transportation (in gCO2e per passenger-kilometer) 9 emissions_data = { 10 "train": 41, 11 "plane": 160, 12 "bike": 0, 13 "bus": 105, 14 "car": 192, 15 "car_shared": 0 16 } 17 18 if len(sys.argv) != 4: 19 print("Usage: python script.py <input_csv_file> <country> <city>") 20 sys.exit(1) 21 22 geolocator = Nominatim(user_agent='Highlights Conference 2023') 23 24 @cache 25 def get_lat_lon(country, city): 26 location = geolocator.geocode(country + ", " + city) 27 if location is None: 28 print(f"got None response for {country} and {city}") 29 return location.latitude, location.longitude 30 31 target_lat, target_lon = get_lat_lon(sys.argv[2], sys.argv[3]) 32 33 def haversine_distance(lat1, lon1, lat2, lon2): 34 # Convert latitude and longitude from degrees to radians 35 lat1 = math.radians(lat1) 36 lon1 = math.radians(lon1) 37 lat2 = math.radians(lat2) 38 lon2 = math.radians(lon2) 39 40 # Radius of the Earth in kilometers (mean value) 41 earth_radius = 6371.0 # km 42 43 # Haversine formula 44 dlon = lon2 - lon1 45 dlat = lat2 - lat1 46 a = math.sin(dlat / 2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2)**2 47 c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) 48 distance = earth_radius * c 49 50 return distance 51 52 def estimate_distance(country, city): 53 lat, lon = get_lat_lon(country, city) 54 return haversine_distance(lat, lon, target_lat, target_lon) 55 56 57 total_carbon_footprint = 0 58 total_carbon_footprint2 = 0 59 # Available fields are 60 # timestamp,firstname,lastname,email,affiliation,no_zulip,level,presenting,extra,physical,hcrw,country,city,mode 61 with open(sys.argv[1], 'r') as csv_file: 62 reader = csv.DictReader(csv_file) 63 for row in reader: 64 if row['physical'] == "true" and emissions_data.get(row['mode']) is not None: 65 # Calculate the carbon footprint for the round trip 66 mode = None 67 match row['mode']: 68 case "car": 69 mode = "car" 70 case "train": 71 mode = "train" 72 case "bus": 73 mode = "bus" 74 case "plane": 75 mode = "plane" 76 case _: 77 mode = "none" 78 79 lat, lon = get_lat_lon(row['country'], row['city']) 80 distance = haversine_distance(lat, lon, target_lat, target_lon) 81 if distance != 0 and mode != "none": 82 print(f"{mode}, {lat}, {lon}, {distance*1000}") 83 print(f"{mode}, {lat}, {lon}, {distance*1000}") 84 85