def dijkstra(start_tile, end_tile): """ Dijkstra's algorithm :param start_tile: Tile object, start tile of board :param end_tile: Tile object, end tile of board :return: """ queue = PriorityQueue() queue.put(start_tile, 0) came_from = {start_tile: None} cost_so_far = {start_tile: 0} has_been_next_tile = [] while not queue.empty(): current_tile = queue.get() current_tile.visit() if current_tile == end_tile: break for next_tile in current_tile.neighbours: if next_tile not in has_been_next_tile: has_been_next_tile.append(next_tile) new_cost = cost_so_far[current_tile] + 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 queue.put(next_tile, priority) came_from[next_tile] = current_tile return came_from, cost_so_far, has_been_next_tile
def ready_to_CPU(self): """ Moves process at head of ready queue to CPU """ if not PriorityQueue.empty(self): self.active = PriorityQueue.dequeue(self) self.active.set_proc_loc(self._dev_name) else: # Nothing in ready queue self.active = None print io.nothing_in_ready()
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
class DiskDrive(PriorityQueue): """ Initializes new disk drive with device name and two empty queues to implement FLOOK disk scheduling """ def __init__(self, dname, cyl): self._dev_type = "Disk Drive" self._dev_name = dname self._cylinders = cyl # Two priority queues to implement FSCAN. Q2 is frozen self._q1 = PriorityQueue() self._q2 = PriorityQueue(True) ## Methods to check/return device properties def get_num_cylinders(self): return self._cylinders def is_device_name(self, query_name): return True if self._dev_name == query_name else False def get_dev_name(self): return self._dev_name def is_device_type(self, query_type): return True if self._dev_type == query_type else False def get_dev_type(self): return self._dev_type def contains(self, pid): return (self._q1.contains(pid) or self._q2.contains(pid)) ## Scheduling methods def enqueue(self, proc): """ Enqueue processes to unfrozen queue. Update process location. If frozen queue is empty, unfreeze and freeze other queue """ if self._q1.is_frozen(): #Q1 is frozen, add to Q2 proc.set_proc_loc(self._dev_name) self._q2.enqueue(proc) if self._q1.empty(): self._q2.freeze() self._q1.unfreeze() else: #Q2 frozen, add to Q1 proc.set_proc_loc(self._dev_name) self._q1.enqueue(proc) if self._q2.empty(): self._q1.freeze() self._q2.unfreeze() def dequeue(self): """ Remove and return process at head of frozen queue. Clear any parameters passed when queued. Only dequeue processes from whichever queue is frozen. If dequeuing empties queue, freeze queue and unfreeze other queue """ if self._q1.is_frozen(): proc = self._q1.dequeue() if self._q1.empty(): self._q2.freeze() self._q1.unfreeze() else: proc = self._q2.dequeue() if self._q2.empty(): self._q1.freeze() self._q2.unfreeze() proc.clear_params() return proc def terminate(self, pid): if self._q1.contains(pid): self._q1.terminate(pid) if self._q1.is_frozen() and self._q1.empty(): self._q1.unfreeze() self._q2.freeze() elif self._q2.contains(pid): self._q2.terminate(pid) if self._q2.is_frozen() and self._q2.empty(): self._q2.unfreeze() self._q1.freeze() else: raise IndexError ## Methods to print device in human readable form to console def __repr__(self): return self._dev_name + " (" + self._dev_type.lower() + ")" def __str__(self): """ Returns device name and type as a string """ return self._dev_type + " " + self._dev_name def snapshot(self): """ Prints active processes in disk drive queue, in order they will be processed """ print io.snapshot_header(self._dev_name) if self._q1.empty() and self._q2.empty(): print '{:^78}'.format("EMPTY: No processes in queue") else: if self._q1.is_frozen(): print io.snapshot_header("PROCESSING [FROZEN]", "-") self._q1.snapshot() print io.snapshot_header("NEW REQUESTS", "-") self._q2.snapshot() else: print io.snapshot_header("PROCESSING [FROZEN]", "-") self._q2.snapshot() print io.snapshot_header("NEW REQUESTS", "-") self._q1.snapshot()
def timedGameScoreSearch(graph, playerKey, timeout): startPos = graph.getPosition(playerKey) counter = 0 frontier = PriorityQueue() graphKey = graph.getStateKey() foundKey = None frontier.put(graphKey, 0) cameFrom = {} costSoFar = {} startKey = graph.getStateKey() expandedNodes[startKey] = graph cameFrom[startKey] = None costSoFar[startKey] = 0 bestHeuristicSoFar = 99999 bestFoundSoFar = startKey targetScore = 50 while not frontier.empty(): counter += 1 if counter > 1999: break currentKey = frontier.get() current = expandedNodes[currentKey] if time.time() > timeout: foundKey = bestFoundSoFar logger.info("breaking because of timeout, counter: " + str(counter)) break #check for goal if current.getScore() > targetScore: foundKey = currentKey logger.info("breaking because found, counter: " + str(counter)) break nCounter = 0 for next in current.neighbors(playerKey): nCounter += 1 nextKey = next.getStateKey() expandedNodes[nextKey] = next newCost = costSoFar[currentKey] + 1 #graph.cost(current, next, playerKey) if nextKey not in costSoFar or newCost < costSoFar[nextKey]: costSoFar[nextKey] = newCost heuristic = next.cleverScoreHeuristic(targetScore) if heuristic < bestHeuristicSoFar and len(next.neighbors(playerKey)) > 0: bestFoundSoFar = nextKey bestHeuristicSoFar = heuristic priority = newCost + heuristic cameFrom[nextKey] = currentKey if len(next.neighbors(playerKey)) > 0: # add to frontier if I am alive in this NODE #Add large penalty for states where an opponent can blow me up so we only remove from frontier if absolutely nescecerry #get position nextPosition = next.getPosition(playerKey) inOpponentDangerZone = next.testIfInOpponentDanger(nextPosition) #logger.info("inOpponentDangerZone: %s" % inOpponentDangerZone) #check if in simulatedBombZone opponentDangerPenalty = 0 if inOpponentDangerZone: opponentDangerPenalty = 999 frontier.put(nextKey, priority + opponentDangerPenalty) #logger.info("returning from timedGameStarSearch, counter: " + str(counter)) return cameFrom, costSoFar, foundKey, startKey