def distance_list(origin, destination):
    try:
        origin = "NTU+" + origin + "+Singapore"
        pass
    except:
        pass
    for i in range(len(destination)):
        try:
            destination[i] = "NTU+" + destination[i].replace(
                " ", "+") + "+Singapore"
        except:
            pass

    gmaps = Client(key=API_KEY)
    matrix = gmaps.distance_matrix(origin, destination, mode="walking")
    list = []
    for i in range(len(matrix['rows'][0]['elements'])):
        if matrix['rows'][0]['elements'][i][
                'status'] == 'ZERO_RESULTS':  # Check for infeasible routes
            list.append(
                None
            )  # If there is no viable routes, distance is returned as None
        else:
            list.append(
                int(
                    float(matrix['rows'][0]['elements'][i]['distance']['text']
                          [:len(matrix['rows'][0]['elements'][i]['distance']
                                ['text']) - 3]) * 1000))
    return list
Пример #2
0
def get_single_data_point(
    gmaps: googlemaps.Client,
    start: str,
    end: str,
    departure_time: dt.datetime,
    traffic_model: str,
) -> int:
    '''
    params:
        gmaps: google maps client object
        start, end: addresses for home and work (strings)
        departure_time: datetime object
        traffic_model: one of 'optimistic', 'best_guess', 'pessimistic'
    return 
        duration_in_traffic (int) in seconds
    Note: will be called ~1000 times; Google maps API daily free request limit is 2500
    '''
    result = gmaps.distance_matrix(start,
                                   end,
                                   mode='driving',
                                   departure_time=departure_time,
                                   traffic_model=traffic_model)
    # return preditced travel time in seconds
    try:
        return result['rows'][0]['elements'][0]['duration_in_traffic']['value']
    except:
        return -1
def obtain_commute_times(origin, destination, time_range):
    '''
    This function will obtain the commute times from origin to destination 
    '''
    from googlemaps import Client
    from datetime import datetime, timedelta
    import numpy as np
    import time

    API_key = 'AIzaSyCJUNcLHEBBi8pd2CyYzSzlFZFvb_vOhaU'
    gmaps = Client(API_key)

    # The time interval on x-axis between each api call/data point
    time_interval = 600  # Seconds, or 10 minutes
    t_int_minutes = time_interval / 60

    # This gives the nearest wednesday at midnight to the current data
    today = datetime.today()
    today_ind = today.weekday()
    day_modif = 16 - today_ind  # 16 to get the nearest wednesday, two weeks from now
    wednesday_mid = today + timedelta(days=day_modif,
                                      seconds=-today.second,
                                      minutes=-today.minute,
                                      hours=-today.hour)
    print(wednesday_mid)
    wed_mid_int = int(wednesday_mid.strftime("%s"))

    # This converts the start time into an integer time on monday
    hour_range_depart = time_range

    # This builds your time array based on the start time and end time monday

    start_time = wed_mid_int + hour_range_depart[0] * 3600
    end_time = wed_mid_int + hour_range_depart[1] * 3600
    time_interval = int((end_time - start_time) / time_interval)

    # Use linspace to make our integer times
    times = np.linspace(start_time, end_time, time_interval + 1,
                        endpoint=True).astype(np.int)

    org = origin
    dest = destination

    org_mat = [org]
    dest_mat = [dest]

    commute_times = [] * len(times)

    for i in range(0, len(times)):
        dept_time_iter = times[i]
        directions = gmaps.distance_matrix(org_mat,
                                           dest_mat,
                                           departure_time=dept_time_iter,
                                           traffic_model='pessimistic')
        commute_time = directions['rows'][0]['elements'][0][
            'duration_in_traffic']['value']
        commute_times.append(commute_time)

    return commute_times
Пример #4
0
def calculate_distance():
    """Calculate the distance for all apartments that were not calculated yet.

    - Query all pins;
    - Query all apartments not yet calculated;
    - Call Google Maps Distance Matrix;
    - Save the results.
    """
    maps = Client(key=read_from_keyring(PROJECT_NAME, 'google_maps_api_key'))
    assert maps
    tomorrow = date.today() + timedelta(0 if datetime.now().hour < 9 else 1)
    morning = datetime(tomorrow.year, tomorrow.month, tomorrow.day, 9, 0)
    LOGGER.warning('Next morning: %s', morning)

    empty = dict(text='ERROR', value=-1)
    for pin in Pin.query.all():
        while True:
            apartments = Apartment.query.outerjoin(Distance, and_(
                Apartment.id == Distance.apartment_id, Distance.pin_id == pin.id)) \
                .filter(Apartment.active.is_(True), Distance.apartment_id.is_(None)).limit(20)
            search = {
                apartment.id: apartment.address
                for apartment in apartments.all()
            }
            if not search:
                LOGGER.warning('All distances already calculated for %s', pin)
                break

            ids = list(search.keys())
            origin_addresses = list(search.values())
            LOGGER.warning('Calling Google Maps for %s', pin)
            try:
                result = maps.distance_matrix(origin_addresses, [pin.address],
                                              mode='transit',
                                              units='metric',
                                              arrival_time=morning)
            except HTTPError as err:
                LOGGER.error('Error on Google Distance Matrix: %s', str(err))
                continue
            LOGGER.warning('Processing results from Google Maps for %s', pin)
            for row_dict in [row['elements'][0] for row in result['rows']]:
                duration, distance = row_dict.get('duration',
                                                  empty), row_dict.get(
                                                      'distance', empty)
                meters = distance.get('value')
                apt_id = ids.pop(0)
                model = Distance.create(apartment_id=apt_id,
                                        pin_id=pin.id,
                                        json=row_dict,
                                        meters=meters,
                                        minutes=round(
                                            duration.get('value') / 60))
                if meters <= 0:
                    LOGGER.error('Error calculating %s: %s', model,
                                 json.dumps(row_dict))
                else:
                    LOGGER.warning('Calculating %s', model)
Пример #5
0
def distance_between(origins: list, destination: str):
    if not origins or not destination:
        return None
    client = Client(key=GOOGLE_API_KEY)
    try:
        destinations = [destination]
        units = 'metric'
        raw = client.distance_matrix(origins, destinations, units=units)
        return [_extract_row_data(row) for row in raw['rows']]
    except Exception as e:
        return None
Пример #6
0
    def calcular_distancia(self):
        primera_ubicacion = self.ui.txt_primera_ubicacion.text().strip()

        if len(primera_ubicacion):
            segunda_ubicacion = self.ui.txt_segunda_ubicacion.text().strip()

            if len(segunda_ubicacion):
                cliente = Client(key='AIzaSyDCugQUG_8vYlrXz2URJEUgYKuOF4miIcU')

                resultado = cliente.distance_matrix(primera_ubicacion, segunda_ubicacion)

                distancia = resultado['rows'][0]['elements'][0]['distance']['text']

                self.ui.txt_distancia.setText(distancia)
            else:
                self.mensaje.setIcon(QMessageBox.Warning)
                self.mensaje.setText('El campo Segunda ubicación es obligatorio.')
                self.mensaje.exec_()
        else:
            self.mensaje.setIcon(QMessageBox.Warning)
            self.mensaje.setText('El campo Primera ubicación es obligatorio.')
            self.mensaje.exec_()
Пример #7
0
    def getDeliveryTime(ori, dest):

        """ Get routing time based on coordinates for origin and destination using HERE routing API.

        Returns:
            string: Returns delivery time and distance calculated with Here API.
        """

        start_time = time.time()

        routingApi = herepy.RoutingApi(os.getenv("HERE_KEY"))
        gm = GoogleMaps(os.getenv("GOOGLE_KEY"))

        try:
            response = routingApi.truck_route(ori.coords[::-1], dest.coords[::-1], [herepy.RouteMode.truck, herepy.RouteMode.fastest]).as_dict()
            distance = response.get('response').get('route')[0].get('summary').get('distance') / 1000
        except herepy.error.HEREError:
            try:
                response = gm.distance_matrix(ori.coords[::-1], dest.coords[::-1], mode="driving", departure_time=dt.datetime.now(), traffic_model="pessimistic")
                distance = response.get('rows')[0].get('elements')[0].get('distance').get('value') / 1000
            except Exception as e:
                capture_exception(e)
                raise e

        if distance < 51:
            deltime = 6
        elif distance > 50 and distance < 701:
            deltime = 24
        elif distance > 700 and distance < 1400:
            deltime = 48
        else:
            deltime = 72

        print('--- Tiempo de ejecucion calcDeliveryTime: {} segundos ---'.format((time.time() - start_time)))

        return deltime, distance
Пример #8
0
 d2=(yUTM2-yUTM1)**2
 d3=d1+d2
 distance=d3**0.5
 distance=distance/1000
 print(distance)
 #5.5.2. Now if the distance is below a given threshold, I will allow the computation
 if distance<threshold:
     coordCOMP=xcoord2, ycoord2
     #5.6. Increase counter of distance by 1.
     countdistance=countdistance+1
     module10=countdistance%100
     if module10==0:
         #5.7. Every 100 queries we sleep for 10 seconds.
         time.sleep(10)
     #5.8 Walking distance.
     algoprueba=gmaps.distance_matrix(coordORIG,coordCOMP,mode=MODE)
     #5.9 Driving distance stored in a set of dictionaries and lists.
     #We need to extract it in seven steps.
     algo2=algoprueba['rows']
     algo3=algo2[0]
     algo4=algo3['elements']
     algo5=algo4[0]
     status=algo5['status']
     #5.10 If status ok, compute distance.
     if status=='OK':
         algo6=algo5['distance']
         algo7=algo6['value']
     else:
         algo7='NA'
         #5.10 Just to verify, it is being computed nice.
         print(algo7)
Пример #9
0
 d3 = d1 + d2
 distance = d3**0.5
 distance = distance / 1000
 print(distance)
 #5.5.2. Now if the distance is below a given threshold, I will allow the computation
 if distance < threshold:
     coordCOMP = xcoord2, ycoord2
     #5.6. Increase counter of distance by 1.
     countdistance = countdistance + 1
     module10 = countdistance % 100
     if module10 == 0:
         #5.7. Every 100 queries we sleep for 10 seconds.
         time.sleep(10)
     #5.8 Walking distance.
     algoprueba = gmaps.distance_matrix(coordORIG,
                                        coordCOMP,
                                        mode=MODE)
     #5.9 Driving distance stored in a set of dictionaries and lists.
     #We need to extract it in seven steps.
     algo2 = algoprueba['rows']
     algo3 = algo2[0]
     algo4 = algo3['elements']
     algo5 = algo4[0]
     status = algo5['status']
     #5.10 If status ok, compute distance.
     if status == 'OK':
         algo6 = algo5['distance']
         algo7 = algo6['value']
     else:
         algo7 = 'NA'
         #5.10 Just to verify, it is being computed nice.
Пример #10
0
def runCapacitated_TW_VRP(key):
    locations = [
        manuf_cntr,
        distb_cntr2,
        distb_cntr3,
        distb_cntr5,
        distb_cntr6,
        distb_cntr8,
        distb_cntr9,
        distb_cntr10,
    ]
    demands = [0, 10, 20, 50, 10, 30, 20, 40]
    num_vehicles = 2
    vehicle_capacity = 100
    srvc_tm_perUnit = 120  #2 min
    earliest_dlvry_tm = 0
    latest_dlvry_tm = 16200  #4.5 hrs after dispatch

    #Create GoogleMap instance to request information from Google Maps API
    gmap = Client(key)

    #Fetch inter-location distances from google maps api
    dist_mtrx_resp = gmap.distance_matrix(locations, locations, mode="driving")

    #Store the distancevalues & duration values in a matrix
    x = 0
    y = 0
    dist_mtrx = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
                 [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
                 [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
                 [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
    duratn_mtrx = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
                   [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
                   [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
                   [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]

    while (x < len(locations)):
        while (y < len(locations)):
            dist_mtrx[x][y] = dist_mtrx_resp.get("rows")[x].get(
                "elements")[y].get("distance").get("value")
            duratn_mtrx[x][y] = dist_mtrx_resp.get("rows")[x].get(
                "elements")[y].get("duration").get("value")
            y += 1
        y = 0
        x += 1

    print("Duration Matrix")
    print(duratn_mtrx)

    #####################
    # Distance Callback #
    #####################

    def CreateDistanceCallback(dist_matrix):
        def dist_callback(from_node, to_node):
            return dist_matrix[from_node][to_node]

        return dist_callback

    #############################################
    # Capacity callback & constraint definition #
    ############################################

    def CreateDemandCallback(dmd):
        def demand_callback(from_node, to_node):
            return dmd[from_node]

        return demand_callback

    def add_capacity_constraints(routing, demand_callback):
        """Adds capacity constraint"""
        capacity = "Capacity"
        #vehicle_capacity = 100
        routing.AddDimension(
            demand_callback,
            0,  # null capacity slack
            vehicle_capacity,  # vehicle maximum capacity
            True,  # start cumul to zero
            capacity)

    #############################################
    # Time callback & constraint definition #
    ############################################

    def CreateTimeCallback(duratn_mtrx):
        def serviceTime(node):
            """Gets the service time for a node assuming 2 mins of service time per unit"""
            return demands[node] * srvc_tm_perUnit

        def tot_time_callback(from_node, to_node):
            """Gets the total time to reach a node as the travel duration + service time"""
            return duratn_mtrx[from_node][to_node] + serviceTime(from_node)

        return tot_time_callback

    def add_time_window_constraints(routing, tot_time_callback):
        """Adds time window constraint"""
        time = "Time"
        horizon = 120
        #earliest_dlvry_tm = 0
        #latest_dlvry_tm = 16200
        routing.AddDimension(
            tot_time_callback,
            horizon,  # allow waiting time
            latest_dlvry_tm,  # maximum time per vehicle
            False,  # don't force start cumul to zero since we are giving TW to start nodes
            time)
        time_dimension = routing.GetDimensionOrDie(time)
        for location_idx in range(len(locations)):
            if location_idx == 0:
                continue
            index = routing.NodeToIndex(location_idx)
            time_dimension.CumulVar(index).SetRange(earliest_dlvry_tm,
                                                    latest_dlvry_tm)
            routing.AddToAssignment(time_dimension.SlackVar(index))
        for vehicle_id in xrange(num_vehicles):
            index = routing.Start(vehicle_id)
            time_dimension.CumulVar(index).SetRange(0, 0)
            routing.AddToAssignment(time_dimension.SlackVar(index))

    ####################
    # Get Routes Array #
    ####################
    def get_routes_array(assignment, num_vehicles, routing):
        # Get the routes for an assignent and return as a list of lists.
        routes = []
        durations = []
        for route_nbr in range(num_vehicles):
            node = routing.Start(route_nbr)
            route = []
            time_wndw = []

            while not routing.IsEnd(node):
                index = routing.NodeToIndex(node)
                route.append(index)
                node = assignment.Value(routing.NextVar(node))
                time_dimension = routing.GetDimensionOrDie('Time')
                time_var = time_dimension.CumulVar(index)
                time_min = assignment.Min(time_var)
                time_max = assignment.Max(time_var)
                time_wndw.append([time_min, time_max])
            routes.append(route)
            durations.append(time_wndw)
        return routes, durations

    ###################
    #       Main      #
    ###################

    # Create Routing Model
    routing = pywrapcp.RoutingModel(len(locations), num_vehicles, 0)
    # Define weight of each edge based on distance
    dist_callback = CreateDistanceCallback(dist_mtrx)
    routing.SetArcCostEvaluatorOfAllVehicles(dist_callback)
    #add capacity constraints
    dmd_callback = CreateDemandCallback(demands)
    add_capacity_constraints(routing, dmd_callback)
    #add time-window constraints
    time_callback = CreateTimeCallback(duratn_mtrx)
    add_time_window_constraints(routing, time_callback)
    # Setting first solution heuristic (cheapest addition).
    search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters()
    search_parameters.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
    # Solve the problem.
    assignment = routing.SolveWithParameters(search_parameters)
    routes, durations = get_routes_array(assignment, num_vehicles, routing)

    #calculating route lengths
    route_lengths = []
    route_loads = []
    for route in routes:
        r_len = 0
        prevNode = 0
        route_ld = []
        for node in route:
            if (node != 0):
                print(prevNode, node)
                r_len += dist_mtrx[prevNode][node]
            prevNode = node
            route_ld.append(demands[node])
        print(r_len)
        route_lengths.append(r_len)
        route_loads.append(route_ld)
    print("Routes array:")
    print(routes)
    print("Route lengths:")
    print(route_lengths)
    print("Route loads:")
    print(route_loads)
    print("Time Windows")
    print(durations)
    print("========")

    optimizedResp = {
        "routesArr": routes,
        "routesLen": route_lengths,
        "routesLoad": route_loads,
        "routesTW": durations,
        "constraints": {
            "n_veh": num_vehicles,
            "veh_ld_cap": vehicle_capacity,
            "unitOffloadTm": srvc_tm_perUnit,
            "totDlvryTW": latest_dlvry_tm
        }
    }
    return optimizedResp
Пример #11
0
#create the Google maps client
gmaps = Client(key=API_KEY)
#mapp = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=Paris&destinations=Poitier&mode=bicycling&language=fr-FR&key=AIzaSyAcXNyjXepUbFyAf5auZq_RAF_CJJofG_E'


# read the cities

cities = pd.read_csv('villes.csv')

origins = ["Perth, Australia", "Sydney, Australia",
                   "Melbourne, Australia", "Adelaide, Australia",
                   "Brisbane, Australia", "Darwin, Australia",
                   "Hobart, Australia", "Canberra, Australia"]

origins = list(cities['Ville'].values[0:10])
destinations = list(cities['Ville'].values[0:10])

matrix = gmaps.distance_matrix(origins, destinations)
matrix_train = gmaps.distance_matrix(origins, destinations,mode='walking')


def extract_value(row):
  return map( lambda x: x['duration']['text'], row['elements'])

mm = map(extract_value, matrix['rows'])
mm_train = map(extract_value, matrix_train['rows'])

dur = DataFrame(mm,index=origins, columns=destinations)
dur_train = DataFrame(mm_train,index=origins, columns=destinations)
print dur
print dur_train
Пример #12
0
 d2=(yUTM2-yUTM1)**2
 d3=d1+d2
 distance=d3**0.5
 distance=distance/1000
 print(distance)
 #5.5.2. Now if the distance is below a given threshold, I will allow the computation
 if distance<threshold:
     coordCOMP=xcoord2, ycoord2
     #5.6. Increase counter of distance by 1.
     countdistance=countdistance+1
     module10=countdistance%100
     if module10==0:
         #5.7. Every 100 queries we sleep for 10 seconds.
         time.sleep(10)
     #5.8 Walking distance.
     algoprueba=gmaps.distance_matrix(coordORIG,coordCOMP,mode='walking')
     #5.9 Driving distance stored in a set of dictionaries and lists.
     #We need to extract it in seven steps.
     algo2=algoprueba['rows']
     algo3=algo2[0]
     algo4=algo3['elements']
     algo5=algo4[0]
     status=algo5['status']
     #5.10 If status ok, compute distance.
     if status=='OK':
         algo6=algo5['distance']
         algo7=algo6['value']
     else:
         algo7='NA'
         #5.10 Just to verify, it is being computed nice.
         print(algo7)
def runMultiVehicleOptimzation(key, num_vehicles):
    locations = [
        manuf_cntr, distb_cntr2, distb_cntr3, distb_cntr5, distb_cntr6,
        distb_cntr8, distb_cntr9, distb_cntr10
    ]

    #Create GoogleMap instance to request information from Google Maps API
    gmap = Client(key)

    #Fetch inter-location distances from google maps api
    dist_mtrx_resp = gmap.distance_matrix(locations, locations, mode="driving")

    #Store the distancevalues in a distance matrix
    x = 0
    y = 0
    dist_mtrx = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
                 [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
                 [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
                 [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
    while (x < len(locations)):
        while (y < len(locations)):
            dist_mtrx[x][y] = dist_mtrx_resp.get("rows")[x].get(
                "elements")[y].get("distance").get("value")
            y += 1
        y = 0
        x += 1

    ###################################
    # Distance callback and dimension #
    ####################################

    def CreateDistanceCallback(dist_matrix):
        def dist_callback(from_node, to_node):
            return dist_matrix[from_node][to_node]

        return dist_callback

    def add_distance_dimension(routing, dist_callback):
        """Add Global Span constraint"""
        distance = "Distance"
        maximum_distance = 90000
        routing.AddDimension(
            dist_callback,
            0,  # null slack
            maximum_distance,  # maximum distance per vehicle
            True,  # start cumul to zero
            distance)
        distance_dimension = routing.GetDimensionOrDie(distance)
        # Try to minimize the max distance among vehicles.
        distance_dimension.SetGlobalSpanCostCoefficient(100)

    ####################
    # Get Routes Array #
    ####################
    def get_routes_array(assignment, num_vehicles, routing):
        # Get the routes for an assignent and return as a list of lists.
        routes = []
        for route_nbr in range(num_vehicles):
            node = routing.Start(route_nbr)
            route = []

            while not routing.IsEnd(node):
                index = routing.NodeToIndex(node)
                route.append(index)
                node = assignment.Value(routing.NextVar(node))
            routes.append(route)
        return routes

    ########
    # Main #
    ########

    # Create Routing Model
    routing = pywrapcp.RoutingModel(len(locations), num_vehicles, 0)
    # Define weight of each edge
    dist_callback = CreateDistanceCallback(dist_mtrx)
    routing.SetArcCostEvaluatorOfAllVehicles(dist_callback)
    add_distance_dimension(routing, dist_callback)
    # Setting first solution heuristic (cheapest addition).
    search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters()
    search_parameters.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
    # Solve the problem.
    assignment = routing.SolveWithParameters(search_parameters)
    routes = get_routes_array(assignment, num_vehicles, routing)

    #calculating route lengths
    route_lengths = []
    for route in routes:
        r_len = 0
        prevNode = 0
        for node in route:
            if (node != 0):
                print(prevNode, node)
                r_len += dist_mtrx[prevNode][node]
            prevNode = node
        print(r_len)
        route_lengths.append(r_len)
    print("Routes array:")
    print(routes)
    print("Route lengths:")
    print(route_lengths)
    print("========")

    optimizedResp = {
        "routesArr": routes,
        "routesLen": route_lengths,
        "constraints": {
            "n_veh": num_vehicles
        }
    }
    return optimizedResp
Пример #14
0
 def get_distance_duration(self):
     gmaps = Client(key=settings.GMAPS_API_KEY)
     response = gmaps.distance_matrix(self.origin, self.destin)
     return self._build_data_with_postcode(response)
Пример #15
0
class DistanceCalculator:
    """Calculate distance between pins."""
    def __init__(self):
        """Init instance."""
        self.matrix_client = None
        self.key_generator = cycle(GOOGLE_MATRIX_API_KEYS)

    def load_client(self):
        """Load a client with the next API key."""
        self.matrix_client = Client(key=next(self.key_generator))

    def calculate(self):
        """Calculate the distance for all apartments that were not calculated yet.

        - Query all pins;
        - Query all apartments not yet calculated;
        - Call Google Maps Distance Matrix;
        - Save the results.
        """
        self.load_client()
        tomorrow = date.today() + timedelta(
            0 if datetime.now().hour < 9 else 1)
        morning = datetime(tomorrow.year, tomorrow.month, tomorrow.day, 9, 0)
        LOGGER.warning('Next morning: %s', morning)

        empty = {'text': 'ERROR', 'value': -1}
        for pin in Pin.query.all():
            while True:
                apartments = Apartment.query.outerjoin(Distance, and_(
                    Apartment.id == Distance.apartment_id, Distance.pin_id == pin.id)) \
                    .filter(Apartment.active.is_(True),
                            Apartment.address.isnot(None), Distance.apartment_id.is_(None)).limit(20)
                search = {
                    apartment.id: apartment.address
                    for apartment in apartments.all()
                }
                if not search:
                    LOGGER.warning('All distances already calculated for %s',
                                   pin)
                    break

                ids = list(search.keys())
                origin_addresses = list(search.values())
                LOGGER.warning('Calling Google Maps for %s', pin)
                try:
                    result = self.matrix_client.distance_matrix(
                        origin_addresses, [pin.address],
                        mode='transit',
                        units='metric',
                        arrival_time=morning)
                except (ApiError, HTTPError) as err:
                    LOGGER.error('Error on Google Distance Matrix: %s %s',
                                 str(err), origin_addresses)
                    continue
                except Timeout:
                    # A timeout usually happens when the daily request quota has expired.
                    # Let's load another client with the next API key.
                    LOGGER.error(
                        'Daily quota probably expired... loading next API key')
                    self.load_client()
                    continue

                LOGGER.warning('Processing results from Google Maps for %s',
                               pin)
                for row_dict in [row['elements'][0] for row in result['rows']]:
                    duration, distance = row_dict.get('duration',
                                                      empty), row_dict.get(
                                                          'distance', empty)
                    meters = distance.get('value')
                    apt_id = ids.pop(0)
                    model = Distance.create(apartment_id=apt_id,
                                            pin_id=pin.id,
                                            json=row_dict,
                                            meters=meters,
                                            minutes=round(
                                                duration.get('value') / 60))
                    if meters <= 0:
                        LOGGER.error('Error calculating %s: %s', model,
                                     json.dumps(row_dict))
                    else:
                        LOGGER.warning('Calculating %s', model)
Пример #16
0
gmaps = Client(key=API_KEY)
#mapp = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=Paris&destinations=Poitier&mode=bicycling&language=fr-FR&key=AIzaSyAcXNyjXepUbFyAf5auZq_RAF_CJJofG_E'

# read the cities

cities = pd.read_csv('villes.csv')

origins = [
    "Perth, Australia", "Sydney, Australia", "Melbourne, Australia",
    "Adelaide, Australia", "Brisbane, Australia", "Darwin, Australia",
    "Hobart, Australia", "Canberra, Australia"
]

origins = list(cities['Ville'].values[0:10])
destinations = list(cities['Ville'].values[0:10])

matrix = gmaps.distance_matrix(origins, destinations)
matrix_train = gmaps.distance_matrix(origins, destinations, mode='walking')


def extract_value(row):
    return map(lambda x: x['duration']['text'], row['elements'])


mm = map(extract_value, matrix['rows'])
mm_train = map(extract_value, matrix_train['rows'])

dur = DataFrame(mm, index=origins, columns=destinations)
dur_train = DataFrame(mm_train, index=origins, columns=destinations)
print dur
print dur_train
Пример #17
0
def runCapacitatedVRP(key, num_vehicles, vehicle_capacity):

    locations = [
        manuf_cntr,
        distb_cntr2,
        distb_cntr3,
        distb_cntr5,
        distb_cntr6,
        distb_cntr8,
        distb_cntr9,
        distb_cntr10,
    ]
    demands = [0, 10, 20, 50, 10, 30, 20, 40]
    print(vehicle_capacity)

    #Create GoogleMap instance to request information from Google Maps API
    gmap = Client(key)

    #Fetch inter-location distances from google maps api
    dist_mtrx_resp = gmap.distance_matrix(locations, locations, mode="driving")

    #Store the distancevalues in a distance matrix
    x = 0
    y = 0
    dist_mtrx = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
                 [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
                 [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
                 [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
    while (x < len(locations)):
        while (y < len(locations)):
            dist_mtrx[x][y] = dist_mtrx_resp.get("rows")[x].get(
                "elements")[y].get("distance").get("value")
            y += 1
        y = 0
        x += 1
    '''
    dist_mtrx=[[0,15795,29256,24177,25868,34809,32858,31861],
    [16872,0,13429,12096,13787,18982,17032,17459],
    [28803,13758,0,14724,12395,7998,6716,6143],
    [22989,12054,14708,0,5873,14991,16086,18738],
    [25182,14247,10509,6246,0,10864,8872,20054],
    [33710,18664,9621,15621,11553,0,2708,19163],
    [33446,17430,6590,16822,10325,1690,0,16083],
    [31081,17776,6126,20309,16241,13511,10534,0]]
    '''

    #####################
    # Distance Callback #
    #####################

    def CreateDistanceCallback(dist_matrix):
        def dist_callback(from_node, to_node):
            return dist_matrix[from_node][to_node]

        return dist_callback

    #############################################
    # Capacity callback & constraint definition #
    ############################################

    def CreateDemandCallback(dmd):
        def demand_callback(from_node, to_node):
            return dmd[from_node]

        return demand_callback

    def add_capacity_constraints(routing, demand_callback):
        """Adds capacity constraint"""
        capacity = "Capacity"
        #vehicle_capacity = 100
        routing.AddDimension(
            demand_callback,
            0,  # null capacity slack
            vehicle_capacity,  # vehicle maximum capacity
            True,  # start cumul to zero
            capacity)

    ####################
    # Get Routes Array #
    ####################
    def get_routes_array(assignment, num_vehicles, routing):
        # Get the routes for an assignent and return as a list of lists.
        routes = []
        for route_nbr in range(num_vehicles):
            node = routing.Start(route_nbr)
            route = []

            while not routing.IsEnd(node):
                index = routing.NodeToIndex(node)
                route.append(index)
                node = assignment.Value(routing.NextVar(node))
            routes.append(route)
        return routes

    ###################
    #       Main      #
    ###################

    # Create Routing Model
    routing = pywrapcp.RoutingModel(len(locations), num_vehicles, 0)
    # Define weight of each edge based on distance
    dist_callback = CreateDistanceCallback(dist_mtrx)
    routing.SetArcCostEvaluatorOfAllVehicles(dist_callback)
    #add capacity constraints
    dmd_callback = CreateDemandCallback(demands)
    add_capacity_constraints(routing, dmd_callback)
    # Setting first solution heuristic (cheapest addition).
    search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters()
    search_parameters.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
    # Solve the problem.
    assignment = routing.SolveWithParameters(search_parameters)
    routes = get_routes_array(assignment, num_vehicles, routing)

    #calculating route lengths
    route_lengths = []
    route_loads = []
    for route in routes:
        r_len = 0
        prevNode = 0
        route_ld = []
        for node in route:
            if (node != 0):
                print(prevNode, node)
                r_len += dist_mtrx[prevNode][node]
            prevNode = node
            route_ld.append(demands[node])
        print(r_len)
        route_lengths.append(r_len)
        route_loads.append(route_ld)
    print("Routes array:")
    print(routes)
    print("Route lengths:")
    print(route_lengths)
    print("Route loads:")
    print(route_loads)
    print("========")

    optimizedResp = {
        "routesArr": routes,
        "routesLen": route_lengths,
        "routesLoad": route_loads,
        "constraints": {
            "n_veh": num_vehicles,
            "veh_ld_cap": vehicle_capacity
        }
    }
    return optimizedResp