Ejemplo n.º 1
0
def locate_on_quad(G, num_cols, num_rows, max_lat, min_lon, dist):
    bcn_matrix = [[[] for i in range(num_cols)] for i in range(num_rows)]
    for station in G.nodes:
        i = int(haversine((max_lat, min_lon), (station.lat, min_lon)) // dist)
        j = int(haversine((max_lat, min_lon), (max_lat, station.lon)) // dist)
        bcn_matrix[i][j].append(station)
    return bcn_matrix
Ejemplo n.º 2
0
def create_graph(dist):
    #First, we import all the bicing stations info, in panda format.
    url = 'https://api.bsmsa.eu/ext/api/bsm/gbfs/v2/en/station_information'
    bicing = pd.DataFrame.from_records(pd.read_json(url)['data']['stations'],
                                       index='station_id')

    dist /= 1000  #Convert distance (given in m) to km.
    G = nx.Graph()
    for station in bicing.itertuples():
        G.add_node(station)

    max_lat, min_lat, max_lon, min_lon = bbox(G)

    #We determine the number of rows and columns,
    num_rows = int(haversine((max_lat, min_lon),
                             (min_lat, min_lon)) // dist) + 1
    num_cols = int(haversine((max_lat, min_lon),
                             (max_lat, max_lon)) // dist) + 1

    #Function that locates every station in its respective quadrant.
    bcn_matrix = locate_on_quad(G, num_cols, num_rows, max_lat, min_lon, dist)

    #In this loop, we check all the possible connections between stations.
    for i in range(num_rows):
        for j in range(num_cols):
            G = adjacent(G, bcn_matrix, i, j, i, j, dist)
            if i > 0: G = adjacent(G, bcn_matrix, i, j, i - 1, j, dist)
            if i > 0 and j + 1 < num_cols:
                G = adjacent(G, bcn_matrix, i, j, i - 1, j + 1, dist)
            if j + 1 < num_cols:
                G = adjacent(G, bcn_matrix, i, j, i, j + 1, dist)
            if i + 1 < num_rows and j + 1 < num_cols:
                G = adjacent(G, bcn_matrix, i, j, i + 1, j + 1, dist)
    return G
Ejemplo n.º 3
0
def route(G, name_file, addresses):
    coord_origin, coord_destination = addressesTOcoordinates(addresses)
    coord_origin = Pandas(lat=coord_origin[0], lon=coord_origin[1])
    coord_destination = Pandas(lat=coord_destination[0],
                               lon=coord_destination[1])
    radius = haversine(coord_origin, coord_destination)
    G.add_nodes_from([coord_origin, coord_destination])
    for node in G.nodes:
        dist_O = haversine(coord_origin, (node.lat, node.lon))
        dist_D = haversine(coord_destination, (node.lat, node.lon))
        if dist_O <= radius:
            G.add_edge(coord_origin, node, weight=dist_O/4)
        if dist_D <= radius:
            G.add_edge(coord_destination, node, weight=dist_D/4)
    fastest_path = nx.dijkstra_path(G, coord_origin, coord_destination)
    G.remove_nodes_from([coord_origin, coord_destination])
    Route = nx.Graph()
    # When we modify the graph in order to be plotted, we also compute
    # the average time of the route.
    time = 0
    for i in range(len(fastest_path)-1):
        a, b = ((fastest_path[i].lat, fastest_path[i].lon),
                (fastest_path[i+1].lat, fastest_path[i+1].lon))
        if i == 0 or i == len(fastest_path)-1:
            time += haversine(a, b)/4
        else:
            time += haversine(a, b)/10
        Route.add_edge(fastest_path[i], fastest_path[i+1])
    plotgraph(Route, name_file)
    return int(time*60)
Ejemplo n.º 4
0
def latlong(event):
    data = json.loads(event['body']) if event.get('body', 0) else event
    conn = get_db()
    curr = conn.cursor()
    curr.execute(
        "SELECT latitude,longitude, status from restaurant_restaurants ")
    row = curr.fetchall()
    if len(row) >= 2:
        restaurantsDataList = row
        customer = {
            'latitude': data['latitude'],
            'longitude': data['longitude']
        }
        result = closest(restaurantsDataList, customer)
        response = result[:10]

        rs = []
        for items in response:
            restaurants_lat_long = (items['latitude'], items['longitude']
                                    )  # (lat, lon)
            customers_lat_logn = (data['latitude'], data['longitude'])

            distance_li = haversine(restaurants_lat_long, customers_lat_logn)

            if distance_li <= 5:
                # if items.get('status') == "Open":
                rs.append(items['latitude'])

        find_lat = tuple(rs)
        return find_lat
    else:
        return []
def distance(position1, position2):
    change = haversine((position1[0], position1[1]),
                       (position2[0], position2[1]),
                       miles=False)
    #change = great_circle((position1[0], position1[1]),(position2[0],position2[1])).miles
    change = change * 1000
    return change
Ejemplo n.º 6
0
def findClosest(inLat, inLon, numTrucks, cache):
    #Get food truck data from cache if exists, else read the food truck data and set the cache
    json_data = cache.get("data")
    if (json_data == None):
        json_data = read_data(cache)

    #Iterate through food truck json file and calculate the distance from the input latitude and longitude.
    #Store the distance and the food trucks in an array.
    #For production, look into using array and numpy array for handling arrays, since they are quicker due to preallocation of memory.
    distList = []
    for i in json_data['data']:
        #Use the haversine formula to compute the distance
        dist = haversine(inLat, inLon, i["Latitude"], i["Longitude"])
        distList.append([
            dist, i["Applicant"], i["LocationDescription"], i["Latitude"],
            i["Longitude"], i["locationid"]
        ])

    #Set the distance as the key to sort on
    def sortDist(val):
        return val[0]

    #Store the distance in the array, so the closest is at the top
    distList.sort(key=sortDist)

    #Add the numTrucks closest food trucks to an array
    x = 0
    closest = []
    while (x < numTrucks):
        closest.append(distList[x])
        x += 1

    #Return the numTrucks closest food trucks in the json array
    return json.dumps(closest)
Ejemplo n.º 7
0
def adjacent(G, bcn_matrix, i, j, k, l, dist):
    for st_A in bcn_matrix[i][j]:
        for st_B in bcn_matrix[k][l]:
            d_AB = haversine([st_A.lat, st_A.lon], [st_B.lat, st_B.lon])
            if d_AB <= dist and st_A != st_B:
                G.add_edge(st_A, st_B, weight=d_AB / 10)
    return G
Ejemplo n.º 8
0
def htmlemail(lat, lon, radius):
    recipients = user.objects.filter(last_lat__lt=lat + 5,
                                     last_lat__gt=lat - 5,
                                     last_lon__lt=lon + 5,
                                     last_lon__gt=lon - 5)
    recips = {}
    for recipient in recipients:
        recips[
            recipient.
            fsq_id] = recipient.first_name, recipient.last_name, recipient.email
    the_records = record.objects.filter(time__lt=time(),
                                        time__gt=time() - 86400)
    the_set = {}
    for item in the_records:

        v = authenticator.userless_query("/venues/" + item.venue_id)
        vlat = v['venue']['location']['lat']
        vlon = v['venue']['location']['lng']
        venue_name = v['venue']['name']
        try:
            venue_address = v['venue']['location']['address'] + ' ' + v[
                'venue']['location']['city'] + ', ' + v['venue']['location'][
                    'state'] + ' ' + v['venue']['location']['postalCode']
        except:
            pass
        if item.venue_id in the_set.keys():
            the_set[item.venue_id][2] += item.target.quotient()
            the_set[item.venue_id][3] += 1
        elif haversine(float(vlon), float(vlat), float(lon),
                       float(lat)) <= int(radius):
            the_set[item.venue_id] = [
                venue_name, venue_address,
                item.target.quotient(), 1
            ]
        else:
            pass

    averages = {}
    for item in the_set.iteritems():
        averages[item[0]] = [
            item[1][2] / item[1][3], {
                'female': [],
                'male': []
            }
        ]

    for item in the_records:
        try:

            u = user_lookup.objects.get(pic_id=item.target.pic_id)
            g = authenticator.query(
                "users/" + u.fsq_id,
                token="1A0ESOQC4W2RIGY442CJTKKFJEM04BYCEHSG0SNCVIWMKPII")
            averages[item.venue_id][1][g['user']['gender']].append(
                item.target.pic_id)
        except:
            pass
    for item in the_set:
        the_set[item].append(averages[item])
    return the_set
Ejemplo n.º 9
0
def suggested_venues(fsq_id='', lat='', lon='', radius=''):
	newdict = {}
	if fsq_id:
                query = record.objects.filter(time__lt=time(), time__gt=time()-3600, user=user.objects.get(fsq_id=fsq_id)).order_by('venue_id')
		for venue in query:
	      		if venue.venue_id not in newdict:
				newdict[venue.venue_id]=[1,[venue.target.pic_id]]              
			elif venue.target.pic_id not in newdict[venue.venue_id][1]:
				newdict[venue.venue_id][0]+=1
				newdict[venue.venue_id][1].append(venue.target.pic_id)
			else:
				pass
	else:
		query = record.objects.filter(time__lt=time(), time__gt=time()-3600).order_by('venue_id')
		for venue in query:
			v=venue_ll.objects.get(venue_id=venue.venue_id)
			vlat=v.lat
			vlon=v.lon
			if venue.venue_id not in newdict and haversine(float(lat),float(lon),float(vlat),float(vlon)) <= int(radius)/1000:
				newdict[venue.venue_id]=[1,[venue.target.pic_id]]
			elif venue.venue_id in newdict:
				newdict[venue.venue_id][0]+=1
				newdict[venue.venue_id][1].append(venue.target.pic_id)
			else:
				pass
	sorted_vals=sorted(newdict.iteritems(), key=operator.itemgetter(1))
	sorted_vals.reverse()
	return sorted_vals[:5]
Ejemplo n.º 10
0
def suggested_venues(fsq_id='', lat='', lon='', radius=''):
    newdict = {}
    if fsq_id:
        query = record.objects.filter(
            time__lt=time(),
            time__gt=time() - 3600,
            user=user.objects.get(fsq_id=fsq_id)).order_by('venue_id')
        for venue in query:
            if venue.venue_id not in newdict:
                newdict[venue.venue_id] = [1, [venue.target.pic_id]]
            elif venue.target.pic_id not in newdict[venue.venue_id][1]:
                newdict[venue.venue_id][0] += 1
                newdict[venue.venue_id][1].append(venue.target.pic_id)
            else:
                pass
    else:
        query = record.objects.filter(time__lt=time(), time__gt=time() -
                                      3600).order_by('venue_id')
        for venue in query:
            v = venue_ll.objects.get(venue_id=venue.venue_id)
            vlat = v.lat
            vlon = v.lon
            if venue.venue_id not in newdict and haversine(
                    float(lat), float(lon), float(vlat),
                    float(vlon)) <= int(radius) / 1000:
                newdict[venue.venue_id] = [1, [venue.target.pic_id]]
            elif venue.venue_id in newdict:
                newdict[venue.venue_id][0] += 1
                newdict[venue.venue_id][1].append(venue.target.pic_id)
            else:
                pass
    sorted_vals = sorted(newdict.iteritems(), key=operator.itemgetter(1))
    sorted_vals.reverse()
    return sorted_vals[:5]
Ejemplo n.º 11
0
def getBairroFromLatLong(rddB, Lat, Long, sc):

    dLat = Decimal(Lat)
    dLong = Decimal(Long)

    tempRdd = rddB.map(lambda l: (l["Bairro"], haversine(dLong, dLat, Decimal(l["Longitude"]), Decimal(l["Latitude"]))))

    return tempRdd.min()[0]
Ejemplo n.º 12
0
def findRadius(gps, placelist):
    distance = 0
    if len(placelist) == 0:
        return 50000.0
    for place in placelist:
        km = haversine(gps, (place.getLng(), place.getLng()))
        if km > distance:
            distance = km
    return distance
Ejemplo n.º 13
0
 def distance(self, other, type):
     from utils import euclidean
     import haversine
     if type == 'euclidean':
         return euclidean(self.center[0], self.center[1], other.center[0],
                          other.center[1])
     if type == 'haversine':
         pa = (self.center[0], self.center[1])
         pb = (other.center[0], other.center[1])
         return haversine(pa, pb)
Ejemplo n.º 14
0
def create_G_Coord(G, coord_origin, coord_destination):
    G_coord = nx.Graph()
    #In this new graph, the weight of the edges is the time needed to go from one node to another.
    for e in G.edges():
        coord1, coord2, dist = (e[0].lat,
                                e[0].lon), (e[1].lat,
                                            e[1].lon), G.edges[e[0],
                                                               e[1]]['weight']
        G_coord.add_edge(coord1, coord2, weight=dist / 10)
    #In this loop, all the added edges are done by foot.
    for node in G.nodes(
    ):  #adds edges between origin, destination and the stations
        n_coord = (node.lat, node.lon)
        dist_to_og, dist_to_dest = haversine(coord_origin, n_coord), haversine(
            coord_destination, n_coord)
        G_coord.add_weighted_edges_from([
            (coord_origin, n_coord, dist_to_og / 4),
            (coord_destination, n_coord, dist_to_dest / 4)
        ])
    G_coord.add_edge(coord_origin,
                     coord_destination,
                     weight=(haversine(coord_origin, coord_destination) / 4))
    return G_coord
def find_nearest_drone(drone_list, anomaly):
    """Find the drone closest to the anomaly."""
    min_dist = 10000000000000
    closest_drone = None
    for drone in drone_list:
        if drone["DroneState"]["Status"] != "Confirming":
            if drone["DroneState"]["DroneID"] != anomaly["DroneID"]:
                drone_location = tuple([float(x) for x in drone["DroneState"]["Position"].spit(',')])
                anomaly_location = tuple([float(x) for x in anomaly["Position"].spit(',')])
                dist = haversine(drone_location, anomaly_location)
                if dist < min_dist:
                    min_dist = dist
                    closest_drone = drone
    return closest_drone
def getBairroFromLatLongDict(dictB, Lat, Long):

    dLat = Decimal(Lat)
    dLong = Decimal(Long)

    minValue = Decimal('inf')
    minBairro = "None"

    for key, value in dictB.iteritems():
        dist = haversine(dLong, dLat, Decimal(key[1]), Decimal(key[0]))
        if dist < minValue:
            minValue = dist
            minBairro = value

    return minBairro
Ejemplo n.º 17
0
def port_visit(row):


    lat = row['lat']
    lon = row['lon']

    port_list = br_ports.value
    visitors_list = []
    for i in port_list:
        distance = haversine((lat,lon), (i[1], i[0]), miles=False)
        if (distance < 0.5):
             visitors_list.append(row['sourcemmsi'])
             break

    return visitors_list
Ejemplo n.º 18
0
def get_new_state(anomaly, drone):
    """Create the new drone state based on the anomaly."""
    drone_position = tuple(
        [float(x) for x in drone["DroneState"]["Position"].split(',')])
    anomaly_position = tuple(
        [float(x) for x in anomaly["Location"].split(',')])

    if haversine(drone_position, anomaly_position) < 10:
        drone["DroneState"]["State"] = "Active"
        return drone, "ReadData"

    direction = get_direction(source=drone_position,
                              destination=anomaly_position)
    drone["DroneState"]["Direction"] = direction
    return drone, None
Ejemplo n.º 19
0
def parse_location(Location):
    coordinates_list_km = []
    location = [Location['lat'], Location['lng']]
    coordinates_list = Coordinates.objects.values_list('adress_id_id', 'lat',
                                                       'lng')

    for item in coordinates_list:
        if item[1] is not None and item[2] is not None:
            item_data = [item[1], item[2]]
            distances = haversine(tuple(location), tuple(item_data))
            tuple_data = [item[0], distances]
            coordinates_list_km.append(tuple(tuple_data))

    bubbleSort(coordinates_list_km)
    nearest_coordinates = coordinates_list_km[:NEAREST_LOCATION]
    return nearest_coordinates
def get_haversine_dist(start_point, end_point):
    """get haversine distance betweent 2 points

    Keyword arguments:
    start_point -- start point
    end_point -- end point
    """

    dist = haversine(start_point, end_point, unit='mi')

    if math.isnan(dist):
        rv_value = 100000000
    else:
        rv_value = dist

    return rv_value
def check_stores_by_geo(filter_brands, myLatLong, all_locs, within_km):
    stores_to_check = []
    stores_to_check_filtered_by_brand = []
    for loc in all_locs["locations"]:
        locLatLong = (loc["geoPoint"]["latitude"], loc["geoPoint"]["longitude"])
        distance = haversine(myLatLong, locLatLong)
        if distance <= within_km:
            # Add a distance key:value pair to the location object so that
            # locations can be sorted by distance after the list is created
            loc_distance = {"distance": distance}
            loc.update(loc_distance)
            stores_to_check.append(loc)
    if filter_brands:
        if stores_to_check:
            for store in stores_to_check:
                storeBannerId = store["storeBannerId"]
                if storeBannerId in filter_brands:
                    stores_to_check_filtered_by_brand.append(store)
        return stores_to_check_filtered_by_brand
    else:
        return stores_to_check
def whichTypesToRequestGoogle(dynamodb, lat, lng, types):
    requests = dynamodb.Table('requests')
    geohashes = adjacentHashes(geoHash(lat, lng, length=17))
    result = []
    for hash in geohashes:
        response = requests.query(
            KeyConditionExpression=Key('geohash').eq(hash.to01()))
        items = response['Items']
        result += items
    resultTypes = types.copy()
    if len(result) != 0:
        for request in result:
            requestlat = request['lat']
            requestlng = request['lng']
            type = request['type']
            radius = request['radius']
            if type in resultTypes:
                distance = haversine((lat, lng), (requestlat, requestlng))
                if (distance / float(radius)) <= .8:
                    resultTypes.remove(type)
    return resultTypes
Ejemplo n.º 23
0
def htmlemail(lat,lon, radius):
	recipients=user.objects.filter(last_lat__lt=lat+5, last_lat__gt=lat-5, last_lon__lt=lon+5, last_lon__gt=lon-5)
	recips={}
	for recipient in recipients:
		recips[recipient.fsq_id]=recipient.first_name, recipient.last_name, recipient.email
	the_records = record.objects.filter(time__lt=time(),time__gt=time()-86400)
	the_set={}
	for item in the_records:
		
		v=authenticator.userless_query("/venues/"+item.venue_id)
		vlat=v['venue']['location']['lat']
		vlon=v['venue']['location']['lng']
		venue_name=v['venue']['name']
		try: 
			venue_address=v['venue']['location']['address']+' '+v['venue']['location']['city']+', '+v['venue']['location']['state']+' '+v['venue']['location']['postalCode']
		except:
			pass
		if item.venue_id in the_set.keys():
			the_set[item.venue_id][2]+=item.target.quotient()
			the_set[item.venue_id][3]+=1
		elif haversine(float(vlon),float(vlat),float(lon),float(lat))<=int(radius):
			the_set[item.venue_id]=[venue_name,venue_address,item.target.quotient(),1]
		else:
			pass
	
	averages={}		
	for item in the_set.iteritems():
       		averages[item[0]]=[item[1][2]/item[1][3],{'female':[],'male':[]}]	

	for item in the_records:
		try:

			u=user_lookup.objects.get(pic_id=item.target.pic_id)
			g=authenticator.query("users/"+u.fsq_id, token="1A0ESOQC4W2RIGY442CJTKKFJEM04BYCEHSG0SNCVIWMKPII")
			averages[item.venue_id][1][g['user']['gender']].append(item.target.pic_id)
		except:
			pass
	for item in the_set:
		the_set[item].append(averages[item])
	return the_set
Ejemplo n.º 24
0
import requests
import json

send_url = 'http://freegeoip.net/json'
r = requests.get(send_url)
j = json.loads(r.text)
lat = j['latitude']
lon = j['longitude']

from haversine import *

current = (lat, lon)
disaster_brian_head = (-115, 38)
dist_brian_head = haversine(current, disaster_brian_head)
dist_brian_head = str(round(dist_brian_head))
print("You are " + dist_brian_head +
      " miles from the Brian Head, UT wildfire.")

disaster_esmeralda = (-80, 0)
dist_esmeralda = haversine(current, disaster_esmeralda)
dist_esmeralda = str(round(dist_esmeralda))
print("You are " + dist_esmeralda +
      " miles from the Esmeralda, Ecuador earthquake.")

disaster_teramo = (14, 43)
dist_teramo = haversine(current, disaster_teramo)
dist_teramo = str(round(dist_teramo))
print("You are " + dist_teramo + " miles from the Teramo, Italy earthquake.")

disaster_bodrum = (27, 39)
dist_bodrum = haversine(current, disaster_bodrum)
Ejemplo n.º 25
0
		def gethaversine(src,dest):
			return haversine(src,dest,miles=True)
Ejemplo n.º 26
0
        # Storing usable filtered coordinates
        lat_ff.append(lat_f)
        lon_ff.append(lon_f)
        alt_ff.append(alt_f)

        distances_pp = []
        distances_pp_f = []

    for j in range(len(lon_rz) - 1):

        # Defining cordinates of two points to messure distance
        coordinates0 = (lat_rz[j], lon_rz[j])
        coordinates1 = (lat_rz[j + 1], lon_rz[j + 1])

        # Calculating haversine distance between two points in nautical miles
        distance_pp = float(haversine(coordinates0, coordinates1, unit='nmi'))

        # Storing calculated point to point distances into a vector
        distances_pp.append(distance_pp)

        # Sum of point to point distances to obtain total distance of a flight
        distances = sum(distances_pp)

        # Next step perform a filter taking out first 6 nm of the flight
        distances2 = np.asarray(distances)

        GCD_CDGLHR = great_circle(coor_CDG, coor_LHR).nm

        altitude = alt_rz[j]
    Heff = ((distances - GCD_CDGLHR) / distances) * 100
    print(distances)
Ejemplo n.º 27
0
from vision import cono
from socket import *
from bbbgps import *
from navegacion import *
from haversine import *
import thread
import time
import sys

#arriba = [11.020289, -74.848016]
#abajo  = [11.020035, -74.848057]
#izquierda=[11.020194, -74.848468]
#derecha = [11.020127, -74.847667]
dest  = [11.01796,-74.85141]
inicio= [11.01807,-74.85141]
punto2= [11.01826,-74.85138]

#triang(dest,newpos,pos)
a= int(triang(dest,inicio,[11.01807,-74.85142]))
a= a*1600/360
print a
print haversine(inicio,[11.01807,-74.85142])*1000
Ejemplo n.º 28
0
class mgo:

    def __init__(self):
        self.Users = {}
        self.table = {}
        self.token = "21234589jkjidjfoai"
        self.messages = {}
        self.msgid = 0

    def user_exists(self,user,password):
        """Change logic to get info from db or firebase"""
        if user in self.Users:
            return True       ## Raise Exception
        else:
            return False

    def update_user(self,username,password):
        """Update username and password to db<Update this to communicate with firebase>"""
        self.Users[username] = password
        return token

    def add_user(self,username,password):
        """Add new usser to db"""

        if user_exists(username)
            pass   # later pass message user exists
        else:
            token = update_user(username,password)
            return token

    def login(self,username,password):
        """Logs user in the system <Needs to get data from firebase>"""
        if username in self.Users[username]:                  ##Update logic
            if password == self.Users[username]:
                return self.token
        if res is None:
            return None  # login failed

    def add_message(self,username,message,location):
        """Add a new message to the messages dictionary"""
        #### USE pandas or sql lite db to or get from firebase
        id = self.msgid + 1
        self.messages[id] = {"username":username,"message" : message ,"loc":location}
        self.push_to_users(id,location)

    def get_messages(location):
        """Returns all messages in given latitude and longitude range"""
        get_valid_msg_ids = get_msg_ids(location)
        res = [self.messages[id] for id in get_valid_msg_ids]
        return res

    def get_msg_ids(location):
        """Get all messges in the location range""" ###### Not needed
        ids = []
        for id in self.messages:
            if is_range(location,self.messages[id][location],radius):
                ids.append(ids)
        return ids

    def is_range(location1,location2),radius):
        """Checks if corodinates are in is_range
            Formula for Haversine Distance Algorithm between two places
            R = earth’s radius (mean radius = 6,371km)
            Δlat = lat2− lat1
            Δlong = long2− long1
            a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2)
            c = 2.atan2(√a, √(1−a))
            d = R.c
        """
        distance = haversine(coord1, coord2) * 1000
        if distance <= radius:
            return True
        else:
            return False
Ejemplo n.º 29
0
def solve(grid,
          start,
          goal,
          solver=0,
          ntype=4,
          trace=False,
          currentsGrid_u=None,
          currentsGrid_v=None,
          geotransform=None,
          targetSpeed_mps=1,
          timeOffset=0,
          pixelsize_m=1,
          distMeas="haversine"):

    solvers = ["dijkstra", "astar"]
    if solver >= len(solvers):
        print("Invalid solver ID {}".format(solver_id))
        exit(-1)

    rows, cols = grid.shape
    frontier = PriorityQueue()
    frontier.put(start, 0)
    came_from = {}
    cost_so_far = {}
    time_so_far = {}
    came_from[start] = None
    cost_so_far[start] = 0
    time_so_far[start] = timeOffset

    tgrid = None
    if trace:
        tgrid = grid.copy()

    if distMeas == "haversine":
        # Lat, lon of goal
        g_latlon = grid2world(goal[0], goal[1], geotransform, rows)

    # Explore
    while not frontier.empty():
        current = frontier.get()

        if distMeas == "haversine":
            c_latlon = grid2world(current[0], current[1], geotransform, rows)

        if trace:
            tgrid[current] = 0.25

        # Check if goal
        if current == goal:
            break
        # Add suitable neighbors
        neighbors = getNeighbors(current, rows, cols, grid, ntype)

        for next in neighbors:
            if next[0] < 0 or next[1] < 0 or next[0] >= rows or next[1] >= cols:
                continue
            if grid[next] != 0:
                continue

            if distMeas == "haversine":
                n_latlon = grid2world(next[0], next[1], geotransform, rows)
                dist = haversine.haversine(c_latlon, n_latlon) * 1000
            elif distMeas == "euclidean-scaled":
                dist = pow((pow(current[0] - next[0], 2) +
                            pow(current[1] - next[1], 2)), 0.5) * pixelsize_m
            elif distMeas == "euclidean":
                dist = pow((pow(current[0] - next[0], 2) +
                            pow(current[1] - next[1], 2)), 0.5)

            # Cost
            if currentsGrid_u is None:
                et = time_so_far[current] + (dist / targetSpeed_mps)
                # Distance cost
                new_cost = cost_so_far[current] + dist
            else:
                # Energy cost
                work, et = calcWork(current,
                                    next,
                                    currentsGrid_u,
                                    currentsGrid_v,
                                    targetSpeed_mps,
                                    geotransform=geotransform,
                                    timeIn=time_so_far[current],
                                    pixelsize_m=pixelsize_m,
                                    distMeas=distMeas)
                new_cost = cost_so_far[current] + work

            update = False
            if next not in cost_so_far:
                update = True
            else:
                if new_cost < cost_so_far[next]:
                    update = True
            if update:
                cost_so_far[next] = new_cost
                if solver == 1:  # A*
                    if distMeas == "haversine":
                        priority = new_cost + (haversine(n_latlon, g_latlon) *
                                               1000)
                    elif distMeas == "euclidean-scaled":
                        priority = new_cost + pow(
                            (pow(next[0] - goal[0], 2) +
                             pow(next[1] - goal[1], 2)), 0.5) * pixelsize_m
                    elif distMeas == "euclidean":
                        priority = new_cost + pow(
                            (pow(next[0] - goal[0], 2) +
                             pow(next[1] - goal[1], 2)), 0.5)
                else:  # Default: dijkstra
                    priority = new_cost

                frontier.put(next, priority)
                came_from[next] = current
                time_so_far[next] = et

    # Reconstruct path
    current = goal
    path = []

    while current != start:
        if trace:
            tgrid[current] = 1.5
        path.append(current)
        current = came_from[current]
    if trace:
        tgrid[start] = 0.5
    path.append(start)
    path.reverse()

    return path, tgrid, cost_so_far[goal], time_so_far[goal]
Ejemplo n.º 30
0
def geojson_haversine(geojson_tuple_a, geojson_tuple_b, haversine, **kwargs):
    flipped_a = geojson_tuple_a[1], geojson_tuple_a[0]
    flipped_b = geojson_tuple_b[1], geojson_tuple_b[0]
    return haversine(flipped_a, flipped_b, **kwargs)
Ejemplo n.º 31
0
    alt = flights['alt']
    xalt = np.arange(alt.size)
    new_xalt = np.linspace(xalt.min(), xalt.max(), CHUNK_SIZE)
    alt_rz = sp.interpolate.interp1d(xalt, alt, kind='slinear')(new_xalt)
    x,y = m(lon_rz,lat_rz)
    m.plot(*(x, y), color = 'b', linewidth=0.1)


    

    for j in range(len(lon_rz)-1):

        # Defining cordinates of two points to messure distance      
        coordinates0 = (lat_rz[j],lon_rz[j])
        # Calculating haversine distance between two points in nautical miles
        distance_to_AIRP1 = float(haversine(coor_AIRP1,coordinates0,unit='nmi'))
        distance_to_AIRP2 = float(haversine(coor_AIRP2,coordinates0,unit='nmi'))
        
        if distance_to_AIRP1 > 60 and distance_to_AIRP2 > 60:

            lon_f = [lon_rz[j]]
            lat_f = [lat_rz[j]]
            alt_f = [alt_rz[j]]

            # lat_teste_f = [lat_teste[j]]
            # lon_teste_f = [lon_teste[j]]
            
            lat_ff.append(lat_f)
            lon_ff.append(lon_f)
            alt_ff.append(alt_f)
Ejemplo n.º 32
0
        coords = geo_json[0]["geometry"]["coordinates"]
        myLat = coords[1]
        myLong = coords[0]
myLatLong = (myLat, myLong)

if mode == "report":
    print(f'export MYLAT="{myLat}" ; export MYLONG="{myLong}"')

stores_to_check = []

with open("locations.json") as inf:
    all_locs = json.load(inf)

for loc in all_locs["locations"]:
    locLatLong = (loc["geoPoint"]["latitude"], loc["geoPoint"]["longitude"])
    distance = haversine(myLatLong, locLatLong)
    if distance <= within_km:
        # Add a distance key:value pair to the location object so that
        # locations can be sorted by distance after the list is created
        loc_distance = {"distance": distance}
        loc.update(loc_distance)
        stores_to_check.append(loc)

if stores_to_check:
    # Sort the list of locations by distance
    stores_to_check = sorted(stores_to_check, key=lambda s: s["distance"])

store_urls = {
    "bloor": "https://www.bloorstreetmarket.ca",
    "box": "https://www.boxfoodstores.ca",
    "independent": "https://www.yourindependentgrocer.ca",
Ejemplo n.º 33
0
    lon = flights['lon']
    xlon = np.arange(lon.size)
    new_xlon = np.linspace(xlon.min(), xlon.max(), CHUNK_SIZE)
    lon_rz = sp.interpolate.interp1d(xlon, lon, kind='slinear')(new_xlon)

    alt = flights['alt']
    xalt = np.arange(alt.size)
    new_xalt = np.linspace(xalt.min(), xalt.max(), CHUNK_SIZE)
    alt_rz = sp.interpolate.interp1d(xalt, alt, kind='slinear')(new_xalt)

    for j in range(len(lon_rz) - 1):

        # Defining cordinates of two points to messure distance
        coordinates0 = (lat_rz[j], lon_rz[j])
        # Calculating haversine distance between two points in nautical miles
        distance_to_FRA = float(haversine(coor_FRA, coordinates0, unit='nmi'))
        distance_to_ITA = float(haversine(coor_ITA, coordinates0, unit='nmi'))

        if distance_to_FRA > 60 and distance_to_ITA > 60:

            lon_f = [lon_rz[j]]
            lat_f = [lat_rz[j]]
            alt_f = [alt_rz[j]]

            lat_ff.append(lat_f)
            lon_ff.append(lon_f)
            alt_ff.append(alt_f)

print(len(lat_ff))

mms = preprocessing.MinMaxScaler(feature_range=(0, 1))
Ejemplo n.º 34
0
    alt = flights['alt']
    xalt = np.arange(alt.size)
    new_xalt = np.linspace(xalt.min(), xalt.max(), CHUNK_SIZE)
    alt_rz = sp.interpolate.interp1d(xalt, alt, kind='slinear')(new_xalt)

    x, y = m(lon_rz, lat_rz)
    m.plot(*(x, y), color='b', linewidth=0.1)

    for j in range(len(lon_rz) - 1):

        # Defining cordinates of two points to messure distance
        coordinates0 = (lat_rz[j], lon_rz[j])
        # Calculating haversine distance between two points in nautical miles
        distance_to_AIRP1 = float(
            haversine(coor_AIRP1, coordinates0, unit='nmi'))
        distance_to_AIRP2 = float(
            haversine(coor_AIRP2, coordinates0, unit='nmi'))

        if distance_to_AIRP1 > 60 and distance_to_AIRP2 > 60:

            lon_f = [lon_rz[j]]
            lat_f = [lat_rz[j]]
            alt_f = [alt_rz[j]]

            # lat_teste_f = [lat_teste[j]]
            # lon_teste_f = [lon_teste[j]]

            lat_ff.append(lat_f)
            lon_ff.append(lon_f)
            alt_ff.append(alt_f)