Beispiel #1
0
def single_source_dijkstra(road_network, start):
    """
    Compute the shortest paths from a vertex, whose id is start, to all other vertices using Dijkstra's algorithm.

    :param road_network: RoadNetwork
    :param start: int
    :return: dict[int, int]
        the "came from" array
    """
    import time
    start_time = time.clock()

    frontier = PriorityQueue()
    frontier.put(start, 0)
    came_from = dict()
    cost_so_far = dict()
    came_from[start] = None
    cost_so_far[start] = 0

    while not frontier.empty():
        current = frontier.get()
        for neighbor in road_network.get_neighbors(current):
            new_cost = cost_so_far[current] + road_network.get_weight(
                current, neighbor)
            if neighbor not in cost_so_far or new_cost < cost_so_far[neighbor]:
                cost_so_far[neighbor] = new_cost  # relax
                priority = new_cost
                frontier.put(neighbor, priority)
                came_from[neighbor] = current

    print("Elapsed time is %f seconds." % (time.clock() - start_time))

    return came_from
Beispiel #2
0
def get_shortest_path(road_network, s_vid, e_vid):
    """
    Return the shortest path from vertex s_vid to vertex e_vid using A* algorithm.

    If s_vid-->e_vid is unreachable, return None.

    :param road_network: RoadNetwork
    :param s_vid: int
    :param e_vid: int
    :return: Path
    """
    frontier = PriorityQueue()
    frontier.put(s_vid, 0)
    came_from = dict()
    cost_so_far = dict()
    came_from[s_vid] = None
    cost_so_far[s_vid] = 0

    while not frontier.empty():
        current = frontier.get()
        # Take a look at the number of lines of code:) date: 2016/12/13 23:12
        if current == e_vid:
            break

        for neighbor in road_network.get_neighbors(current):
            new_cost = cost_so_far[current] + road_network.get_weight(
                current, neighbor)
            if neighbor not in cost_so_far or new_cost < cost_so_far[neighbor]:
                cost_so_far[neighbor] = new_cost
                priority = new_cost + road_network.get_straight_distance(
                    neighbor, e_vid)
                frontier.put(neighbor, priority)
                came_from[neighbor] = current

    return construct_path(road_network, s_vid, e_vid, came_from)
Beispiel #3
0
def greedy_bfs(road_network, s_vid, e_vid):
    """
    Return the shortest path from vertex s_vid to vertex e_vid using Greedy-Best-First-Search.

    In Greedy-BFS, the heuristic function is road_network.get_straight_distance().

    :param road_network: RoadNetwork
    :param s_vid: int
    :param e_vid: int
    :return: Path
    """
    frontier = PriorityQueue()
    frontier.put(s_vid, 0)
    came_from = dict()
    came_from[s_vid] = None

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

        if current == e_vid:
            break

        for neighbor in road_network.get_neighbors(current):
            if neighbor not in came_from:
                priority = road_network.get_straight_distance(neighbor, e_vid)
                frontier.put(neighbor, priority)
                came_from[neighbor] = current

    return construct_path(road_network, s_vid, e_vid, came_from)
Beispiel #4
0
def dijkstra(road_network, s_vid, e_vid):
    """
    Return the exact shortest path from vertex s_vid to vertex e_vid using Dijkstra's algorithm.

    :param road_network: RoadNetwork
    :param s_vid: int
    :param e_vid: int
    :return: Path
    """
    frontier = PriorityQueue()
    frontier.put(s_vid, 0)
    came_from = dict()
    cost_so_far = dict()
    came_from[s_vid] = None
    cost_so_far[s_vid] = 0

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

        if current == e_vid:
            break

        for neighbor in road_network.get_neighbors(current):
            new_cost = cost_so_far[current] + road_network.get_weight(
                current, neighbor)
            if neighbor not in cost_so_far or new_cost < cost_so_far[neighbor]:
                cost_so_far[neighbor] = new_cost  # relax
                priority = new_cost
                frontier.put(neighbor, priority)
                came_from[neighbor] = current

    return construct_path(road_network, s_vid, e_vid, came_from)
Beispiel #5
0
    def search_path(self):
        frontier = PriorityQueue()
        frontier.put(self.start_node, 0)
        came_from = {}
        cost_so_far = {}
        visited_site = {}
        came_from[self.start_node] = None
        cost_so_far[self.start_node] = 0

        self.real_end_node = None

        s_t = time.clock()

        while not frontier.empty():
            if time.clock() - s_t > 60:
                print("search path time out.")
                return []

            current = frontier.get()  # type: Node
            cur_site = (current.xid, current.yid)

            if current.xid == self.target_xid and current.yid == self.target_yid:
                self.real_end_node = current
                break

            # inspect five (include itself) neighbors
            neighbors = self._get_neighbors(current)
            for nb in neighbors:
                new_cost = cost_so_far[current] + self._get_cost(current, nb)
                next_site = (nb.xid, nb.yid)
                if nb not in cost_so_far or new_cost < cost_so_far[nb]:
                    if next_site == cur_site and next_site in visited_site:
                        cost_so_far[nb] = new_cost + 2
                    else:
                        cost_so_far[nb] = new_cost
                    visited_site[next_site] = (nb.hour, nb.step)
                    priority = cost_so_far[nb] + self.heuristic(
                        nb, self.end_node)
                    frontier.put(nb, priority)
                    came_from[nb] = current

        if self.real_end_node is None:
            return []

        path = [self.real_end_node]
        now = self.real_end_node
        while came_from[now] is not None:
            now = came_from[now]
            path.append(now)
        path.reverse()

        return path
Beispiel #6
0
def load_query():
    """
    Load taxi queries from file.

    :return: PriorityQueue[(int, Query)]
    :rtype: [dict[int, Query], PriorityQueue]
    """
    from datetime import datetime
    import time

    print("Loading queries and create query queue (will take about 20 sec)...")
    start_time = time.clock()

    query_set = dict()
    query_queue = PriorityQueue()
    start_time_tuple = datetime.strptime('00:00:00', '%H:%M:%S')
    identifier = 0

    i = 0
    file_list = os.listdir("./data/queries")
    for file_name in file_list:
        i += 1
        print("Loading the %d-th file..." % i)
        cur_file = open("./data/queries/" + file_name)
        for line in cur_file:
            [time_str, ori_lat, ori_lon, des_lat, des_lon] = line.split(',')
            time_tuple = datetime.strptime(time_str, '%H:%M:%S')
            timestamp = (time_tuple - start_time_tuple).seconds + 1

            if timestamp < SIM_START_TIME or timestamp > SIM_END_TIME:
                continue

            ori_lat = float(ori_lat)
            ori_lon = float(ori_lon)
            des_lat = float(des_lat)
            des_lon = float(des_lon)
            origin = Location(ori_lat, ori_lon)
            destination = Location(des_lat, des_lon)

            query = Query(identifier, timestamp, origin, destination)
            query_set[identifier] = query
            query_queue.put(query, timestamp)

            identifier += 1
        cur_file.close()
    print("Done. Elapsed time is %f seconds" % (time.clock() - start_time))
    return [query_set, query_queue]
Beispiel #7
0
    def run(self):

        print("The simulation system is running...")
        start_time = time.clock()

        waiting_queries = PriorityQueue()

        for timestamp in range(SIM_START_TIME, SIM_END_TIME + 1):
            print("Time: %d" % timestamp)
            # Catch the queries to be processed in this timestamp. The queries consists of two parts:
            # 1. queries that happened in this timestamp
            # 2. queries that stranded in previous timestamps
            while not self.query_queue.empty():
                new_query = self.query_queue.get()
                if new_query.timestamp == timestamp:
                    waiting_queries.put(new_query, new_query.timestamp)
                else:
                    self.query_queue.put(new_query, new_query.timestamp)
                    break
            while not self.dispatcher.failed_queries.empty():
                old_query = self.dispatcher.failed_queries.get()
                waiting_queries.put(old_query, old_query.timestamp)

            # Process the queries.
            while not waiting_queries.empty():
                query = waiting_queries.get()
                if query.status == CANCELLED:
                    self.dispatcher.add_cancelled_query(query)
                else:
                    self.dispatcher.dispatch_taxi(timestamp, query, self.db,
                                                  self.taxi_set,
                                                  self.road_network)

            # Update the status of all the queries
            for query in self.query_set.values():
                if query.timestamp <= timestamp and query.status == WAITING:
                    query.update_status(timestamp)

            # All the taxis drive according to their schedule.
            for taxi in self.taxi_set.values():
                taxi.drive(timestamp, self.road_network, self.dispatcher,
                           self.query_set, self.db)

        print("The simulation is end. Elapsed time is %f." %
              (time.clock() - start_time))
Beispiel #8
0
    def search_path_greedy_best_first(self):
        frontier = PriorityQueue()
        frontier.put(self.start_node, 0)
        came_from = dict()
        came_from[self.start_node] = None

        self.real_end_node = None

        s_t = time.clock()

        while not frontier.empty():
            if time.clock() - s_t > 60:
                print("search path time out.")
                return []

            current = frontier.get()  # type: Node

            if current.xid == self.target_xid and current.yid == self.target_yid:
                self.real_end_node = current
                break

            # inspect five (include itself) neighbors
            neighbors = self._get_neighbors(current)
            for nb in neighbors:
                if nb not in came_from:
                    priority = self.heuristic(nb, self.end_node)
                    frontier.put(nb, priority)
                    came_from[nb] = current

        if self.real_end_node is None:
            return []

        path = [self.real_end_node]
        now = self.real_end_node
        while came_from[now] is not None:
            now = came_from[now]
            path.append(now)
        path.reverse()

        return path
    total_num_df_online, total_num_alg_online = 0.0, 0.0

    total_cost_df_offline, total_cost_alg_offline, total_cost_opt = 0.0, 0.0, 0.0
    total_num_df_offline, total_num_alg_offline, total_num_opt = 0.0, 0.0, 0.0

    for round_id in range(0, rounds):

        # Generate the input
        [job_set, pm_set, ele_price] = load_data(num_jobs,
                                                 num_slots)  # real-trace input

        # Put all the jobs into a priority queue with start time of the job as the priority
        pq = PriorityQueue()
        for i in job_set:
            job = job_set[i]
            pq.put(job, job.start_time)

        # Init the online algorithms
        num_pms = len(job_set)
        online_alg = OnlineSolver(num_pms, num_slots, ele_price)
        online_df = OnlineDemandFirst(num_pms, num_slots, ele_price)
        opt_lb = ILPSolver(job_set, pm_set, ele_price)

        # Init the offline algorithms and run
        solver = OfflineSolver()
        solver.solve_offline_demand_first(copy.deepcopy(job_set), pm_set,
                                          ele_price)
        cost_df_offline = solver.evaluate(pm_set, ele_price)
        num_df_offline = solver.evaluate_pm_number()
        solver.reset(pm_set)
Beispiel #10
0
    def run(self):
        start_time = time.clock()
        query_num = len(self.query_set)
        print "query to be processed NUM:", query_num
        processed_order = 0
        query_sum_dist = 0

        waiting_queries = PriorityQueue()

        for timestamp in range(SIM_START_TIME, SIM_END_TIME + 1):
            print("Time: %d" % timestamp)
            sim_start_time = time.clock()
            # Catch the queries to be processed in this timestamp. The queries consists of two parts:
            # 1. queries that happened in this timestamp
            # 2. queries that stranded in previous timestamps
            while not self.query_queue.empty():
                new_query = self.query_queue.get()
                if new_query.timestamp == timestamp:
                    waiting_queries.put(new_query, new_query.timestamp)
                else:
                    self.query_queue.put(new_query, new_query.timestamp)
                    break
            while not self.dispatcher.failed_queries.empty():
                old_query = self.dispatcher.failed_queries.get()
                waiting_queries.put(old_query, old_query.timestamp)

            # Process the queries.
            while not waiting_queries.empty():
                query = waiting_queries.get()
                if query.status == CANCELLED:
                    self.dispatcher.add_cancelled_query(query)
                else:
                    if DEBUG_MODEL:
                        print "......To process query:", query.id
                        print "origin: %s ---> dest:%s" % (query.o_geohash,
                                                           query.d_geohash)
                        print "[%f, %f]----->[%f,%f]" % (
                            query.pickup_window.early,
                            query.pickup_window.late,
                            query.delivery_window.early,
                            query.delivery_window.late)
                        print "[%f, %f]----->[%f,%f]" % (
                            query.origin.lon, query.origin.lat,
                            query.destination.lon, query.destination.lat)
                        print "dist:", get_distance(query.origin,
                                                    query.destination)

                    flag_suc = self.dispatcher.dispatch_taxi(
                        timestamp, query, self.db, self.taxi_set,
                        self.road_network, self.query_set)
                    if flag_suc:
                        processed_order += 1
                        query_sum_dist += get_distance(query.origin,
                                                       query.destination)
                        print "order Num:", processed_order
                        print "order Dist:", query_sum_dist

                    if processed_order > 0 and processed_order % 100 == 0:
                        self.print_load(processed_order)

            # Update the status of all the queries
            for query in self.query_set.values():
                if query.timestamp <= timestamp and query.status == WAITING:
                    query.update_status(timestamp)

            # All the taxis drive according to their schedule.
            for taxi in self.taxi_set.values():
                taxi.drive(timestamp, self.road_network, self.dispatcher,
                           self.query_set, self.db)

            print "Done in %f seconds" % (time.clock() - sim_start_time)

        [max, min, count] = self.print_utility()
        print("after:"), max - min, ("  count:"), count
        print("satisfy ratio:"), self.print_satisfy(query_num)
        for load in self.maxLoad:
            print load, "    "
        for load in self.sumLoad:
            print load, "    "
        print("The simulation is end. Elapsed time is %f." %
              (time.clock() - start_time))
        winsound.Beep(600, 1000)