def calulate_airport_distance(id1, id2): with open("airports.csv") as airport_csv: airports_reader = csv.reader(airport_csv) airports_header = next(airports_reader) airport_latitude_list = {} airport_longitude_list = {} for airport in airports_reader: airport_latitude_list[int(airport[0])] = float(airport[6]) airport_longitude_list[int(airport[0])] = float(airport[7]) with open("route.csv") as route_csv: route_reader = csv.reader(route_csv) route_header = next(route_reader) distance(airport_latitude_list[id1], airport_longitude_list[id1], airport_latitude_list[id2], airport_longitude_list[id2])
def distance(city1, city2): # Get lists of possible airports city1airports = find_airports(city1) city2airports = find_airports(city2) # Make sure we actually got airports if len(city1airports) == 0 or len(city2airports) == 0: print("Couldn't find an airport for ya, bud.") return # Create rows to write later new_rows = [] for airport1 in city1airports: for airport2 in city2airports: city1_lat = float(airport1[6]) city1_long = float(airport1[7]) city2_lat = float(airport2[6]) city2_long = float(airport2[7]) result = geo_distance.distance(city1_lat, city1_long, city2_lat, city2_long) new_rows.append([city1, airport1[1], city2, airport2[1], result]) with open('result.csv', 'w') as file: writer = csv.writer(file) header = [ 'Departing City', 'Departing Airport', 'Arriving City', 'Arriving Airport', 'Distance (km)' ] writer.writerow(header) for row in new_rows: writer.writerow(row)
def find_route_info(): ''' :return: [ [source airport ID, (its city, its country), # of flights out of that airport, distination ID, (its city, its country), flight distance, world rank of that flight distance] ] ''' info = [] d = airports_info() with open('routes.csv') as f: routes = csv.reader(f) header = next(routes) for row in routes: source, dest = row[3], row[5] if source in d and dest in d: source_list = d[source] dest_list = d[dest] source_lat, source_long = source_list[1], source_list[2] dest_lat, dest_long = dest_list[1], dest_list[2] info.append([ source, source_list[0], source_list[3], dest, dest_list[0], geo_distance.distance(source_lat, source_long, dest_lat, dest_long), 0 ]) add_distance_rank(info) return info
def calc_airport_distances(origin, destination): origin_city = csv_airport(origin) destination_city = csv_airport(destination) rows = [] for airport1 in origin_city: for airport2 in destination_city: lat_origin = float(airport1[6]) long_origin = float(airport2[7]) lat_destination = float(airport2[6]) long_destination = float(airport2[7]) km_dist = geo_distance.distance(lat_origin, long_origin, lat_destination, long_destination) rows.append([origin, airport1[1], destination, airport2[1], km_dist]) # for the csv print( "The distance from {}'s {} to {}'s {} in kilometers is {}".format( origin, airport1[1], destination, airport2[1], km_dist)) with open('distances.csv', 'w') as file: write = csv.writer(file) header = [ 'Departing', 'Departing Airport', 'Arriving', 'Arriving Airport', 'Difference in KM' ] write.writerow(header) for row in rows: write.writerow(row)
def get_route_distance(): #Make latitude dictionary with open("airports.csv") as airports_csv: airport_reader = csv.reader(airports_csv) airport_header = next(airport_reader) latitudes = {row[0]: row[6] for row in airport_reader} #Make longitudes dictionary with open("airports.csv") as airports_csv: airport_reader = csv.reader(airports_csv) longitudes = {row[0]: row[7] for row in airport_reader} #Lookup coordinates to routes with open("routes.csv") as routes_csv: route_reader = csv.reader(routes_csv) route_header = next(route_reader) #Keep track of lookup errors no_id = 0 errors = [] for row in route_reader: from_air = row[3] to_air = row[5] #Get origin lat, longs try: from_lat, from_long = float(latitudes[from_air]), float( longitudes[from_air]) except KeyError: no_id += 1 if from_air not in errors: errors.append(from_air) #Get destination lat, longs try: to_lat, to_long = float(latitudes[to_air]), float( longitudes[to_air]) except KeyError: no_id += 1 if to_air not in errors: errors.append(from_air) #Calculate route distance route_distance = distance(from_lat, from_long, to_lat, to_long) #Save to new file new_row = [ from_air, from_lat, from_long, to_air, to_lat, to_long, route_distance ] with open("combined_file.csv", "a") as combined: combined_writer = csv.writer(combined) combined_writer.writerow(new_row) #Print any lookup errors print("Records that don't match:", str(no_id)) print("Errors: ", errors)
def print_airport(): # initialize lat and lon dictionaries lat = dict() lon = dict() # Open the airports.csv file to read lat and lon for each aiport (store # airport ID as int as dict key with open('airports.csv') as fin: reader = csv.reader(fin) header = next(reader) # Latitude is index 6, longitude is index 7 for row in reader: lat[int(row[0])] = float(row[6]) lon[int(row[0])] = float(row[7]) # Now open the dists.txt file for writing out the distance calculations with open('dists.txt', 'w', newline='') as fout: writer = csv.writer(fout) # Write a header line writer.writerow(('Start-Airport-ID','End-Airport-ID','Distance')) # Open the routes.csv to see what distances to calculate with open('routes.csv') as f: reader = csv.reader(f) header = next(reader) # Read the file for row in reader: # Start ID is index 3, dest ID is index 5 try: # Attempt to pull the start_id and end_id start_id = int(row[3]) end_id = int(row[5]) except ValueError: # Skip it if there's an issue with the value continue try: # Attempt to calculate the distance dist = distance(lat[start_id], lon[start_id], lat[end_id], lon[end_id]) except KeyError: # But if that fails skip it continue # write out the start_id, end_id and distance writer.writerow((f'{start_id}', f'{end_id}',f'{dist}'))
def calc_airport_distances(): # define two empty dicts that will hold our lat/long info airport_lats = {} airport_longs = {} with open("airports.csv") as f: # setup reader and remove header airport_reader = csv.reader(f) airport_headers = next(airport_reader) for row in airport_reader: try: airport_lats[row[0]] = float(row[6]) except ValueError: print("Value not a float") else: airport_longs[row[0]] = float(row[7]) # now that we have lookup dicts for lat/long loop through the routes with open("routes.csv") as f2: route_reader = csv.reader(f2) route_headers = next(route_reader) for row in route_reader: source_id = row[3] dest_id = row[5] # check to see if the ids for both airports are in the lookup dicts if source_id in airport_lats and dest_id in airport_lats: # use the lat/long dicts to get the coordinate info for each airport source_lat = airport_lats[source_id] source_long = airport_longs[source_id] dest_lat = airport_lats[dest_id] dest_long = airport_longs[dest_id] # make a variable that captures the output from the geo_distance function km_dist = geo_distance.distance(source_lat, source_long, dest_lat, dest_lat) # open a csv file that we want to append information to and write a row with open("air_dist.csv", "a") as f_3: f_3_writer = csv.writer(f_3) f_3_writer.writerow([source_id, dest_id, km_dist])
def get_distances(routes, names, coords): distances = [] errors = 0 for row in routes: a1, a2 = row[0], row[1] # print(a1, a2) try: (lat1, long1) = coords[a1] (lat2, long2) = coords[a2] except KeyError: # print('fail on key 1: {}'.format(a1)) distances.append('airport not found: {}'.format(a1)) errors += 1 continue distances.append(geo_distance.distance(lat1, long1, lat2, long2)) print('Found distances of {} routes with {} errors.'.format(len(distances), errors)) print('EX:') print('First route: {}'.format(routes[0])) print_distance(routes[0], distances[0], names) return distances
def flight_distances(): latitudes = {} longitudes = {} with open("airports.csv") as file: airports = csv.reader(file) airport_headers = next(file) for row in airports: latitudes[row[0]] = float(row[6]) longitudes[row[0]] = float(row[7]) flights = [] with open("routes.csv") as file: routes = csv.reader(file) route_headers = next(file) for row in routes: flights.append((row[3], row[5])) flight_distances = [] bad_rows = [] #values = [] for (origin, destination) in flights: try: lat1, long1, lat2, long2 = latitudes[origin], longitudes[ origin], latitudes[destination], longitudes[destination] flight_distance = geo_distance.distance(latitudes[origin], longitudes[origin], latitudes[destination], longitudes[destination]) flight_distances.append((origin, destination, flight_distance)) except KeyError: bad_rows.append((origin, destination)) ''' The code below enables us to see why the distances for some rows can't be calculated: they involve airports that aren't listed in airports.csv a, b, c, d = origin in latitudes.keys(), origin in longitudes.keys(), destination in latitudes.values(), destination in longitudes.values() values.append((a, b, c, d)) COULD'VE JUST DONE "pass" ''' return flight_distances
def calc_airport_distances(): airport_lats = {} airport_longs = {} stops = None with open("airports.csv") as airports_csv: airport_reader = csv.reader(airports_csv) airport_headers = next(airport_reader) for row in airport_reader: airport_lats[row[0]] = float(row[6]) airport_longs[row[0]] = float(row[7]) with open("routes.csv") as routes_csv: route_reader = csv.reader(routes_csv) route_headers = next(route_reader) for row in route_reader: source_id = row[3] dest_id = row[5] # print(row) if row[7] == 'Y': stops == True if source_id in airport_lats and dest_id in airport_lats: source_lat = airport_lats[source_id] source_long = airport_longs[source_id] dest_lat = airport_lats[dest_id] dest_long = airport_longs[dest_id] km_dist = geo_distance.distance(source_lat, source_long, dest_lat, dest_long) with open("dist_info.csv", "a") as dist_info: dist_info_writer = csv.writer(dist_info) dist_info_writer.writerow( [source_id, dest_id, km_dist, stops])
# create a histogram displaying the frequency of flights by distance. # #As per data used from CSV files. import geo_distance import csv import numpy as np import matplotlib.pyplot as plt distances = [] latitudes = {} longitudes = {} f = open("data/airports.dat") for row in csv.reader(f): airport_id = row[0] latitudes[airport_id] = float(row[6]) longitudes[airport_id] = float(row[7]) f = open("data/routes.dat") for row in csv.reader(f): source_airport = row[3] dest_airport = row[5] if source_airport in latitudes and dest_airport in latitudes: source_lat = latitudes[source_airport] source_long = longitudes[source_airport] dest_lat = latitudes[dest_airport] dest_long = longitudes[dest_airport] distances.append(geo_distance.distance(source_lat,source_long,dest_lat,dest_long)) plt.hist(distances, 100, facecolor='r') plt.xlabel("Distance (km)") plt.ylabel("Number of flights") plt.show()
airport_lats[row[0]] = float(row[6]) airport_longs[row[0]] = float(row[7]) with open('routes.csv') as route_csv: route_reader = csv.reader(route_csv) route_header = next(route_reader) for row in route_reader: source_airport = row[2] source_id = row[3] dest_airport = row[4] dest_id = row[5] if source_id in airport_lats and dest_id in airport_longs: # use the lat/long dicts to get the coordinate info for each airport source_lat = airport_lats[source_id] source_long = airport_longs[source_id] dest_lat = airport_lats[dest_id] dest_long = airport_longs[dest_id] km_dist = geo_distance.distance(source_lat, source_long, dest_lat, dest_long) with open("dist_info.csv", "a") as dist_info: dist_info_writer = csv.writer(dist_info) dist_info_writer.writerow([source_airport, dest_airport, km_dist]) calc_airport_distances()
result = response["which"] if result == "positive": droid.startLocating() time.sleep(16) resultado = droid.readLocation().result #print(resultado) droid.ttsSpeak("posicion guardada") longitud = resultado['network']['longitude'] latitud = resultado['network']['latitude'] droid.stopLocating() print(longitud, latitud) elif result == "negative": print "ponte a trabajar" time.sleep(120) droid.startLocating() time.sleep(16) resultado2 = droid.readLocation().result droid.ttsSpeak("segunda posicion guardada") longitud2 = resultado2['network']['longitude'] latitud2 = resultado2['network']['latitude'] droid.stopLocating() distancia = (geo_distance.distance(latitud, longitud, latitud2, longitud2) * 1000) if distancia < 10: droid.ttsSpeak("no te has movido") else: droid.ttsSpeak("no te alejes de tu trabajo")
def get_distance(source_tuple, dest_tuple): return geo_distance.distance(source_tuple[0], source_tuple[1], dest_tuple[0], dest_tuple[1])
if response.has_key("which"): result=response["which"] if result=="positive": droid.startLocating() time.sleep(16) resultado = droid.readLocation().result #print(resultado) droid.ttsSpeak("posicion guardada") longitud = resultado['network']['longitude'] latitud = resultado['network']['latitude'] droid.stopLocating() print (longitud, latitud) elif result=="negative": print "ponte a trabajar" time.sleep(120) droid.startLocating() time.sleep(16) resultado2 = droid.readLocation().result droid.ttsSpeak("segunda posicion guardada") longitud2 = resultado2['network']['longitude'] latitud2 = resultado2['network']['latitude'] droid.stopLocating() distancia = (geo_distance.distance(latitud,longitud,latitud2,longitud2)*1000) if distancia < 10: droid.ttsSpeak("no te has movido") else: droid.ttsSpeak("no te alejes de tu trabajo")