Beispiel #1
0
    def dropoff(self):
        # print(self.get_location(), self.state.destination_lat, self.state.destination_lon)
        assert len(self.__customers) > 0
        lenC = len(self.__customers)
        assert self.get_location() == self.__customers[lenC-1].get_destination()

        if FLAGS.enable_pooling:
            # print("DropOff, pooling!")
            lenC = len(self.__customers)
            self.state.travel_dist += great_circle_distance(self.__customers[0].get_origin()[0], self.__customers[0].get_origin()[1],
                self.__customers[lenC-1].get_destination()[0], self.__customers[lenC-1].get_destination()[1])
            # print("Dist: ", self.state.travel_dist)
            # print("Trip: ", great_circle_distance(self.__customers[0].get_origin()[0], self.__customers[0].get_origin()[1],
            #     self.__customers[lenC-1].get_destination()[0], self.__customers[lenC-1].get_destination()[1]))
            for i in range(lenC):
                # print("Trip: ", lenC)
                customer = self.__customers.pop(0)
                self.earnings += customer.make_payment(self.state.current_capacity, self.state.driver_base_per_trip)
                customer.get_off()

        else:
            # print("Dropoff, not pooling!")
            customer = self.__customers.pop(0)
            customer.get_off()
            self.earnings += customer.make_payment(1, self.state.driver_base_per_trip)
            self.state.travel_dist += great_circle_distance(customer.get_origin()[0], customer.get_origin()[1],
                                                            customer.get_destination()[0],
                                                            customer.get_destination()[1])

        self.state.current_capacity = 0
        self.__customers_ids = []
        self.__change_to_idle()
        # latest_cust_id = self.state.assigned_customer_id.pop(0)
        self.__reset_plan()
        self.__log()
Beispiel #2
0
    def match(self, current_time, vehicles, requests):
        assignments = []
        vehicles, vehicles_tocharge = self.find_available_vehicles(vehicles)
        n_vehicles = len(vehicles)
        if n_vehicles == 0:
            return assignments
        # List of distances for all available vehicles to requests' origin points
        d = great_circle_distance(vehicles.lat.values, vehicles.lon.values,
                                  requests.origin_lat.values[:, None],
                                  requests.origin_lon.values[:, None])

        for ridx, request_id in enumerate(requests.index):
            vidx = d[ridx].argmin(
            )  # Retrieving the min distance (nearest vehicle to request)
            # Check if it is within the acceptable range of travelling distance
            if d[ridx, vidx] < self.reject_distance:
                vehicle_id = vehicles.index[vidx]
                duration = d[ridx, vidx] / 8.0
                distance = d[ridx, vidx]
                assignments.append(
                    self.create_matching_dict(vehicle_id, request_id, duration,
                                              distance))
                d[:, vidx] = float('inf')
            else:
                continue
            if len(assignments) == n_vehicles:
                return assignments
        return assignments
    def init_price(self, match_commands):
        m_commands = []
        for c in match_commands:
            vehicle = VehicleRepository.get(c["vehicle_id"])
            # vehicle.state.status = status_codes.V_ASSIGNED
            if vehicle is None:
                print("Invalid Vehicle id")
                continue
            customer = CustomerRepository.get(c["customer_id"])
            if customer is None:
                print("Invalid Customer id")
                continue

            triptime = c["duration"]

            # if FLAGS.enable_pricing:
            dist_for_pickup = c["distance"]
            dist_till_dropoff = great_circle_distance(
                customer.get_origin()[0],
                customer.get_origin()[1],
                customer.get_destination()[0],
                customer.get_destination()[1])
            total_trip_dist = dist_for_pickup + dist_till_dropoff
            [travel_price, wait_price] = vehicle.get_price_rates()
            # v_cap = vehicle.state.current_capacity
            initial_price = calculate_price(total_trip_dist, triptime,
                                            vehicle.state.mileage,
                                            travel_price, wait_price,
                                            vehicle.state.gas_price,
                                            vehicle.state.driver_base_per_trip)
            c["init_price"] = initial_price
            m_commands.append(c)
            # print(c)

        return m_commands
Beispiel #4
0
 def compute_speed(self, route, triptime):
     lats, lons = zip(*route)
     distance = geoutils.great_circle_distance(lats[:-1], lons[:-1], lats[1:], lons[1:])     # Distance in meters
     speed = sum(distance) / triptime
     # print("Dispatch!")
     self.state.travel_dist += sum(distance)
     return speed
Beispiel #5
0
    def drive(self, vehicle, timestep):
        route = vehicle.get_route()  # Sequence of (lon, lat)
        speed = vehicle.get_speed()
        dist_left = timestep * speed  # Remaining Distance
        rlats, rlons = zip(
            *([vehicle.get_location()] +
              route))  # New vehicle location after driving this route
        step_dist = geoutils.great_circle_distance(
            rlats[:-1], rlons[:-1], rlats[1:],
            rlons[1:])  # Get distcnace in meters
        # print(step_dist)
        # print(type(step_dist))
        vehicle.state.travel_dist += dist_left

        for i, d in enumerate(step_dist):

            if dist_left < d:
                bearing = geoutils.bearing(
                    rlats[i], rlons[i], rlats[i + 1],
                    rlons[i + 1])  # Calculate angle of motion
                next_location = geoutils.end_location(
                    rlats[i], rlons[i], dist_left,
                    bearing)  # Calculate nxt location
                vehicle.update_location(
                    next_location, route[i + 1:]
                )  # Updating location based on route's nxt (lon, lat)
                return

            dist_left -= d

        if len(route) > 0:
            vehicle.update_location(route[-1], [])  # Go the last step
Beispiel #6
0
 def compute_speed(self, route, triptime):
     lats, lons = zip(*route)
     distance = geoutils.great_circle_distance(lats[:-1], lons[:-1], lats[1:], lons[1:])     # Distance in meters
     speed = sum(distance) / triptime
     self.state.travel_dist += sum(distance)
     self.state.SOC -= sum(distance)*METER_PER_MILE/self.get_mile_of_range() # meter to mile
     return speed
Beispiel #7
0
    def eta_many_to_many(self,
                         origins,
                         destins,
                         max_distance=5000,
                         ref_speed=5.0):
        T = np.full((len(origins), len(destins)), np.inf)
        origins_lat, origins_lon = zip(*origins)
        destins_lat, destins_lon = zip(*destins)
        origins_lat, origins_lon, destins_lat, destins_lon = map(
            np.array, [origins_lat, origins_lon, destins_lat, destins_lon])
        origins_x, origins_y = mesh.lon2X(origins_lon), mesh.lat2Y(origins_lat)
        destins_x, destins_y = mesh.lon2X(destins_lon), mesh.lat2Y(destins_lat)
        d = geoutils.great_circle_distance(origins_lat[:, None],
                                           origins_lon[:, None], destins_lat,
                                           destins_lon)

        for i, (x, y) in enumerate(zip(origins_x, origins_y)):
            for j in np.where(d[i] < max_distance)[0]:
                axi = destins_x[j] - x + MAX_MOVE
                ayi = destins_y[j] - y + MAX_MOVE
                if 0 <= axi and axi <= 2 * MAX_MOVE and 0 <= ayi and ayi <= 2 * MAX_MOVE:
                    ref_d = self.ref_d[x, y, axi, ayi]
                    if ref_d == 0:
                        T[i, j] = d[i, j] / ref_speed
                    else:
                        T[i, j] = self.tt_map[x, y, axi, ayi] * d[i, j] / ref_d
        return [T, d]
Beispiel #8
0
 def eta_many_to_many(self, origins, destins):
     origins_lon, origins_lat = zip(*origins)
     destins_lon, destins_lat = zip(*destins)
     origins_lon, origins_lat, destins_lon, destins_lat = map(
         np.array, [origins_lon, origins_lat, destins_lon, destins_lat])
     d = geoutils.great_circle_distance(origins_lon[:, None],
                                        origins_lat[:, None], destins_lon,
                                        destins_lat)
     return d
Beispiel #9
0
    def filter_candidates(self, vehicles, requests):
        d = great_circle_distance(vehicles.lat.values, vehicles.lon.values,
                                  requests.origin_lat.mean(),
                                  requests.origin_lon.mean())

        within_limit_distance = d < self.reject_distance + self.unit_length * (
            self.k - 1)
        candidates = vehicles.index[within_limit_distance]
        d = d[within_limit_distance]
        return candidates[np.argsort(d)[:2 * len(requests) + 1]].tolist()
Beispiel #10
0
 def filter_CS_candidates(self, vehicles, charging_stations):
     d = great_circle_distance(vehicles.lat.values, vehicles.lon.values,
                               mean(charging_stations[:, 0]),
                               mean(charging_stations[:, 1]))
     within_limit_distance = d < 1e3 * (
         self.reject_distance + self.unit_length *
         (self.k - 1))  # a large enough number
     candidates = vehicles.index[within_limit_distance]
     d = d[within_limit_distance]
     return candidates[np.argsort(d)[:2 * len(charging_stations) +
                                     1]].tolist()
def remove_outliers(df):
    df['distance'] = great_circle_distance(df.origin_lat, df.origin_lon,
                                           df.destination_lat,
                                           df.destination_lon).astype(int)
    df['speed'] = df.distance / df.trip_time / 1000 * 3600  # km/h
    df['rpm'] = df.fare / df.trip_time * 60  # $/m

    df = df[(df.trip_time > 60) & (df.trip_time < 3600 * 2)]
    df = df[(df.distance > 100) & (df.distance < 100000)]
    df = df[(df.speed > 2) & (df.speed < 80)]
    df = df[(df.rpm < 3.0) & (df.rpm > 0.3)]
    return df.drop(['distance', 'speed', 'rpm'], axis=1)
Beispiel #12
0
def create_reachable_map(engine):
    lon0, lat0 = convert_xy_to_lonlat(0, 0)
    lon1, lat1 = convert_xy_to_lonlat(1, 1)
    d_max = great_circle_distance(lat0, lon0, lat1, lon1) / 2.0

    points = []
    for x, y in state_space:
        lon, lat = convert_xy_to_lonlat(x, y)
        points.append((lat, lon))

    nearest_roads = engine.nearest_road(points)
    reachable_map = np.zeros((MAP_WIDTH, MAP_HEIGHT), dtype=np.float32)
    for (x, y), (latlon, d) in zip(state_space, nearest_roads):
        if d < d_max:
            reachable_map[x, y] = 1

    return reachable_map
Beispiel #13
0
    def __init__(self):
        self.tt_map = np.load(os.path.join(DATA_DIR, 'tt_map.npy'))
        self.routes = pickle.load(open(os.path.join(DATA_DIR, 'routes.pkl'), 'rb'))

        d = self.tt_map.copy()
        for x in range(d.shape[0]):
            origin_lon = mesh.X2lon(x)
            for y in range(d.shape[1]):
                origin_lat = mesh.Y2lat(y)
                for axi in range(d.shape[2]):
                    x_ = x + axi - MAX_MOVE
                    destin_lon = mesh.X2lon(x_)
                    for ayi in range(d.shape[3]):
                        y_ = y + ayi - MAX_MOVE
                        destin_lat = mesh.Y2lat(y_)
                        d[x, y, axi, ayi] = geoutils.great_circle_distance(
                            origin_lat, origin_lon, destin_lat, destin_lon)
        self.ref_d = d
Beispiel #14
0
    def init_price(self, match_commands):
        m_commands = []
        for c in match_commands:
            vehicle = VehicleRepository.get(c["vehicle_id"])
            # vehicle.state.status = status_codes.V_ASSIGNED
            if vehicle is None:
                print("Invalid Vehicle id")
                continue
            customer = CustomerRepository.get(c["customer_id"])
            if customer is None:
                print("Invalid Customer id")
                continue

            triptime = c["duration"]

            # if FLAGS.enable_pricing:
            dist_for_pickup = c["distance"]

            od_route = self.routing_engine.route_time([
                (customer.get_origin(), customer.get_destination())
            ])
            # dist_dropoff = great_circle_distance(customer.get_origin()[0], customer.get_origin()[1],
            #                               customer.get_destination()[0], customer.get_destination()[1])
            route, time = od_route[0]
            lats, lons = zip(*route)
            distance = geoutils.great_circle_distance(
                lats[:-1], lons[:-1], lats[1:], lons[1:])  # Distance in meters
            dist_till_dropoff = sum(distance)

            # print(dist_dropoff, dist_till_dropoff)

            total_trip_dist = dist_for_pickup + dist_till_dropoff
            [travel_price, wait_price] = vehicle.get_price_rates()
            # v_cap = vehicle.state.current_capacity
            initial_price = calculate_price(total_trip_dist, triptime,
                                            vehicle.state.mileage,
                                            travel_price, wait_price,
                                            vehicle.state.gas_price,
                                            vehicle.state.driver_base_per_trip)
            c["init_price"] = initial_price
            m_commands.append(c)
            # print(c)

        return m_commands
Beispiel #15
0
    def drive(self, vehicle, timestep):
        route = vehicle.get_route()
        speed = vehicle.get_speed()
        dist_left = timestep * speed
        rlats, rlons = zip(*([vehicle.get_location()] + route))
        step_dist = geoutils.great_circle_distance(rlats[:-1], rlons[:-1],
                                                   rlats[1:], rlons[1:])
        for i, d in enumerate(step_dist):
            if dist_left < d:
                bearing = geoutils.bearing(rlats[i], rlons[i], rlats[i + 1],
                                           rlons[i + 1])
                next_location = geoutils.end_location(rlats[i], rlons[i],
                                                      dist_left, bearing)
                vehicle.update_location(next_location, route[i + 1:])
                return
            dist_left -= d

        if len(route) > 0:
            vehicle.update_location(route[-1], [])
Beispiel #16
0
 def match(self, current_time, vehicles, requests):
     assignments = []
     vehicles = self.find_available_vehicles(vehicles)
     n_vehicles = len(vehicles)
     if n_vehicles == 0:
         return assignments
     d = great_circle_distance(vehicles.lat.values, vehicles.lon.values,
                               requests.origin_lat.values[:, None],
                               requests.origin_lon.values[:, None])
     for ridx, request_id in enumerate(requests.index):
         vidx = d[ridx].argmin()
         if d[ridx, vidx] < self.reject_distance:
             vehicle_id = vehicles.index[vidx]
             duration = d[ridx, vidx] / 8.0
             assignments.append(
                 self.create_command(vehicle_id, request_id, duration))
             d[:, vidx] = float('inf')
         else:
             continue
         if len(assignments) == n_vehicles:
             return assignments
     return assignments
Beispiel #17
0
 def dropoff(self,tick):
     # print(self.get_location(), self.state.destination_lat, self.state.destination_lon)
     assert len(self.__customers) > 0
     lenC = len(self.__customers)
     # assert self.get_location() == self.__customers[lenC-1].get_destination_lonlat()
     self.state.current_hex = self.__customers[lenC-1].get_destination_id()
     customer = self.__customers.pop(0)
     customer.get_off()
     self.customer_payment = customer.make_payment(1, self.state.driver_base_per_trip)
     
     self.earnings += self.customer_payment
     trip_distance = great_circle_distance(customer.get_origin()[0], customer.get_origin()[1],
                                                     customer.get_destination()[0],
                                                     customer.get_destination()[1])
     self.state.travel_dist += trip_distance
     self.state.SOC -= trip_distance*METER_PER_MILE/self.get_mile_of_range() # meter to mile
     self.rb_next_state = [tick,self.get_id(),self.state.current_hex,self.get_SOC()]
     self.rb_reward = BETA_EARNING* self.customer_payment - BETA_COST*self.compute_charging_cost(trip_distance) - SOC_PENALTY*(1-self.get_SOC())
     if self.state.status == status_codes.V_OFF_DUTY:
         self.flag = 1
      # specify it
     if self.get_SOC() <0:
         self.rb_reward -= 50 # additional penalty for running out battery
         self.state.SOC = self.state.target_SOC
         self.__set_destination(self.get_location(), PENALTY_CHARGING_TIME) # 45 min for emergency charging
         self.__change_to_cruising()
         self.recent_transitions.append((self.rb_state,self.rb_action,self.rb_next_state,self.rb_reward,self.flag))
         # self.dqn_network.dump_transitions(self.recent_transitions[-1])
         return
     self.recent_transitions.append((self.rb_state,self.rb_action,self.rb_next_state,self.rb_reward,self.flag))
     # self.dump_replay_buffer()
     # self.dqn_network.dump_transitions(self.recent_transitions[-1])
     self.state.current_capacity = 0
     self.__customers_ids = []
     self.__change_to_idle()
     # latest_cust_id = self.state.assigned_customer_id.pop(0)
     self.__reset_plan()
     self.__log()
    def propose_price(self, vehicle, price, request):
        if len(vehicle.q_action_dict) == 0:
            # print("NOT DISPATCHED BEFORE!")
            return price
        else:
            # print(self.q_action_dict)
            r_lon, r_lat = request.origin_lon, request.origin_lat
            r_x, r_y = mesh.convert_lonlat_to_xy(r_lon, r_lat)
            # print("ID: ", self.state.id)
            # print("Request: ", r_x, r_y)
            sorted_q = {
                k: v
                for k, v in sorted(vehicle.q_action_dict.items(),
                                   key=lambda item: item[1],
                                   reverse=True)
            }
            # print("Sorted: ", sorted_q)
            # print("Epsilon: ", self.epsilon, len(self.q_action_dict))
            filtered_q = list(islice(sorted_q, vehicle.epsilon))
            # filtered_q = dict(filtered_q)
            # print("Filtered: ", filtered_q)
            if (r_x, r_y) in filtered_q:
                # print("Here!")
                return price

            if (r_x, r_y) in vehicle.q_action_dict.keys():
                # print("Exists!")
                # req_q = self.q_action_dict.get((r_x,r_y))
                rank = 0
                index = 0
                for (kx, ky), v in sorted_q.items():
                    # print((kx,ky), (r_x, r_y))
                    if (kx, ky) == (r_x, r_y):
                        rank = index
                    index += 1
            else:
                # print("Does not exist!")
                dist_list = {}
                for (kx, ky), v in vehicle.q_action_dict.items():
                    k_lon, k_lat = mesh.convert_xy_to_lonlat(kx, ky)
                    dist = great_circle_distance(r_lat, r_lon, k_lat, k_lon)
                    dist_list[(kx, ky)] = dist

                # print("D: ", dist_list)
                min_dist = np.min(list(dist_list.values()))
                (min_x, min_y) = list(dist_list.keys())[list(
                    dist_list.values()).index(min_dist)]
                req_q = vehicle.q_action_dict.get((min_x, min_y))
                # print(min_dist, (min_x,min_y), req_q)

                rank = 0
                index = 0
                for (kx, ky), v in sorted_q.items():
                    if (kx, ky) == (min_x, min_y):
                        rank = index
                    index += 1
            # print("Rank: ", rank, len(self.q_action_dict))
            rank = 1 - (rank / len(vehicle.q_action_dict))
            # print("Rank_: ", rank, (self.state.driver_base_per_trip/100))
            return price + (rank * 0.5 *
                            (vehicle.state.driver_base_per_trip / 100))
Beispiel #19
0
 def compute_speed(self, route, triptime):
     lats, lons = zip(*route)
     distance = geoutils.great_circle_distance(lats[:-1], lons[:-1],
                                               lats[1:], lons[1:])
     speed = sum(distance) / triptime
     return speed
Beispiel #20
0
    def generate_plan(self, vehicle, cust_list, new_customer):
        # print("In Plan: ", vehicle.get_id())
        time_till_pickup = 0
        insertion_cost = 0
        # distance_till_dropoff = 0
        if len(cust_list) == 1 & len(vehicle.current_plan) == 0:
            vehicle.current_plan.append(new_customer.get_origin())
            vehicle.current_plan.append(new_customer.get_destination())
            vehicle.ordered_pickups_dropoffs_ids.append(new_customer.get_id())
            vehicle.ordered_pickups_dropoffs_ids.append(new_customer.get_id())
            vehicle.pickup_flags.append(1)
            vehicle.pickup_flags.append(0)

            routes_till_pickup = [(vehicle.get_location(),
                                   vehicle.current_plan[0])]
            routes = self.routing_engine.route_time(routes_till_pickup)

            for (route, time) in routes:
                time_till_pickup += time

            od_pairs = [(vehicle.get_location(), vehicle.current_plan[0]),
                        (vehicle.current_plan[0], vehicle.current_plan[1])]
            routes = self.routing_engine.route_time(od_pairs)
            for (route, time) in routes:
                vehicle.current_plan_routes.append([route, time])
                lats, lons = zip(*route)
                distance = geoutils.great_circle_distance(
                    lats[:-1], lons[:-1], lats[1:],
                    lons[1:])  # Distance in meters
                insertion_cost += sum(distance)

        else:
            new_list = [
                new_customer.get_origin(),
                new_customer.get_destination()
            ]
            # print(new_list)
            final_pickup_flags = []
            final_plan = []
            final_pickups_dropoffs_ids = []
            final_routes = []

            min_distance = np.inf
            min_time = np.inf
            pickup_index = 0
            # all_options = vehicle.current_plan + new_list
            # print(all_options)
            # perm = list(itertools.permutations(all_options))
            # print(perm)
            # print(len(set(perm)))
            # print("Insert Pickup")
            for pos in range(len(vehicle.current_plan) + 1):
                # print(vehicle.current_plan)
                new_plan = vehicle.current_plan[:pos]
                new_pickup_flags = vehicle.pickup_flags[:pos]
                new_pickups_dropoffs_ids = vehicle.ordered_pickups_dropoffs_ids[:
                                                                                pos]
                new_plan.append(new_list[0])
                new_pickup_flags.append(1)
                new_pickups_dropoffs_ids.append(new_customer.get_id())
                new_plan.extend(vehicle.current_plan[pos:])
                new_pickup_flags.extend(vehicle.pickup_flags[pos:])
                new_pickups_dropoffs_ids.extend(
                    vehicle.ordered_pickups_dropoffs_ids[pos:])

                # print("List: ", new_plan, new_pickup_flags, new_pickups_dropoffs_ids)
                od_pairs = [(vehicle.get_location(), new_plan[0])]
                od_pairs.extend([(new_plan[x], new_plan[x + 1])
                                 for x in range(len(new_plan) - 1)])
                # print(od_pairs)
                total_time = 0
                total_dist = 0
                potential_routes_time = self.routing_engine.route_time(
                    od_pairs)
                new_routes = []
                index = 0
                wait_time = 0
                # pickup_distance = 0
                for (route, time) in potential_routes_time:
                    total_time += time
                    lats, lons = zip(*route)
                    distance = geoutils.great_circle_distance(
                        lats[:-1], lons[:-1], lats[1:],
                        lons[1:])  # Distance in meters
                    total_dist += sum(distance)
                    new_routes.append([route, time])
                    if index < pos + 1:
                        wait_time += time
                        # pickup_distance += sum(distance)
                    index += 1
                # print("Pos: ", pos, "Wait: ", wait_time)
                # print("T: ", total_time)
                # print("D: ", total_dist)

                if (total_time < min_time) | (total_dist < min_distance):
                    min_time = total_time
                    min_distance = total_dist
                    insertion_cost = total_dist
                    final_pickup_flags = new_pickup_flags
                    final_plan = new_plan
                    final_pickups_dropoffs_ids = new_pickups_dropoffs_ids
                    pickup_index = pos
                    final_routes = new_routes
                    time_till_pickup = wait_time
                    # distance_till_pickup = pickup_distance

                # print("Min: ", min_time, min_distance)
            vehicle.current_plan = final_plan
            vehicle.pickup_flags = final_pickup_flags
            vehicle.ordered_pickups_dropoffs_ids = final_pickups_dropoffs_ids
            vehicle.current_plan_routes = final_routes

            final_pickup_flags = []
            final_plan = []
            final_pickups_dropoffs_ids = []
            final_routes = []

            min_distance = np.inf
            min_time = np.inf

            # print("Insert Drop-off! ", pickup_index, time_till_pickup, vehicle.current_plan)

            for pos in range(len(vehicle.current_plan) + 1):
                if pos <= pickup_index:
                    continue
                # print(vehicle.current_plan)
                new_plan = vehicle.current_plan[:pos]
                new_pickup_flags = vehicle.pickup_flags[:pos]
                new_pickups_dropoffs_ids = vehicle.ordered_pickups_dropoffs_ids[:
                                                                                pos]
                new_plan.append(new_list[1])
                new_pickup_flags.append(0)
                new_pickups_dropoffs_ids.append(new_customer.get_id())
                new_plan.extend(vehicle.current_plan[pos:])
                new_pickup_flags.extend(vehicle.pickup_flags[pos:])
                new_pickups_dropoffs_ids.extend(
                    vehicle.ordered_pickups_dropoffs_ids[pos:])

                # print("List: ", new_plan, new_pickup_flags, new_pickups_dropoffs_ids)
                od_pairs = [(vehicle.get_location(), new_plan[0])]
                od_pairs.extend([(new_plan[x], new_plan[x + 1])
                                 for x in range(len(new_plan) - 1)])
                total_time = 0
                total_dist = 0
                potential_routes_time = self.routing_engine.route_time(
                    od_pairs)
                # print(len(new_plan)+1, len(od_pairs), len(potential_routes_time))
                new_routes = []
                # counter = 0
                # dropoff_distance = 0
                for (route, time) in potential_routes_time:
                    total_time += time
                    lats, lons = zip(*route)
                    distance = geoutils.great_circle_distance(
                        lats[:-1], lons[:-1], lats[1:],
                        lons[1:])  # Distance in meters
                    total_dist += sum(distance)
                    new_routes.append([route, time])
                    # if pickup_index < counter < pos+1:
                    #     dropoff_distance += sum(distance)
                    # counter += 1
                # print("T: ", total_time)
                # print("D: ", total_dist)

                if (total_time < min_time) | (total_dist < min_distance):
                    min_time = total_time
                    min_distance = total_dist
                    insertion_cost = total_dist
                    final_pickup_flags = new_pickup_flags
                    final_plan = new_plan
                    final_pickups_dropoffs_ids = new_pickups_dropoffs_ids
                    final_routes = new_routes
                    # distance_till_dropoff = dropoff_distance

                # print("Min: ", min_time, min_distance)
            vehicle.current_plan = np.copy(final_plan).tolist()
            vehicle.pickup_flags = np.copy(final_pickup_flags).tolist()
            vehicle.ordered_pickups_dropoffs_ids = np.copy(
                final_pickups_dropoffs_ids).tolist()
            vehicle.current_plan_routes = np.copy(final_routes).tolist()
            # print("Generated Plan: ", vehicle.current_plan)
            # dist_time = []
            # for (route, time) in vehicle.current_plan_routes:
            #     lats, lons = zip(*route)
            #     distance = geoutils.great_circle_distance(lats[:-1], lons[:-1], lats[1:],lons[1:])  # Distance in meters
            #     dist = sum(distance)
            #     dist_time.append([dist, time])
            # print("Routes: ", dist_time)

            # print(time_till_pickup, distance_till_pickup, distance_till_dropoff)
            # print("Nxt!!")

        return insertion_cost, time_till_pickup
Beispiel #21
0
    def init_price(self, match_commands, charging_commands):
        m_commands = []
        for m in match_commands:
            vehicle = VehicleRepository.get(m["vehicle_id"])
            # vehicle.state.status = status_codes.V_ASSIGNED
            if vehicle is None:
                print("Invalid Vehicle id")
                continue
            customer = CustomerRepository.get(m["customer_id"])
            if customer is None:
                print("Invalid Customer id")
                continue

            triptime = m["duration"]

            # if FLAGS.enable_pricing:
            dist_for_pickup = m["distance"]
            dist_till_dropoff = great_circle_distance(
                customer.get_origin()[0],
                customer.get_origin()[1],
                customer.get_destination()[0],
                customer.get_destination()[1])
            total_trip_dist = dist_for_pickup + dist_till_dropoff
            [travel_price, wait_price] = vehicle.get_price_rates()
            # v_cap = vehicle.state.current_capacity
            initial_price = calculate_price(total_trip_dist, triptime,
                                            vehicle.state.mileage,
                                            travel_price, wait_price,
                                            vehicle.state.gas_price,
                                            vehicle.state.driver_base_per_trip)
            m["init_price"] = initial_price
            m_commands.append(m)

        # matching_charging_station
        c_commands = []  # charging command
        for c in charging_commands:
            vehicle = VehicleRepository.get(c["vehicle_id"])
            if vehicle is None:
                print("Invalid Vehicle id")
                continue
            charging_pile = ChargingRepository.get_charging_station(
                c["customer_id"])

            # charging_pile = df_charging_piles["customer_id"] # return to that row
            if charging_pile is None:
                print("Invalid Customer id")
                continue
            charging_incentives = 0  # charging_pile.get_incentive()

            triptime = c["duration"]
            # if FLAGS.enable_pricing:
            dist_to_cs = c["distance"]
            total_trip_dist = dist_to_cs
            [travel_price, wait_price] = vehicle.get_price_rates()
            # v_cap = vehicle.state.current_capacity
            initial_price = calculate_price(total_trip_dist, triptime,
                                            vehicle.state.mile_of_range,
                                            travel_price, wait_price,
                                            vehicle.state.full_charge_price,
                                            vehicle.state.driver_base_per_trip)
            c["init_price"] = initial_price + charging_incentives
            c_commands.append(c)

        return m_commands, c_commands