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 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 #7
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
        cost_df_offline = solver.evaluate(pm_set, ele_price)
        num_df_offline = solver.evaluate_pm_number()
        solver.reset(pm_set)

        solver.solve_offline_alg(copy.deepcopy(job_set), pm_set, ele_price)
        cost_alg_offline = solver.evaluate(pm_set, ele_price)
        num_alg_offline = solver.evaluate_pm_number()
        solver.reset(pm_set)

        cost_opt = 0

        # Simulate the running of time (for online simulation)
        for t in range(0, num_slots):
            # Catch all the jobs arrive at time t
            cur_job_set = {}
            while not pq.empty():
                job = pq.get()
                if job.start_time == t:
                    cur_job_set[job.id] = job
                else:
                    pq.put(job, job.start_time)
                    break

            if len(cur_job_set) == 0:
                continue

            # Push the cur_job_set to the online algorithm engine
            #online_alg.job_set = copy.deepcopy(cur_job_set)
            #online_df.job_set = copy.deepcopy(cur_job_set)  # 2017.09.17 using deepcopy?
            online_alg.job_set = cur_job_set
            online_df.job_set = cur_job_set
Beispiel #9
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)