def get_gigs(): response = request.get_json() latitude, longitude = response['latitude'], response['longitude'] user_location = lonlat(longitude, latitude) auth_url = response['url'] access_token = get_access_token(auth_url, 'join') spotify_id = get_user_id(access_token) users_top_tracks = get_user_top_tracks(access_token) user = User( access_token=access_token, spotify_id=spotify_id, is_host=False, top_tracks=users_top_tracks, longitude=longitude, latitude=latitude, ) db.session.add(user) db.session.commit() # Check if any gigs are in range host_users = list(User.query.filter(User.is_host == true()).all()) gigs_in_range = [] for host in host_users: host_location = lonlat(host.longitude, host.latitude) if distance(host_location, user_location).meters < 1000: gig_name = Gig.query.filter(Gig.id == host.gig_id).first().gig_name gigs_in_range.append({'gig_name': gig_name, 'id': host.gig_id}) if not gigs_in_range: return make_response(jsonify({'error': 'Not in location of a gig'}), 400) return jsonify({'message': 'Playlist Updated', 'id': spotify_id, 'gigs': gigs_in_range})
def distance_meters(a0, a1): """Helper for getting spatial dist from lon/lat""" lonlat_a0 = gpy.lonlat(*a0) lonlat_a1 = gpy.lonlat(*a1) return gpy.distance(lonlat_a0, lonlat_a1).meters
def find_met(ylat, xlon, metlib_df): """ Returns the meteorological station closest to the facility """ # create numpy arrays lat = metlib_df['surflat'].values lon = metlib_df['surflon'].values dist = np.ones(len(lat)) facility = (xlon, ylat) for i in np.arange(len(lon)): station = (lon[i], lat[i]) dist[i] = round( distance(lonlat(*facility), lonlat(*station)).kilometers, 4) index = np.where(dist == dist.min())[0][0] distance2fac = dist[index] surf_file = metlib_df['surffile'][index] upper_file = metlib_df['upperfile'][index] surfyear = int(metlib_df['surfyear'][index]) # Note: remove white space from surfcity and uacity, Aermod will not allow spaces in the city name surfdata_str = str(metlib_df['surfwban'][index]) + " " + str( int(metlib_df['surfyear'][index])) + " " + str( metlib_df['surfcity'][index]).replace(" ", "") uairdata_str = str(metlib_df['uawban'][index]) + " " + str( int(metlib_df['surfyear'][index])) + " " + str( metlib_df['uacity'][index]).replace(" ", "") prof_base = str(metlib_df['elev'][index]) return surf_file, upper_file, surfdata_str, uairdata_str, prof_base, distance2fac, surfyear
def return_met(facid, faclat, faclon, surfname, metlib_df): """ Returns the meteorological information for a specific surface station name """ metrow = metlib_df.loc[metlib_df['surffile'].str.upper() == surfname.upper()] if metrow.empty == True: emessage = ( "Meteorology station " + surfname + " was chosen for facility " + facid + "\n" "That station is not in the meteorlogical library. The facility will be skipped" ) Logger.logMessage(emessage) raise Exception(emessage) facility = (faclon, faclat) station = (metrow['surflon'].iloc[0], metrow['surflat'].iloc[0]) distance2fac = round( distance(lonlat(*facility), lonlat(*station)).kilometers, 4) surf_file = metrow['surffile'].iloc[0] upper_file = metrow['upperfile'].iloc[0] surfyear = metrow['surfyear'].iloc[0] # Note: remove white space from surfcity and uacity, Aermod will not allow spaces in the city name surfdata_str = str(metrow['surfwban'].iloc[0]) + " " + str( int(metrow['surfyear'].iloc[0])) + " " + str( metrow['surfcity'].iloc[0]).replace(" ", "") uairdata_str = str(metrow['uawban'].iloc[0]) + " " + str( int(metrow['surfyear'].iloc[0])) + " " + str( metrow['uacity'].iloc[0]).replace(" ", "") prof_base = str(metrow['elev'].iloc[0]) return surf_file, upper_file, surfdata_str, uairdata_str, prof_base, distance2fac, surfyear
def getNearbyRestautants(request): client = coreapi.Client() schema = client.get( 'https://maps.googleapis.com/maps/api/place/nearbysearch/json') data = request.data location = (data['lat'], data['lng']) radius = 3000 placetype = 'restaurant' key = '' params = { "location": location, "radius": radius, "type": placetype, "key": key } #result = client.action(schema, [], params) results = datajson.data['results'] toreturn = [] for place in results: obj = {} obj['location'] = place['geometry']['location'] obj['name'] = place['name'] obj['place_id'] = place['place_id'] ecart = distance( lonlat(*(data['lng'], data['lat'])), lonlat(*(place['geometry']['location']['lng'], place['geometry']['location']['lat']))) obj['distance'] = ecart.miles toreturn.append(obj) return Response(toreturn)
def sortear_distancia(df, context): """Recibe un DF y le agrega/modifica una columna que almacena la distancia (en metros) entre cada cajero y el usuario. Devuelve el DF ordenado por los cajeros más cercanos al usuario. """ df["distancia"] = df.apply(lambda x: distance(lonlat(*(x['long'], x['lat'])), lonlat(*(context.user_data["longitud"], context.user_data["latitud"]))).meters, axis=1) df = df.sort_values('distancia') return df
def get_timestamps_by_coordinates(self, latitude, longitude, radius=1): timestamps = [] for location in self.raw['locations']: timestamp = int(int(location['timestampMs']) / 1000) loc_latitude = location['latitudeE7'] / 1e7 loc_longitude = location['longitudeE7'] / 1e7 coord_distance = distance(lonlat(longitude, latitude), lonlat(loc_longitude, loc_latitude)).miles if radius >= coord_distance: timestamps.append(timestamp) return sorted(timestamps)
def move_position(self): apt_loc = (self.apt.lng,self.apt.lat) plane_loc = (self.lng,self.lat) bearing = get_bearing(plane_loc,apt_loc) pt = lonlat(*plane_loc) dest = VincentyDistance(meters = self.speed).destination(pt,bearing) return dest.longitude,dest.latitude
def point_along_line(start_point, end_point, meters_from_start): """ Return a point that is one the line between start_point and end_point, meters_from_start away from the start_point Points are (x,y) (lon,lat) """ segment_length = distance(lonlat(*start_point), lonlat(*end_point)).meters ratio_of_distances = meters_from_start / segment_length destination_point = (((1 - ratio_of_distances) * start_point[0]) + (ratio_of_distances * end_point[0]), ((1 - ratio_of_distances) * start_point[1]) + (ratio_of_distances * end_point[1])) return destination_point
def get_nearest_bars(bars): bars_list = [] for bar in bars: longitude = bar['geoData']['coordinates'][0] latitude = bar['geoData']['coordinates'][1] bar_coordinatates = (longitude, latitude) bar_details = { 'title': bar['Name'], 'longitude': bar['geoData']['coordinates'][0], 'latitude': bar['geoData']['coordinates'][1], 'distance': distance(lonlat(*user_coordinates), lonlat(*bar_coordinatates)).km } bars_list.append(bar_details) sorted_bars = sorted(bars_list, key=get_distance) return sorted_bars[:NUMBER_OF_NEAREST_BARS]
def get_nearest_pizzeria(coordinates): pizzerias = [] for pizzeria in get_flow_entries(PIZZERIA_FLOW_SLUG): pizzeria_coodrinates = (pizzeria['latitude'], pizzeria['longitude']) pizzeria_distance = round( distance(pizzeria_coodrinates, lonlat(*coordinates)).km, 3) pizzerias.append((pizzeria['id'], pizzeria_distance)) nearest_pizzeria = min(pizzerias, key=lambda x: x[1]) return nearest_pizzeria
def get_distance_meters(aLocation1, aLocation2): #Haversine method """R = 6371000 #Radius of "spherical" earth lat1_rad = math.radians(aLocation1.lat) lat2_rad = math.radians(aLocation2.lat) dlat_rad = math.radians(aLocation2.lat - aLocation1.lat) dlon_rad = math.radians(aLocation2.lon - aLocation1.lon) dalt = math.fabs(aLocation2.alt - aLocation1.alt) a = math.sin(dlat_rad / 2) * math.sin(dlat_rad / 2) + math.cos(lat1_rad) * math.cos(lat2_rad) * math.sin(dlon_rad / 2) * math.sin(dlon_rad / 2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) d = R * c d1 = haversine((aLocation1.lat, aLocation1.lon), (aLocation2.lat, aLocation2.lon)) return (d, d1)""" #Using Karney method d = distance(lonlat(aLocation1.lat, aLocation1.lon, aLocation1.alt), lonlat(aLocation2.lat, aLocation2.lon, aLocation2.alt)).m dalt = math.fabs(aLocation2.alt - aLocation1.alt) return math.sqrt(math.pow(d, 2) + math.pow(dalt, 2))
def cut_street_into_points(street): """ """ meters_per_car = 21 * one_foot_in_meters geom = [Point(xy) for xy in street['geometry'].coords] geom_idx = 0 parking_spots = [geom[0].coords[0]] meters_remaining_for_current_spot = meters_per_car while geom_idx < (len(geom) - 1): segment_start = geom[geom_idx].coords[0] segment_end = geom[geom_idx + 1].coords[0] segment_length = distance(lonlat(*segment_start), lonlat(*segment_end)).meters while meters_remaining_for_current_spot < segment_length: new_spot = point_along_line(segment_start, segment_end, meters_remaining_for_current_spot) parking_spots += [new_spot] segment_start = new_spot segment_length -= meters_remaining_for_current_spot meters_remaining_for_current_spot = meters_per_car # If this segment is too short for even one parking spot, # OR there is not enough segment remaining for another parking spot, # decrement the meters remaining by leftover segment length and iterate to the next segment. meters_remaining_for_current_spot -= segment_length geom_idx += 1 return [Point(p) for p in parking_spots]
def Distance(loc1, loc2, unit): if unit == "km": return distance(lonlat(*loc1), lonlat(*loc2)).km elif unit == "mi": return distance(lonlat(*loc1), lonlat(*loc2)).mi elif unit == "m": return distance(lonlat(*loc1), lonlat(*loc2)).m else: raise NotImplementedError
def readFile(city, stations, stateCodes, df, within): # finding stations within close distance to city and setting the most recent values for water data based on that proximity try: cityStations = [] stateCode = stateCodes.get(city.state) for station in stations: if(station.stateCode < stateCode): continue elif(station.stateCode > stateCode): break distanceBtwn = distance(lonlat(station.longitude, station.latitude), lonlat(city.longitude, city.latitude)).miles if(distanceBtwn <= within): cityStations.append(station.identifier) pattern = '|'.join(cityStations) city.totalDissolvedSolids = float(df[(df.CharacteristicName == 'Total dissolved solids') & ( df.MeasureUnitCode.str.contains("mg/l")) & (df.MonitoringLocationIdentifier.str.contains(pattern))].iloc[0].ResultMeasureValue) city.specificConductance = float(df[(df.CharacteristicName == 'Specific conductance') & ( df.MeasureUnitCode.str.contains("uS/cm")) & (df.MonitoringLocationIdentifier.str.contains(pattern))].iloc[0].ResultMeasureValue) city.pH = float(df[(df.CharacteristicName == 'pH') & ( df.MeasureUnitCode.str.contains("std units")) & (df.MonitoringLocationIdentifier.str.contains(pattern))].iloc[0].ResultMeasureValue) # if missing any or all data, accept null values for that city except: print("Missing data for " + city.name) return
def get_flight_route_data(start_latitide, start_longitude, start_datetime, end_latitude, end_longitude, end_datetime): """ * Method to find sun's position during flight *** :params start_latitide : source's latitude :params start_longitude : source's longitude :params start_datetime : flight's departure time :params end_latitude : destination's latitude :params end_longitude : destination's latitude :params end_datetime : flight's arrival latitude * return formatted dict with flight's route information """ day = False night = False coordinates_list = [] # start point day/night finder start_datetime_obj = datetime.strptime(start_datetime, "%Y%m%dT%H:%M:%SZ") end_datetime_obj = datetime.strptime(end_datetime, "%Y%m%dT%H:%M:%SZ") tz_start_time = start_datetime_obj.astimezone(pytz.timezone("UTC")) tz_end_time = end_datetime_obj.astimezone(pytz.timezone("UTC")) # checking for sun's position at start point to get if flight started in day or night initial_sun_position = getPosition(tz_start_time, start_latitide, start_longitude) if initial_sun_position["altitude"] > 0: day = True # checking for sun's position at start point to get if flight ended in day or night final_sun_position = getPosition(tz_end_time, end_latitude, end_longitude) if final_sun_position["altitude"] > 0: night = True # distance between start and end point travel_distance = great_circle(lonlat(start_longitude, start_latitide), lonlat(end_longitude, end_latitude)).kilometers total_duration = (end_datetime_obj - start_datetime_obj).seconds speed = travel_distance / (total_duration / 3600) travel_info = { "start": "day" if day else "night", "end": "day" if night else "night", "travel_distance": travel_distance, "total_duration": time.strftime( '%H:%M:%S', time.gmtime((end_datetime_obj - start_datetime_obj).seconds)), "speed": speed / 1.852 } A = (start_latitide, start_longitude) # Point A (lat, long) B = (end_latitude, end_longitude) # Point B (lat, lon) speed = travel_distance / (total_duration / 3600) # code for finding geopoints after every 10km points_inbetween_coordinates = math.floor(travel_distance / 10) enroute_coordinates = [] for point in range(points_inbetween_coordinates + 1): positional_data, time_at_c, coordinates = get_positional_data( A, B, speed, start_datetime_obj) A = coordinates start_datetime_obj = time_at_c positional_data["index"] = point positional_data["time_at_c"] = time_at_c positional_data["enroute_sunrise_lat"] = coordinates[0] positional_data["enroute_sunrise_long"] = coordinates[1] coordinates_list.append(positional_data) remaining_distance = great_circle( lonlat(coordinates[1], coordinates[0]), lonlat(end_longitude, end_latitude)).kilometers point += 1 enroute_coordinates.append({"lat": A[0], "long": A[1]}) travel_info["coordinates_list"] = coordinates_list travel_info["total_duration"] = (tz_end_time - tz_start_time).seconds final_results = process_positional_data(travel_info, tz_start_time, tz_end_time) final_results["total_duration"] = time.strftime( '%H:%M:%S', time.gmtime((tz_end_time - tz_start_time).seconds)) final_results["enroute_coordinates"] = enroute_coordinates return final_results
def test_lonlat_function(self): newport_ri_xy = (-71.312796, 41.49008) point = lonlat(*newport_ri_xy) self.assertEqual(point, (41.49008, -71.312796, 0))
def calc_geodistance(lonlat1=(), lonlat2=()): from geopy.distance import lonlat, distance dist = distance(lonlat(*lonlat1), lonlat(*lonlat2)).km return dist
def _pandas(cls, column, **kwargs): column_shape_format = kwargs.get("column_shape_format") place = kwargs.get("place") geocoder = kwargs.get("geocoder") geocoder_config = kwargs.get("geocoder_config") min_value = kwargs.get("min_value") max_value = kwargs.get("max_value") strict_min = kwargs.get("strict_min") strict_max = kwargs.get("strict_max") units = kwargs.get("units") if min_value is None and max_value is None: raise ValueError("min_value and max_value cannot both be None") if min_value is not None and max_value is not None and min_value > max_value: raise ValueError("min_value cannot be greater than max_value") if geocoder not in ["nominatim", "pickpoint", "openmapquest"]: raise NotImplementedError( "The geocoder is not implemented for this method.") # find the reference shape with the geocoder. if geocoder is not None: try: # Specify the default parameters for Nominatim and run query. User is responsible for config and query params otherwise. query_params = dict(exactly_one=True, geometry="wkt") location = cls.geocode(geocoder, geocoder_config, place, query_params) except: raise Exception( "Geocoding configuration and query failed to produce a valid result." ) else: raise Exception( "A valid geocoder must be provided for this method. See GeoPy for reference." ) # Load the column into a pygeos Geometry vector from numpy array (Series not supported). if column_shape_format == "wkt": shape_test = geos.from_wkt(column.to_numpy(), on_invalid="ignore") elif column_shape_format == "wkb": shape_test = geos.from_wkb(column.to_numpy(), on_invalid="ignore") elif column_shape_format == "lonlat": shape_df = pd.DataFrame(column.to_list(), columns=("lon", "lat")) shape_test = geos.points(shape_df.lon, y=shape_df.lat) elif column_shape_format == "latlon": shape_df = pd.DataFrame(column.to_list(), columns=("lat", "lon")) shape_test = geos.points(shape_df.lon, y=shape_df.lat) else: raise NotImplementedError( "Column values shape format not implemented.") # verify that all shapes are points and if not, convert to centroid point. points_test = pd.Series(shape_test) if not points_test.apply(lambda x: geos.get_type_id(x) == 0).all(): points_test = points_test.map(geos.centroid) # convert the geos point to a geopy point. points_test = points_test.apply( lambda x: lonlat(geos.get_x(x), geos.get_y(x))) if location is None: raise Exception("Geocoding failed to return a result.") else: point_ref = lonlat(location.longitude, location.latitude) # calculate the distance between the points using geopy if units in [ "km", "kilometers", "kilometres", "kilometer", "kilometre" ]: column_dist = points_test.apply( lambda p: distance(p, point_ref).km) elif units in ["m", "meters", "metres", "meter", "metre"]: column_dist = points_test.apply(lambda p: distance(p, point_ref).m) elif units in ["mi", "miles", "mile"]: column_dist = points_test.apply( lambda p: distance(p, point_ref).mi) elif units in ["ft", "feet", "foot"]: column_dist = points_test.apply( lambda p: distance(p, point_ref).ft) else: raise NotImplementedError( "Unit conversion has not yet been implemented. Please use one of km, m, mi, ft" ) # Evaluate the between statement (from column_values_between.py) if min_value is None: if strict_max: return column_dist < max_value else: return column_dist <= max_value elif max_value is None: if strict_min: return min_value < column_dist else: return min_value <= column_dist else: if strict_min and strict_max: return (min_value < column_dist) & (column_dist < max_value) elif strict_min: return (min_value < column_dist) & (column_dist <= max_value) elif strict_max: return (min_value <= column_dist) & (column_dist < max_value) else: return (min_value <= column_dist) & (column_dist <= max_value)
def distance(lon1, lat1, lon2, lat2): loc1 = (lon1, lat1) loc2 = (lon2, lat2) return geodesic(lonlat(*loc1), lonlat(*loc2)).m
def getDistance(a,b):#calcola la distanza tra due punti a e b che rappresentano ciascuno la latitudine e la longitudine return int(distance(lonlat(*a), lonlat(*b)).km)
def dist(loc1, loc2): loc1_pos = (loc1.lng, loc1.lat) loc2_pos = (loc2.lng, loc2.lat) # bearing = get_bearing(loc1_pos,loc2_pos) return distance(lonlat(*loc1_pos), lonlat(*loc2_pos)).meters
def long_lat_dist(first, second, neighbours): first_c = neighbours[first] second_c = neighbours[second] return distance(lonlat(*first_c), lonlat(*second_c)).kilometers
def scale_numeric(ax, inches_to_cm=1 / 2.54): fig = ax.get_figure() bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) bbox_in_data_coords = ax.get_window_extent().transformed( ax.transData.inverted()) dx_fig = bbox.width * inches_to_cm # width in cms # Getting distance: x0, x1, y0, y1 = ax.get_extent() proj4_params = ax.projection.proj4_params units = proj4_params.get('units', None) # if ax projection is a projected crs: if units is not None: dx_mapa = x1 - x0 # in case it is not a projected crs (i.e.: PlateCarree): else: lon_min = x0 lat_mean = np.mean([y0, y1]) # Define starting point. start = geopy.Point(lonlat(lon_min, lat_mean)) delta_x = bbox_in_data_coords.width # in degrees end = geopy.Point(lonlat(lon_min + delta_x, lat_mean)) try: # by defining the ellipsoid ellips = ax.projection.globe.ellipse if ellips == 'WGS84': ellips = 'WGS-84' elif ellips == 'GRS80': ellips = 'GRS-80' elif ellips == 'GRS67': ellips = 'GRS-67' dx_mapa = distance(start, end, ellipsoid=ellips).m * 1e2 # meters to cm except: print( 'Non ellipse was defined. Resorting to the standard wgs84 for distance evaluation' ) # without defining the ellipsod dx_mapa = distance( start, end, ellipsoid=ax.projection.globe.ellipse).m * 1e2 # meters to cm print('distance in x: ', dx_mapa) # updating dx_mapa, so that it will always be [1 in fig cm: dx_mapa cm] dx_mapa = dx_mapa / dx_fig return dx_fig, dx_mapa / 10 # dividing by 10... It fix the error found by comparing with Qgis (why?)
horizontal_length = (int(positions[2]) - int(positions[0]))/904*RESIZE_DIM vertical_length = (int(positions[3]) - int(positions[1]))/904*RESIZE_DIM # Coordinates of centre of cyclone coordinates = open(IMG_DIR + cyclone_name + '.loc.tsv', 'r').readlines()[0].strip().split(' ') cyclone_lat = float(coordinates[0]) cyclone_lon = float(coordinates[1]) # Find the scale of the image with open(IMG_DIR + cyclone_name + '.bboxes.labels.tsv', 'r') as f: coordinates = f.readlines()[0].strip()[1:-1].split(', ') top = coord_transform(coordinates[0][1:-1]) bottom = coord_transform(coordinates[1][1:-1]) left = coord_transform(coordinates[2][1:-1]) right = coord_transform(coordinates[3][1:-1]) horizontal_scale = distance(lonlat(*(left, cyclone_lat)), lonlat(*(right,cyclone_lat))).km / horizontal_length vertical_scale = distance(lonlat(*(cyclone_lon, top)), lonlat(*(cyclone_lon, bottom))).km /vertical_length label.append([horizontal_scale, vertical_scale]) # Putting the data into the appropriate set if '_'.join(cyclone_name.split('_')[:3]) in VALIDATION_SET: val_data.append(resize_img) val_labels.append(label) val_names.append(cyclone_name) elif '_'.join(cyclone_name.split('_')[:3]) in TEST_SET: test_data.append(resize_img) test_labels.append(label) test_names.append(cyclone_name) else: train_data.append(resize_img) train_labels.append(label)
cenBlks = pd.read_csv("points_AlbersXY.csv") # Get list of unique states to loop through states = cenBlks.state_abbrev.unique() # loop through states to make distance matrix for each state one at a time. for state in states: print("Calculating Distance Matrix for State: ", state) st_dat = cenBlks[cenBlks['state_abbrev'] == str(state)] # subset to one state (current state in the loop) st_dat = st_dat[['GEOID10', 'lat', 'lon']] # only keep lat/lon and ID variables # using merge to generate all possibilities between origin and destination # this will make an (N^2 x 6) length matrix with all possible combinations of lat/lon in the state df = pd.merge(st_dat.assign(key=0), st_dat.assign(key=0), suffixes=('', '_x'), on='key').drop('key', axis=1) # Use geopy to calculate miles between all nces combinations in the dataframe we just made df['Miles'] = df.apply( (lambda row: geodesic(lonlat(row['lon'], row['lat']), lonlat(row['lon_x'], row['lat_x'])).miles), axis=1) # Now reshape the data to look like the distance matrix we want df = df.groupby(['GEOID10', 'GEOID10_x'])['Miles'].max().unstack() # Add in state variable to dataset as first variable df.insert(0, 'state', [state] * len(df)) # Save each unique state distance matrix flnm = "stateDistances/" + state + "distMatrix.csv" df.to_csv(flnm)
i = i + 1 # In[ ]: poison_loc_df.head(10) # In[ ]: from geopy.distance import lonlat, distance i = 0 for index, row in poison_loc_df.iterrows(): poison = (poison_loc_df.iloc['lon'], poison_loc_df['lat']) inspection = (-81.695391, 41.499498) print(distance(lonlat(*newport_ri_xy), lonlat(*cleveland_oh_xy)).miles) 538.3904453677203 # In[ ]: # Merge data on business name merge_df = pd.merge(poison_loc_df, inspection_df, how='inner', left_on=['lat', 'lng'], right_on=['latitude', 'longitude']) merge_df.head() # In[ ]: inspection_df
lat_lon_to_index[node] = i # NODES in w_G have index, use that index to build links print(lat_lon_to_index) print(lat_lon_to_index[(-172.0, -81.0)]) # lat_lon_to_index is a list where coordinates are index, # by doing that: add_edge below can convert coordinates to index # ---------------------build network-------- from geopy.distance import lonlat, distance for edge in G.edges(data=True): print([lat_lon_to_index[edge[0]], lat_lon_to_index[edge[1]]]) # node index print(edge[0]) # edge[0] = coordinates dis_km = distance(lonlat(*edge[0]), lonlat(*edge[1])).km # look up node index by coordinates w_G.add_edge(lat_lon_to_index[edge[0]], lat_lon_to_index[edge[1]], distance=dis_km) # distance function uses (latitude, longtitue), shape uses (long, lat), needs conversion # w_G.add_edge(lat_lon_to_index[edge[0]], lat_lon_to_index[edge[1]], distance=edge[2]['cost'],id=edge[2]['edge_id'] ) print(w_G.nodes()[0:10]) print(w_G.edges(data=True)[0:10]) # (data=True) shows the attributes of the links/nodes # ---------------------shortest path--------------------------
# Cyclone wind speed windspeed = 0 with open(IMG_DIR + image + '.wind.tsv', 'r') as f: windspeed = float(f.readlines()[0].strip()) input_sequence_label.append(windspeed) # Coordinates of centre of cyclone coordinates = open(IMG_DIR + image + '.loc.tsv', 'r').readlines()[0].strip().split(' ') cyclone_lat = float(coordinates[0]) cyclone_lon = float(coordinates[1]) # Find the scale of the image horizontal_scale = distance( lonlat(*(left_same, cyclone_lat)), lonlat(*(right_same, cyclone_lat))).km / new_size[1] vertical_scale = distance( lonlat(*(cyclone_lon, top_same)), lonlat(*(cyclone_lon, bottom_same))).km / new_size[0] input_sequence_label.append([horizontal_scale, vertical_scale]) i += 1 # Putting the data into the appropriate set if '_'.join(image_sequence[4].split('_')[:3]) in VALIDATION_SET: val_data.append(input_sequence) val_labels.append(input_sequence_label) val_names.append(image_sequence[4]) elif '_'.join(image_sequence[0].split('_')[:3]) in TEST_SET: test_data.append(input_sequence) test_labels.append(input_sequence_label)
def result(loc1, loc2, one, two): x = (distance(lonlat(*one), lonlat(*two)).miles) print ("Distance between %s and %s is %s miles." % (loc1, loc2, str(x)))