Beispiel #1
0
    def terminate(self, pid=None):
        """
        If no pid given, terminates active process in CPU. Else, terminates 
        process with given pid. 
        If active process is terminated, moves head of Ready Queue to CPU.
        Precondition: pid is a valid PID for a process in the ready queue or CPU
        """
        proc = None
        if self.active:
            # Terminate active process if no pid given or if active process has
            # given pid

            if not pid or self.active.pid == pid:
                proc = self.active
                self.ready_to_CPU()
                self.record_burst(proc)

            else:  # Look for process in ready queue and remove
                proc = PriorityQueue.pop(self, pid)

                # Prompt for time since last interrupt
                # Update burst time for active process
                elapsed = io.get_valid_int("Time since last interrupt")
                self.active.update_burst_time(elapsed)

            # Print stats
            print "\n" + "{:-^78}".format(" Terminated Process Report ")
            print "PID: {:<4} Avg CPU Burst Time: {:<5} Total CPU Time: {:<5}".format(
                proc.pid, proc.avg_burst_time(),
                proc.tot_burst_time()).center(78, " ")

            del proc

        else:
            raise IndexError
Beispiel #2
0
    def dijkstra(self, origin_vertex_value, destination_vertex_value) -> collections.deque([Vertex]):
        labels = {}
        parents = {}
        for v in self.vertices():
            labels[v] = math.inf
            parents[v] = None
        labels[self[origin_vertex_value]] = 0
        table = PriorityQueue([v for v in self.vertices()], key=lambda v: labels[v], reverse=True)  # min-heap

        while table:
            start = table.pop()
            for adjacent_edge in start.outgoing_edges:
                end = adjacent_edge.destination
                index = table.find(end)
                if index != -1:
                    weighted_distance = labels[start] + adjacent_edge.weight
                    if weighted_distance < labels[end]:
                        labels[end] = weighted_distance
                        table.remove(index)
                        table.push(end)
                        parents[end] = start

        result = collections.deque()
        start = self[destination_vertex_value]
        while start is not None:
            result.appendleft(start)
            start = parents[start]
        return result
def Dijkstra(num_nodes, mission, f_next, heuristic=None, num_controls=0):
    """Djikstra planner."""
    t = Timer()
    t.tic()
    
    unvis_node = -1
    previous = np.full(num_nodes, dtype=np.int, fill_value=unvis_node)
    cost_to_come = np.zeros(num_nodes)
    control_to_come = np.zeros((num_nodes, num_controls), dtype=np.int)

    startNode = mission['start']['id']
    goalNode = mission['goal']['id']

    #Priority queue based on the lower cost-to-go
    q = PriorityQueue()
    q.insert(0,startNode)
    foundPlan = False

    while not q.IsEmpty():
        x_ctc = q.pop()
        x = x_ctc[1]
        if x == goalNode:
            foundPlan = True
            break
        neighbours, u, d = f_next(x)
        for xi, ui, di in zip(neighbours, u, d):
            if previous[xi] == unvis_node or cost_to_come[xi] > cost_to_come[x] + di:
                previous[xi] = x
                cost_to_come[xi] = cost_to_come[x] + di
                q.insert(cost_to_come[xi],xi)
                if num_controls > 0:
                    control_to_come[xi] = ui

    # Recreate the plan by traversing previous from goal node
    if not foundPlan:
        return []
    else:
        plan = [goalNode]
        length = cost_to_come[goalNode]
        control = []
        while plan[0] != startNode:
            if num_controls > 0:
                control.insert(0, control_to_come[plan[0]])
            plan.insert(0, previous[plan[0]])

        return {'plan': plan,
                'length': length,
                'num_visited_nodes': np.sum(previous != unvis_node),
                'name': 'Djikstra',
                'time': t.toc(),
                'control': control,
                'visited_nodes': previous[previous != unvis_node]}
Beispiel #4
0
def a_star(start, end):
    """
    A* Pathfinding algorithm. Takes a start tile and end tile, and uses
    their neighbour list to traverse.
    Uses the heapq queue in queues.py.
    :param start: Tile
    :param end: Tile
    :return: came_from, dictionary with all tiles as key, and where we came from (parent tile) as value.
             cost_so_far, dictionary with tiles as key, and their cost so far as value.
             success, True or False. If the algorithm found the end tile or not.
             has_been_next, list over tiles that has been considered as the next tile.
    """
    frontier = PriorityQueue()
    frontier.put(start, 0)
    came_from = {start: None}
    cost_so_far = {start: 0}
    has_been_next = []
    success = False

    while not frontier.empty():
        current = frontier.pop()
        current.visit()

        if current == end:
            print("A* Pathfinder, successful.")
            success = True
            break

        for next_tile in current.neighbours:

            if next_tile not in has_been_next:
                has_been_next.append(next_tile)

            new_cost = cost_so_far[current] + next_tile.weight
            if next_tile not in cost_so_far or new_cost < cost_so_far[
                    next_tile]:
                cost_so_far[next_tile] = new_cost
                priority = new_cost + heuristic(end, next_tile)
                frontier.put(next_tile, priority)
                came_from[next_tile] = current

    return came_from, cost_so_far, success, has_been_next
Beispiel #5
0
def best_first_graph_search(problem, fun, stats=False):
    """Search the nodes with the lowest f scores first.
    You specify the function f(node) that you want to minimize; for example,
    if f is a heuristic estimate to the goal, then we have greedy best
    first search; if f is node.depth then we have breadth-first search.
    There is a subtlety: the line "f = memoize(f, 'f')" means that the f
    values will be cached on the nodes as they are computed. So after doing
    a best first search you can examine the f values of the path returned."""
    memfun = memoize(fun, 'f')
    node = Node(problem.initial)
    if problem.goal_test(node.state):
        return node
    frontier = PriorityQueue(order='min', f=memfun)
    frontier.append(node)
    explored = set()
    number_explored = 0
    added_frontier = 0
    while frontier:
        node = frontier.pop()
        #print "\n popped off frontier: " + str(node.state)
        if problem.goal_test(node.state):
            if stats:
                return node, number_explored, added_frontier
            else:
                return node

        explored.add(node.state)
        number_explored += 1

        for child in node.expand(problem):
            #print "child: " + str(child.state)
            if child.state not in explored and child not in frontier:
                frontier.append(child)
                added_frontier += 1
            elif child in frontier:
                incumbent = frontier[child]
                if memfun(child) < memfun(incumbent):
                    del frontier[incumbent]
                    frontier.append(child)
                    added_frontier += 1
    return None
Beispiel #6
0
def graph_search(problem):
    """graph_search(problem) - Given a problem representation
    attempt to solve the problem.
    Returns a tuple (path, path_cost) where:
    path - list of actions to solve the problem or None if no solution was found
    path_cost - Cost to execute the given path
    """

    initial_node = Node(problem, problem.initial,
                        problem.nodes[problem.initial])

    frontier_nodes = PriorityQueue(min, Node.get_total_cost)
    frontier_nodes.append(initial_node)

    explored_nodes = Explored()
    nodes_explored = 0

    while len(frontier_nodes) > 0:
        # Pop the next node from the frontier, add it to the explored set,
        # and increment the nodes_explored counter
        current_node = frontier_nodes.pop()
        explored_nodes.add(current_node.state)
        nodes_explored += 1

        #Check to see if the current node is a goal state
        if current_node.problem.goal_test(current_node.state):
            return (current_node.path(), current_node.total_cost)

        #Generate the possible actions from the current_node
        successor_nodes = current_node.expand(problem)

        #For each successor_node, if it hasn't been explored, add it to the frontier set
        for node in successor_nodes:
            if explored_nodes.exists(node.state) is False:
                frontier_nodes.append(node)

    print("No solution found.")
    return (None, nodes_explored)