Пример #1
0
def find_segment(trip_record, session, test_pair=None):
    if test_pair:
        me_loc = test_pair
    else:
        me_loc = (trip_record.location_lat, trip_record.location_lng)

    trip = session.query(db.TripRecord, db.Trip).join(
        db.Trip).filter(db.Trip.id == trip_record.trip_id).first()[1]

    origin_station = session.query(
        db.Station).filter(db.Station.id == trip.origin_station_id).first()
    destination_station = session.query(db.Station).filter(
        db.Station.id == trip.destination_station_id).first()

    # print "origin_station: %s" % origin_station
    # print "destination_station: %s" % destination_station

    all_stations = session.query(db.Station).filter(
        db.Station.route_id == origin_station.route_id).all()
    closest_station = None
    closest_distance_so_far = 100
    for station in all_stations:

        station_loc = (station.location_lat, station.location_lng)
        miles = dist(me_loc, station_loc).miles
        if miles < closest_distance_so_far:
            closest_station = station
            closest_distance_so_far = miles

    surrounding_stations = surrounding_station(session, closest_station)
    surround_station_1 = surrounding_stations[1]
    surround_station_2 = surrounding_stations[0]

    # print("surround_station_1: {}".format(surround_station_1.loc()))
    # print("surround_station_2: {}".format(surround_station_2.loc()))
    if dist(surround_station_1.loc(), destination_station.loc()).miles < dist(
            surround_station_2.loc(), destination_station.loc()).miles:
        surround_station_ahead = surround_station_1
        surround_station_behind = surround_station_2
    else:
        surround_station_ahead = surround_station_2
        surround_station_behind = surround_station_1

    if dist(me_loc, destination_station.loc()).miles < dist(
            closest_station.loc(), destination_station.loc()).miles:
        return closest_station, surround_station_ahead
    else:
        return surround_station_behind, closest_station
Пример #2
0
def score(dish, user, user_location, params):
    prefered_foodtypes = user.preferedFoodTypes
    restaurant = dish.restaurant

    hist = sum(prefered_foodtypes[t.name] for t in dish.foodType.all())

    if restaurant.acceptance is not None:
        acceptance = restaurant.acceptance/params["avg_accept"]
    else:
        acceptance = params["min_accept"]/params["avg_accept"]

    if restaurant.rejectance is not None:
        rejectance = restaurant.rejectance/params["avg_reject"]
    else:
        rejectance = params["max_reject"]/params["avg_reject"]

    if restaurant.delay is not None:
        delays = restaurant.delay/params["avg_delay"]
    else:
        delays = params["max_delay"]/params["avg_delay"]

    if restaurant.ordersNumber:
        ordersNumber = restaurant.ordersNumber/params["avg_orders"]
    else:
        ordersNumber = params["min_orders"]/params["avg_orders"]
    
    if user_location:
        distance = dist((restaurant.latitude, restaurant.longitude), (user_location["latitude"], user_location["longitude"])).km
    else:
        distance = 0
        
    return hist + acceptance + ordersNumber - rejectance  - 0.5 * delays - distance
Пример #3
0
 def set_linkDelay(self):
     SPEED_OF_LIGHT = 299792458  # meter per second
     PROPAGATION_FACTOR = 0.77  # https://en.wikipedia.org/wiki/Propagation_delay
     for e in self.net_x.edges(data=True):
         link_delay = e[2].get("LinkDelay", None)
         # As edges are undirectional, only LinkFwdCap determines the available data rate
         # link_fwd_cap = e[2].get("LinkFwdCap", 1000)
         delay = 3
         if link_delay is None:
             n1 = self.net_x.nodes(data=True)[e[0]]
             n2 = self.net_x.nodes(data=True)[e[1]]
             n1_lat, n1_long = n1.get("Latitude",
                                      None), n1.get("Longitude", None)
             n2_lat, n2_long = n2.get("Latitude",
                                      None), n2.get("Longitude", None)
             if not (n1_lat is None or n1_long is None or n2_lat is None
                     or n2_long is None):
                 distance = dist((n1_lat, n1_long),
                                 (n2_lat, n2_long)).meters  # in meters
                 # round delay to int using np.around for consistency with emulator
                 delay = int(
                     np.around((distance / SPEED_OF_LIGHT * 1000) *
                               PROPAGATION_FACTOR))  # in milliseconds
         else:
             delay = link_delay
         e[2]["LinkDelay"] = delay
Пример #4
0
def trip_movement(session, trip, stamp, delta):
    '''
    Answers the question: between stamp and stamp-delta, how far did trip move?
    :param session: The database session to operate with
    :param trip: The trip in question
    :param stamp: A timestamp
    :param delta: A time delta (say, 5 minutes)
    :return: Movement in feet
    '''

    stamp_prev = stamp - delta

    stamp_record = session.query(db.TripRecord)\
                        .filter(db.TripRecord.trip_id == trip.id)\
                        .filter(db.TripRecord.stamp < stamp)\
                        .order_by(db.TripRecord.stamp.desc())\
                        .limit(1)\
                        .first()

    stamp_prev_record = session.query(db.TripRecord)\
                        .filter(db.TripRecord.trip_id == trip.id)\
                        .filter(db.TripRecord.stamp < stamp_prev)\
                        .filter(db.TripRecord.stamp > stamp_prev - datetime.timedelta(minutes=3))\
                        .order_by(db.TripRecord.stamp.desc())\
                        .limit(1)\
                        .first()

    if not stamp_prev_record:
        return -1

    stamp_record_loc = (stamp_record.location_lat, stamp_record.location_lng)
    stamp_prev_record_loc = (stamp_prev_record.location_lat,
                             stamp_prev_record.location_lng)

    return dist(stamp_record_loc, stamp_prev_record_loc).feet
Пример #5
0
def trip_movement(session, trip, stamp, delta):
    '''
    Answers the question: between stamp and stamp-delta, how far did trip move?
    :param session: The database session to operate with
    :param trip: The trip in question
    :param stamp: A timestamp
    :param delta: A time delta (say, 5 minutes)
    :return: Movement in feet
    '''

    stamp_prev = stamp - delta

    stamp_record = session.query(db.TripRecord)\
                        .filter(db.TripRecord.trip_id == trip.id)\
                        .filter(db.TripRecord.stamp < stamp)\
                        .order_by(db.TripRecord.stamp.desc())\
                        .limit(1)\
                        .first()

    stamp_prev_record = session.query(db.TripRecord)\
                        .filter(db.TripRecord.trip_id == trip.id)\
                        .filter(db.TripRecord.stamp < stamp_prev)\
                        .filter(db.TripRecord.stamp > stamp_prev - datetime.timedelta(minutes=3))\
                        .order_by(db.TripRecord.stamp.desc())\
                        .limit(1)\
                        .first()

    if not stamp_prev_record:
        return -1

    stamp_record_loc = (stamp_record.location_lat, stamp_record.location_lng)
    stamp_prev_record_loc = (stamp_prev_record.location_lat, stamp_prev_record.location_lng)

    return dist(stamp_record_loc, stamp_prev_record_loc).feet
Пример #6
0
 def near(request, pk):
     limit = 5
     user = User.objects.get(pk=pk)
     lat = user.location["latitude"]
     lng = user.location["longitude"]
     restaurants = sorted(Restaurant.objects.all(), 
                          key=lambda r: dist((r.chef.latitude, r.chef.longitude), (lat, lng)).km)[:limit]
     return response(restaurants, 'restaurant', request)
Пример #7
0
def trip_length(longitude, latitude):
    # caution: vincenty(dist) function takes a (latitude, longitude) pair!
    xy = np.array([latitude, longitude]).T.reshape(-1, 2)

    total_length = 0.
    for start, stop, in zip(xy[:-1], xy[1:]):
        total_length += dist(start, stop).km

    return total_length
Пример #8
0
def find_segment(trip_record, session, test_pair=None):
    if test_pair:
        me_loc = test_pair
    else:
        me_loc = (trip_record.location_lat, trip_record.location_lng)

    trip = session.query(db.TripRecord, db.Trip).join(db.Trip).filter(db.Trip.id == trip_record.trip_id).first()[1]

    origin_station = session.query(db.Station).filter(db.Station.id == trip.origin_station_id).first()
    destination_station = session.query(db.Station).filter(db.Station.id == trip.destination_station_id).first()

    # print "origin_station: %s" % origin_station
    # print "destination_station: %s" % destination_station

    all_stations = session.query(db.Station).filter(db.Station.route_id == origin_station.route_id).all()
    closest_station = None
    closest_distance_so_far = 100
    for station in all_stations:

        station_loc = (station.location_lat, station.location_lng)
        miles = dist(me_loc, station_loc).miles
        if miles < closest_distance_so_far:
            closest_station = station
            closest_distance_so_far = miles

    surrounding_stations = surrounding_station(session, closest_station)
    surround_station_1 = surrounding_stations[1]
    surround_station_2 = surrounding_stations[0]

    # print("surround_station_1: {}".format(surround_station_1.loc()))
    # print("surround_station_2: {}".format(surround_station_2.loc()))
    if dist(surround_station_1.loc(), destination_station.loc()).miles < dist(surround_station_2.loc(),
                                                                              destination_station.loc()).miles:
        surround_station_ahead = surround_station_1
        surround_station_behind = surround_station_2
    else:
        surround_station_ahead = surround_station_2
        surround_station_behind = surround_station_1

    if dist(me_loc, destination_station.loc()).miles < dist(closest_station.loc(), destination_station.loc()).miles:
        return closest_station, surround_station_ahead
    else:
        return surround_station_behind, closest_station
Пример #9
0
def main():
    w, c = login.doInteractiveLogin()
    conf = c._config['location_explorer']

    if 'max_place_count' in conf:
        max_place_count = conf['max_place_count']
    else:
        max_place_count = -1
    if 'search_center' in conf:
        search_cond = True
        search_center = conf['search_center']
        search_radius = conf['search_radius']
    else:
        search_cond = False
    if 'archive_size' in conf:
        archive_size = conf['archive_size']
    else:
        archive_size = None
    output_filename = conf['output_filename']
    origin = conf['origin']

    archive_count = 0
    location_count = 0
    places = []
    queue = [(0, (origin, ''))]
    processed = {origin}

    while queue and (max_place_count == -1 or len(places) < max_place_count):
        nx = heapq.heappop(queue)[1]
        pid = nx[0]
        location_count += 1
        print('processing %d location %s...' % (location_count, pid))
        loc = w.getPlaceById(pid)
        if search_cond and \
            dist(tuple(search_center), (loc.latitude, loc.longitude)).meters > \
                search_radius:
            continue
        places.append(loc)
        if archive_size and len(places) >= archive_size:
            writeOut(output_filename, archive_count, places)
            places = []
            archive_count += 1
        for p in loc.queryNearby():
            if p['id'] in processed: continue
            processed.add(p['id'])
            heapq.heappush(queue, ( \
                -p['weibo_count'], \
                ( p['id'], p['name'] ) \
            ))

    writeOut(output_filename, archive_count, places, queue)
    print('total %d locations found' % location_count)
Пример #10
0
def buscar_cercanas(n, coord, estaciones):
    nombres_cercanas = distancias = []

    for i in estaciones:
        # Calcular la distancia entre la estación y el punto de interés
        distancia = dist((estaciones[i]['Lat'], estaciones[i]['Long']), coord).km
        # Si encontramos una mejora estación o no hemos llegado a n estaciones
        if distancia < max(distancias) or len(nombres_cercanas) < n:
            # Si ya tenemos una lista de n estaciones, quitar la estación la más lejana
            if len(nombres_cercanas) >= n:
                índice = distancias.index(max(distancias))
                nombres_cercanas.pop(índice)
                distancias.pop(índice)
            # Añadir la nueva estación
            distancias.append(distancia)
            nombres_cercanas.append(estaciones[i]['Estación'])

    # Leer los datos de las n estaciones más cercanas
    estaciones_cercanas = []
    for i in nombres_cercanas:
        estaciones_cercanas.append(
            cargar_estación(os.path.join('Proyectos', 'Clima', i, '.csv'), generar=False)[0]
        )
    return estaciones_cercanas
Пример #11
0
    lat_lon[place] = (loc.latitude, loc.longitude)
    #print("okay")

#getting your location based on ip address

g = geocoder.ip('me')
c = geolocator.reverse((g.latlng))
print("your location: " + str(c.raw['address']['country']))
loc = geolocator.geocode(c.raw['address']['country'])
my_loc = tuple(g.latlng)

#calculating nearest country in wikipedia page to your country

print("calculating nearest country in wikipedia page to your country")

distances = {}

for loc, coord in lat_lon.items():
    sleep(1)
    distance = dist(coord, my_loc).km
    distances[loc] = distance

x = min(distances.values())

your_place = ""
for name, d in distances.items():
    if d == x:
        print("nearest country: ", name)
        your_location = name.replace(" ", "_")
        your_place = name
Пример #12
0
for d in data:
    t2 = arrow.get(d[3])
    if t2 > t1.ceil("day"):
        id += 1
        print("found night {}".format(id))
        p = kml.Placemark(ns, "%s" % id, "nuit_%s" % id, "nuit numéro %s" % id)
        p.geometry = Point(lon, lat)
        docNights.append(p)
        t1 = t2
    lat = d[1]
    lon = d[2]
lat = data[0][1]
lon = data[0][2]
id = 0
for d in data:
    # print(dist((d[2],d[1]),(lon,lat)).kilometers)
    if dist((d[2], d[1]), (lon, lat)).kilometers > 10:
        p = kml.Placemark(ns, "%s" % id, "km_%s" % id, "borne numéro %s" % id)
        p.geometry = Point(lon, lat)
        docRoute.append(p)
        lat = d[1]
        lon = d[2]

fid = open("{}_nights.kml".format(args.title), "w")
fid.write(rootNights.to_string(prettyprint=True))
fid.close()

fid = open("{}_route.kml".format(args.title), "w")
fid.write(rootRoute.to_string(prettyprint=True))
fid.close()
Пример #13
0
def read_network(file, node_cap=None, link_cap=None):
    """
    Read the GraphML file and return list of nodes and edges.
    """
    SPEED_OF_LIGHT = 299792458  # meter per second
    PROPAGATION_FACTOR = 0.77  # https://en.wikipedia.org/wiki/Propagation_delay

    if not file.endswith(".graphml"):
        raise ValueError("{} is not a GraphML file".format(file))
    graphml_network = nx.read_graphml(file, node_type=int)
    networkx_network = nx.Graph()

    #  Setting the nodes of the NetworkX Graph
    for n in graphml_network.nodes(data=True):
        node_id = "pop{}".format(n[0])
        cap = n[1].get("NodeCap", None)
        if cap is None:
            cap = node_cap
            log.warning(
                "NodeCap not set in the GraphML file, now using default NodeCap for node: {}"
                .format(n))
        node_type = n[1].get("NodeType", "Normal")
        node_name = n[1].get("label", None)
        if cap is None:
            raise ValueError(
                "No NodeCap. set for node{} in file {} (as cmd argument or in graphml)"
                .format(n, file))
        # Adding a Node in the NetworkX Graph
        # {"id": node_id, "name": node_name, "type": node_type, "cap": cpu})
        # Type of node. For now it is either "Normal" or "Ingress"
        # Init 'remaining_resources' to the node capacity
        networkx_network.add_node(node_id,
                                  name=node_name,
                                  type=node_type,
                                  cap=cap,
                                  available_sf={},
                                  remaining_cap=cap)

    # set links
    # calculate link delay based on geo positions of nodes;

    for e in graphml_network.edges(data=True):
        # Check whether LinkDelay value is set, otherwise default to None
        source = "pop{}".format(e[0])
        target = "pop{}".format(e[1])
        link_delay = e[2].get("LinkDelay", None)
        # As edges are undirectional, only LinkFwdCap determines the available data rate
        link_fwd_cap = e[2].get("LinkFwdCap", link_cap)
        if e[2].get("LinkFwdCap") is None:
            log.warning(
                "Link {} has no capacity defined in graphml file. So, Using the default capacity"
                .format(e))
        # Setting a default delay of 3 incase no delay specified in GraphML file
        # and we are unable to set it based on Geo location
        delay = 3
        if link_delay is None:
            n1 = graphml_network.nodes(data=True)[e[0]]
            n2 = graphml_network.nodes(data=True)[e[1]]
            n1_lat, n1_long = n1.get("Latitude",
                                     None), n1.get("Longitude", None)
            n2_lat, n2_long = n2.get("Latitude",
                                     None), n2.get("Longitude", None)
            if n1_lat is None or n1_long is None or n2_lat is None or n2_long is None:
                log.warning(
                    "Link Delay not set in the GraphML file and unable to calc based on Geo Location,"
                    "Now using default delay for edge: ({},{})".format(
                        source, target))
            else:
                distance = dist((n1_lat, n1_long),
                                (n2_lat, n2_long)).meters  # in meters
                # round delay to int using np.around for consistency with emulator
                delay = int(
                    np.around((distance / SPEED_OF_LIGHT * 1000) *
                              PROPAGATION_FACTOR))  # in milliseconds
        else:
            delay = link_delay

        # Adding the undirected edges for each link defined in the network.
        # delay = edge delay , cap = edge capacity
        networkx_network.add_edge(source,
                                  target,
                                  delay=delay,
                                  cap=link_fwd_cap,
                                  remaining_cap=link_fwd_cap)

    # setting the weight property for each edge in the NetworkX Graph
    # weight attribute is used to find the shortest paths
    for edge in networkx_network.edges.values():
        edge['weight'] = weight(edge['cap'], edge['delay'])
    # Setting the all-pairs shortest path in the NetworkX network as a graph attribute
    shortest_paths(networkx_network)

    # Filter ingress nodes
    ing_nodes = []
    for node in networkx_network.nodes.items():
        if node[1]["type"] == "Ingress":
            ing_nodes.append(node)

    return networkx_network, ing_nodes
Пример #14
0
root = kml.KML()
ns = '{http://www.opengis.net/kml/2.2}'

# Create a KML Document and add it to the KML root object
doc = kml.Document(ns, '1', 'test document', 'test gps data extraction')
root.append(doc)
# Create a KML Folder and nest it in the first Folder
f = kml.Folder(ns, 'nested-fid', 'nested f name', 'nested f description')
doc.append(f)

lon1 = data[0][2]
lat1 = data[0][1]
p           = kml.Placemark(ns, "0","%s"%data[0][3], 'description')
p.geometry  = Point(lon1,lat1)
f.append(p)

for d in data:
    lon2 = d[2]
    lat2 = d[1]
    print(dist((lon1,lat1),(lon2,lat2)).kilometers)
    if dist((lon1,lat1),(lon2,lat2)).kilometers>10: 
        p           = kml.Placemark(ns, "%s"%d[0],"%s"%d[3], 'description')
        p.geometry  = Point(lon2,lat2)
        f.append(p)
        lon1=lon2
        lat1=lat2

fid = open("/tmp/test.kml","w")
fid.write(root.to_string(prettyprint=True))
fid.close()
Пример #15
0
    def inic(símismo, datos):
        if datos:  # Si se especificaron datos, leerlos
            datos_crudos = símismo.leer_documento(datos)
            for núm, nombre in enumerate(datos_crudos['Parcela']):
                nueva_parcela = Parcela(
                    nombre=nombre,
                    directorio=símismo.directorio,
                    suelos_común=símismo.dic['suelos_común'],
                    variedades_común=símismo.dic['variedades_común'],
                    redes_común=símismo.dic['redes_común'])

                def leer_vars(obj):
                    for var in obj:
                        if type(var) is dict:
                            leer_vars(obj[var])
                        if var in datos_crudos:
                            try:
                                valor = float(datos_crudos[var][núm])
                            except ValueError:
                                valor = datos_crudos[var][núm]
                            obj[var] = valor

                leer_vars(nueva_parcela.dic)

                símismo.parcelas[nombre] = nueva_parcela

        if símismo.dic[
                'redes_común']:  # Si compartemos redes, buscar la red en el lugar común
            símismo.red = Red(nombre=símismo.dic['RedAE'])
        else:  # Si no compartemos, buscarla en el directorio del paisaje actual
            if os.path.isfile(
                    os.path.join(símismo.directorio, símismo.nombre + '.red')):
                símismo.red = Red(nombre=símismo.dic['RedAE'])
            else:  # Si no lo encontramos allí, hacer una copia local de la versión en el lugar común
                dirección = os.path.join('Proyectos', 'Personales', 'Redes',
                                         símismo.nombre + '.red')
                if os.path.isfile(dirección):
                    with open(dirección) as d:
                        doc = d.readlines()
                    with open(
                            os.path.join(símismo.directorio,
                                         símismo.nombre + '.red'), 'w') as d:
                        d.write(doc)
                else:
                    print('No se encontró la red agroecológica %s.' %
                          (símismo.nombre + '.red'))

        # Poner los suelos, variedades, y redes a la parcela
        for itema in símismo.parcelas.items():
            parcela = itema[1]  # Sacar el objeto representando la parcela
            if símismo.dic['suelos_común']:
                # Si todavía no hemos creado un objeto para el suelo en cuestión:
                if parcela.dic['Suelo'] not in símismo.suelos:
                    símismo.suelos[parcela.dic['Suelo']] = Suelo(
                        nombre=parcela.dic['Suelo'],
                        directorio=símismo.directorio)

                # Establecer una referencia entre el suelo apropiade del diccionario de suelos y el suelo de la parcela
                parcela.suelo = símismo.suelos[parcela.dic['Suelo']]

            # Las variedades
            if símismo.dic['variedades_común']:
                # Si todavía no hemos creado un objeto para la variedad en cuestión:
                if parcela.dic['Variedad'] not in símismo.variedades:
                    símismo.variedades[parcela.dic['Variedad']] = Variedad(
                        nombre=parcela.dic['Variedad'],
                        directorio=símismo.directorio)

                # Establecer una referencia entre la variedad del diccionario de variedades y la variedad de la parcela
                parcela.variedad = símismo.variedades[parcela.dic['Variedad']]

            # El clima
            meteo_temp = Diario(coord=(parcela.dic['Lat'],
                                       parcela.dic['Long']))
            meteo_temp.buscar(símismo.dic['fecha_inic'],
                              símismo.dic['fecha_fin'])
            # Si todavía no hemos creado un objeto para la meteorología en cuestión:
            if meteo_temp.nombre not in símismo.meteos:
                símismo.meteos[meteo_temp.nombre] = Diario(
                    nombre=parcela.dic['Variedad'])
            parcela.meteo = símismo.meteos[meteo_temp.nombre]

            # Las redes agroecológicas
            parcela.red = símismo.red

            # Calcular distancias entre parcelas
            for otro_itema in símismo.parcelas.items():
                otra_parcela = otro_itema[1]
                símismo.distancias[itema[0]][otro_itema[1]] = dist(
                    (parcela.dic["Lat"], parcela.dic["Long"]),
                    (otra_parcela.dic["Lat"], otra_parcela.dic["Long"]))