def color_most_constrained_first(graphs, color): global spills, unspillable, num_unused, used_registers #print 'starting color_most_constrained_first' for v in graphs.vertices(): used_registers[v] = set([]) num_unused[v] = len(registers) - len(used_registers[v]) left = set(graphs.vertices()) - set(reserved_registers) - set(registers) queue = PriorityQueue(left, avail_reg_then_unspill) while not queue.empty(): v = queue.pop() if debug: print 'next to color is ' + v if v not in color.keys(): c = choose_color(v, color, graphs,False) color[v] = c for u in graphs.interferes_with(v): #if u in graphs.vertices(): queue.update(u) used_registers[u] |= set([c]) num_unused[u] = len(registers) - len(used_registers[u]) if not is_reg(c): spills += 1 return color
def djisktra(self, a, b): distances = [float("inf") for _ in self.vertices] distances[a] = 0 predecessors = [None for _ in self.vertices] # queue = PriorityQueue() queue = PriorityQueue() queue.enqueue((distances[a], self.vertices[a].label)) while True: if queue.empty(): break # print(queue) _, current = queue.dequeue() if current is b: break # dequeue a node we already looked at # this may not be necessary because it will just not decrease any travel times anyway else: # traverse adj list, and see if any are shorter than current dist for v in self.vertices[current].adj: temp = distances[current] + weight(self.vertices[current], self.vertices[v]) if distances[v] > temp: distances[v] = temp predecessors[v] = current queue.enqueue((temp, v)) # shouldn't this be (distances[v], v) count = 0 for distance in distances: if (distance != float("inf")): count+=1 #print((distances[b], predecessors[b], count)) return (distances, predecessors, count)
def color_most_constrained_first(graphs, color): global spills, unspillable, num_unused, used_registers #print 'starting color_most_constrained_first' for v in graphs.vertices(): used_registers[v] = set([]) num_unused[v] = len(registers) - len(used_registers[v]) left = set(graphs.vertices()) - set(reserved_registers) - set(registers) queue = PriorityQueue(left, avail_reg_then_unspill) while not queue.empty(): v = queue.pop() if debug: print 'next to color is ' + v if v not in color.keys(): c = choose_color(v, color, graphs, False) color[v] = c for u in graphs.interferes_with(v): #if u in graphs.vertices(): queue.update(u) used_registers[u] |= set([c]) num_unused[u] = len(registers) - len(used_registers[u]) if not is_reg(c): spills += 1 return color
class Sim: def __init__(self): self.q = PriorityQueue() self.time = 100 self.nodes = {} self.actors = [] self.done = False def add_actor(self, actor): actor.sim = self self.actors.append(actor) def at(self, event): if event.time < self.time: print "ERROR, time warp" else: self.q.put(event, event.time) def process(self): while not self.q.empty(): event = self.q.get() self.time = event.time try: (result, actor) = event.process(self) actor.send(result) except StopIteration: pass print "Sim done" def prime(self): for a in self.actors: a.prime() def go(self): self.prime() self.process()
class Jeu(): cpt = 0 positions = {} caches = {} caches["l1"] = {} caches["l2"] = {} references = {} clock = 0 strategie = CacheStrategie() def __init__(self, game, player, nom, init, goal, wallStates, goalStates): self.game = game self.player = player self.nom = nom self.position = init self.goal = goal self.graph = Graph((wallStates, goalStates), game.spriteBuilder.rowsize, game.spriteBuilder.colsize) self.chemin = [] self.frontier = PriorityQueue() self.frontier.put(init, 0) self.came_from = {} self.cost_so_far = {} self.came_from[init] = None self.cost_so_far[init] = 0 self.priority = 0 self.avoid = [] self.ID = Jeu.cpt Jeu.cpt += 1 Jeu.positions[self.nom] = init Jeu.caches["l1"][self.nom] = [] Jeu.references[self.nom] = self def play(self): i = 1 while (not self.frontier.empty()): position, cout = self.frontier.get() if (position == self.goal): self.frontier.clear() break for nextP in self.graph.neighbors(position): new_cost = self.cost_so_far[position] + self.graph.cost( position, nextP) if nextP not in self.cost_so_far or new_cost < self.cost_so_far[ nextP]: self.cost_so_far[nextP] = new_cost priority = new_cost + self.heuristic(self.goal, nextP) self.frontier.put(nextP, priority) self.came_from[nextP] = position i += 1 result = self.path() result.reverse() self.chemin = result Jeu.strategie.apply(self) def reset(self): self.graph.wall = list(set(self.graph.wall) - set(self.avoid)) self.chemin = [] self.avoid.clear() self.frontier.clear() self.frontier.put(self.position, 0) self.came_from = {} self.cost_so_far = {} self.came_from[self.position] = None self.cost_so_far[self.position] = 0 self.pause = 0 Jeu.caches["l2"][self.nom] = self.caches["l1"][self.nom] Jeu.caches["l1"][self.nom] = [] def done(self): for i in Jeu.references.values(): if (i.goal != (-1, -1)): return False return True def heuristic(self, a, b): xa, ya = a xb, yb = b return abs(xa - xb) + abs(ya - yb) def path(self): final = [] if (self.goal not in self.came_from): return final current = self.goal while (current != None): final.append(current) current = self.came_from[current] return final def freeze(self, n=1): self.priority += n def isObstacle(self, case): Jeu.positions[self.nom] = (-1, -1) temoin = case in Jeu.positions.values() Jeu.positions[self.nom] = self.position return temoin def move(self): if (Jeu.references[list(Jeu.references.keys())[0]] is self): Jeu.clock += 1 print("clock", Jeu.clock) if (self.priority > 0): print(self.nom, "FREEEEEEEEEEEEZE") self.priority -= 1 return # print("chemin: "+str(self.chemin)) if (len(self.chemin) == 0): # print("joueur {0}: RIEN A CHERCHER".format(self.nom)) Jeu.positions[self.nom] = self.position return if (self.isObstacle(self.chemin[0])): print("joueur {0}: conflit avec un autre joueur".format(self.nom)) Jeu.strategie.reply(self) return Jeu.caches["l1"][self.nom].append(self.position) row, col = self.chemin[0] self.player.set_rowcol(row, col) self.position = (row, col) if (len(self.chemin) > 0): self.chemin.pop(0) Jeu.positions[self.nom] = self.position #print("pos :", self.nom, self.position) self.game.mainiteration()
class Astar(WalkerBase): def __init__(self, maze): #super already sets the start as the current cell super(Astar, self).__init__(maze, maze.start()) self.strategy = "Euclidean" #make it possible to choose an option which heuristic can be used #current position not necessary, stored in walker #open list containing all cells to explore self.open = PriorityQueue() self.closed = dict()# node:parent self.g = 10 #total costs the agent took so far self.last = None self.closed[self._cell] = None def heuristic(self,cell): ''' :param currentPoint: :return: the distance (aka the costs) from the current point to reach the goal based on the current heuristic ''' return np.sqrt(np.square(maze_constants.XCELLS - cell._xLoc)+np.square(maze_constants.YCELLS - cell._yLoc)) #Function tracking back to the last decision point, recursive? def backToDecisionPoint(self,cell): #paint the current cell which will be temporarily discarded self.paint(self._cell,TEMPORARILYDISCARDED_COLOR) self.last = self._cell self._cell = cell def step(self): if self._cell is self._maze.start(): paths = self._cell.get_paths(last=self.last) #self._cell.parent where we came from for i in paths: costs = self.heuristic(self._cell) + self.g self.open.put([i,self._cell,0,self.g],costs) self.paint(i,OPENLIST_COLOR) self.last = self._cell #finished? if self._cell is self._maze.finish(): road = [] tmp = self._cell i = 0 while not (tmp._yLoc == 0 and tmp._xLoc == 0): road.append(tmp) tmp = self.closed[tmp] i+=1 road = road[::-1] for i in road: self.paint(i, FOUND_COLOR) self._isDone = True return #what are the possible steps from here? paths = self._cell.get_paths(last=self.last) #as long as there are cells in the open list, # get the one with the lowest costs next = self.open.get() while next[0] in self.closed.keys(): next = self.open.get() #continue the walk from where we are right now if next[1] == self._cell: self.paint(next[0],CLOSEDLIST_COLOR) self.closed[next[0]] = self._cell self._cell = next[0] self.g += 10 #is the next cell an adjacent cell of the current cell? elif not next[0] in paths: #discard the current position self.paint(self._cell,TEMPORARILYDISCARDED_COLOR) self._cell = next[0] self.last = next[1] self.g = next[2] self.closed[self._cell] = self.last self.paint(self.last,CLOSEDLIST_COLOR) self.paint(self._cell,CLOSEDLIST_COLOR) #Append the open list for the current position newPaths = self._cell.get_paths(last=self.last) if len(newPaths) > 0: for i in newPaths: if not i in self.closed: self.paint(i,OPENLIST_COLOR) f = self.heuristic(i) + self.g self.open.put([i,self._cell,self.g],f) if len(newPaths) == 0 and self.open.empty(): print("This is not suppossed to happen, please start new")