示例#1
0
def aStar(start, goal, neighbor_func, distance_func, heuristic_func):
    """Returns a sequence of nodes that optmizes for the least cost
    from the start node to the goal.

    Let's describe the data that we pass to this function:

    start: the start of the search.
    goal: the goal of the search.
    neighbor_func: a function that, given a state, returns a list of
                   neighboring states.
    distance_func: a function that takes two nodes, and returns
                   the distance between them.
    heuristic_func: a function that takes two nodes, and returns
                    the heuristic distance between them.

    Each state mush be hashable --- each state must support the
    hash() function.
    """
    pqueue = PriorityQueue()
    g_costs = {start : 1}
    parents = {start : start}
    
    pqueue.push(heuristic_func(start, goal), start)
    while not pqueue.isEmpty():
        next_cost, next_node = pqueue.pop()
        g_costs[next_node] = g_costs[parents[next_node]] \
                             + distance_func(next_node, parents[next_node])
        if next_node == goal: break
        children = neighbor_func(next_node)
        for child in children:
            updateChild(goal, distance_func, heuristic_func,
                        child, next_node, parents, g_costs, pqueue)
    return getPathToGoal(start, goal, parents)
示例#2
0
文件: qsim.py 项目: joewing/ms3
 def run(self):
     pq = PriorityQueue()
     for q in self.queues:
         t = q.reset()
         pq.push(t, q)
     while not pq.empty():
         t = max(t, pq.key())
         q = pq.value()
         pq.pop()
         next_t = q.process(t)
         if next_t >= 0:
             pq.push(next_t, q)
     return t
示例#3
0
def greedyFirstSearch(graph, start, goal, heuristic):
	# initialize priority queue
	frontier = PriorityQueue()
	frontier.put(start, 0)
	previous = {}
	previous[start] = None
	counter = 1
	space = 0
	# if frontier isn't empty
	while not frontier.empty():
		current = frontier.get()
		# check if current is the goal
		if current == goal:
			break
		for next in graph.neighbors(current):
			if next not in previous:
				# Greedy Best First Search will only use the heuristic to determine the path to choose
				if heuristic == 1:
			 		heuristicValue = heuristicEuclidean(graph.getWeight(current), graph.getWeight(goal))
			 	else:
			 		heuristicValue = heuristicChebyshev(graph.getWeight(current), graph.getWeight(goal))
				priority = heuristicValue
				frontier.put(next, priority)
				counter = counter + 1
				previous[next] = current
			space = max(space, frontier.size())
	return previous, counter, space
示例#4
0
def aStarSearch(graph, start, goal, heuristic):
	# initialize Priority Queue
	frontier = PriorityQueue()
	frontier.put(start, 0)
	previous = {}
	currentCost = {}
	previous[start] = None
	currentCost[start] = 0
	counter = 1
	space = 0
	# while frontier is not empty
	while not frontier.empty():
		current = frontier.get()
		if current == goal:
			break
		for next in graph.neighbors(current):
			# determine A* cost
			new_cost = currentCost[current] + graph.distanceToDistination(graph.getWeight(current), graph.getWeight(next))
			# check if the cost has gone down since last time we visited to determine if location has already been visited
			if next not in currentCost or new_cost < currentCost[next]:
			 	currentCost[next] = new_cost
				# determine which heuristic to use
			 	if heuristic == 1:
			 		heuristicValue = heuristicEuclidean(graph.getWeight(current), graph.getWeight(goal))
			 	else:
			 		heuristicValue = heuristicChebyshev(graph.getWeight(current), graph.getWeight(goal))
			 	# add heuristic cose to A* cost
			 	priority = new_cost + heuristicValue
			 	# add path with it's priority
			 	frontier.put(next, priority)
			 	previous[next] = current
			 	counter = counter + 1
			 	space = max(space, frontier.size())
	return previous, currentCost, counter, space
示例#5
0
文件: astar.py 项目: zfq308/pylibs
    def __init__(self, world):
        self.world = world
        self.size = (len(world), len(world[0]))
#        self.open = SortedList()
        self.open = PriorityQueue()
        self.openValue = 1
        self.closedValue = 2
示例#6
0
    def get_path(self, start, end, board, cost_estimate=get_distance):
    
        t0 = time.time()

        explored = set()
        previous = {}
        previous[start] = None
        moves = {}
        moves[start] = 0

        frontier = PriorityQueue()
        frontier.insert(start, cost_estimate(start, end))

        if VERBOSE_ASTAR: print 'get_path start, end:', start, end

        while not frontier.is_empty():
        
            if (time.time() - t0 > PATHFINDER_TIMEOUT):
                print 'PATHFINDING TIMEOUT: Averting disconnect...'
                print '    get_path: Probably could not find a valid path from', start, 'to', end
                return [start, start] 

            if VERBOSE_ASTAR: print 'get_path frontier:', frontier

            current = frontier.remove()
            explored.add(current)

            if VERBOSE_ASTAR: print 'get_path explored set', explored
            if VERBOSE_ASTAR: print 'get_path current pos:', current

            if (current == end):
                if VERBOSE_ASTAR: print 'Found end loc'
                break
            else:
                neighbors = get_neighboring_locs(current, board)

                if VERBOSE_ASTAR: print 'get_path neighbors:', neighbors

                for n in neighbors:
                    if n not in explored and (board.passable(n) or n in (start, end)):
                        moves[n] = moves[current] + MOVE_COST
                        frontier.insert(n, cost_estimate(n, end) + moves[n])
                        previous[n] = current

        # found goal, now reconstruct path
        i = end
        path = [i]
        while i != start:
            if (i in previous):
                path.append(previous[i])
                i = previous[i]
            else:
                print 'get_path error: probably could not find a valid path from', start, 'to', end
                return [start, start]    # return something valid

        path.reverse()

        return path
示例#7
0
def dijkstra(G, start):
    pq = PriorityQueue()
    for v in G:
        v.setDistance(sys.maxsize)
        v.setPred(None)
    start.setDistance(0)
    pq.buildHeap([(v.getDistance(),v) for v in G])
    print(pq)
    while not pq.isEmpty():
        currentVert = pq.delMin()
        for nextVert in currentVert.getConnections():
            newDist = currentVert.getDistance() + currentVert.getWeight(nextVert)
            if newDist < nextVert.getDistance():
                nextVert.setDistance(newDist)
                nextVert.setPred(currentVert)
                pq.decreaseKey(nextVert, newDist)
        print(pq)
示例#8
0
def dijkstra(aGraph, start):
    """
	Find Single-Source shortest-paths on a weighted, directed graph
	Return shortest path
	aGraph: class Graph
	start: class Vertex
	"""
    pq = PriorityQueue()
    start.setDistance(0)
    pq.buildHeap([(v.getDistance(), v) for v in aGraph])
    while not pq.isEmpty():
        u = pq.delMin()
        for adjacent in u.getConnections():
            newDist = u.dist + u.getWeight(adjacent)
            if adjacent.dist > newDist:
                adjacent.setDistance(newDist)
                adjacent.setPred(u)
                pq.decreaseKey(adjacent, newDist)
    def dijkstra(self, label: str):
        self.__vertices__[label].weight = 0
        pq: PriorityQueue = PriorityQueue()
        for label in self.__vertices__:
            pq.insert(self.__vertices__[label])

        while not pq.is_empty():
            v: Vertex = pq.delete_min()
            for neighbour_label in self.__adjacency_map__[v.label]:
                neighbour: Vertex = self.__adjacency_map__[
                    v.label][neighbour_label]
                vertex: Vertex = self.__vertices__[neighbour_label]
                if v.weight + neighbour.weight < vertex.weight:
                    self.__prev__[neighbour_label] = v.label
                    self.__distance__[neighbour_label] = self.__distance__[
                        v.label] + 1
                    vertex.weight = v.weight + neighbour.weight
                    pq.decrease_key(vertex.key)
示例#10
0
def AStar(initial_state, heuristic_fn, # heuristic function must be provided
        avoid_backtrack = False, filtering = False, cutoff = INF,
        state_callback_fn = lambda state : False, # A callback function for extended states. If it returns True, terminate
        counter = {'num_enqueues':0, 'num_extends':0}): # A counter for

    frontier = PriorityQueue()
    frontier.append(initial_state, initial_state.get_path_cost() + heuristic_fn(initial_state))

    extended_filter = set()

    while frontier:  # frontier is False when it is empty. So just keep going until out of places to go...

        # choose next state to "extend" from frontier
        ext_node = frontier.pop()

        if (filtering and ext_node.get_all_features() in extended_filter):
            continue

        extended_filter.add(ext_node.get_all_features())

        counter['num_extends'] += 1

        # are we there? If so, return the node.
        if ext_node.is_goal_state():
            return ext_node

        # Update our caller (e.g. GUI) with the state we're extending.
        # Terminate search early if True is returned.
        if (state_callback_fn(ext_node)):
            break

        ### Update frontier with next states
        for state in ext_node.generate_next_states():
            if (avoid_backtrack and ext_node.get_parent() == state):
                continue

            if (filtering and state.get_all_features() in extended_filter):
                continue

            if (cutoff != INF and state.get_path_length() > cutoff):
                continue

            frontier.append(state, state.get_path_cost() + heuristic_fn(state))
            counter['num_enqueues'] += 1

    # if loop breaks before finding goal, search is failure; return None
    return None
示例#11
0
 def prims(self, label: str):
     result: str = ""
     self._vertices[label].weight = 0
     pq: PriorityQueue = PriorityQueue()
     for label in self._vertices:
         pq.insert(self._vertices[label])
     while not pq.is_empty():
         current: Vertex = pq.delete_min()
         if self._prev[current.label] is not None:
             result += self._prev[
                 current.label] + " -> " + current.label + ", "
         for neighbour in self._adjacency_map[current.label]:
             v: Vertex = self._vertices[neighbour.label]
             if neighbour.weight < v.weight:
                 v.weight = neighbour.weight
                 self._prev[v.label] = current.label
                 pq.decrease_key(v.key)
     print(result)
示例#12
0
class AStarPar(multiprocessing.Process):
    '''
    classdocs
    '''

    #----------------------------------------------------------------------
    def __init__(self, world, (tasks, results)):
        '''
        Constructor
        '''
        multiprocessing.Process.__init__(self)
        self.tasks = tasks
        self.results = results
        self.world = world
        self.size = (len(world), len(world[0]))
        self.open = PriorityQueue()
        self.openValue = 1
        self.closedValue = 2
示例#13
0
 def prims(self, label: str):
     result: str = ""
     self._vertices[label].set_weight(0)
     pq: PriorityQueue = PriorityQueue()
     for vertex_label in self._vertices:
         pq.insert(self._vertices[vertex_label])
     while not pq.is_empty():
         vertex: Vertex = pq.delete_min()
         if self._prev[vertex.get_label()] is not None:
             result += self._prev[vertex.get_label()] + " -> " + vertex.get_label() + ", "
         for neighbour_label in self._adjacency_map[vertex.get_label()]:
             neighbour_from_adjacency_map: Vertex = self._adjacency_map[vertex.get_label()][neighbour_label]
             neighbour_from_vertices: Vertex = self._vertices[neighbour_label]
             if neighbour_from_vertices.get_weight() > neighbour_from_adjacency_map.get_weight():
                 neighbour_from_vertices.set_weight(neighbour_from_adjacency_map.get_weight())
                 self._prev[neighbour_from_vertices.get_label()] = vertex.get_label()
                 pq.decrease_key(neighbour_from_vertices.get_key())
     print(result)
 def prims(self, label: str):
     result: str = ""
     index: int = self.findIndexByLabel(label)
     self.vertices[index].weight = 0
     pq = PriorityQueue()
     pq.buildHeap(self.vertices)
     current: Vertex
     while not pq.isEmpty():
         current = pq.deleteMin()
         print(current.label)
         if self.prev[current.label] is not None:
             result += self.prev[
                 current.label] + " -> " + current.label + ", "
         for neighbour in self.adjacencyList[current.label]:
             if neighbour.weight < self.vertices[neighbour.index].weight:
                 self.prev[self.vertices[
                     neighbour.index].label] = current.label
                 self.vertices[neighbour.index].weight = neighbour.weight
                 pq.decreaseKey(self.vertices[neighbour.index].key)
     print(result)
示例#15
0
def a_star_graph_search(map,start,goal):   
    
    """ Frontier and explored must be either a hash or tree for fast 
    membership testing
    
    In this implementation node doesn't need to be hashable because it is 
    not used in membership testing, a dic is used to associate keys and values.
    it may be better to create a Node class"""
    
    node = create_node(start, map, goal)
    if goal == start:
        node["path"].append(start)
        return node
    
    frontier = PriorityQueue()
    frontier.append(node)
    explored = set()
    
    while frontier:
        node = frontier.pop()
        state = node["state"]
        if goal == state:
            return node
        explored.add(state) 
        for action in map.roads[state]: 
            """child_node is not created here to not be called if in explored"""
            if action not in explored and action not in frontier:
                child_node = create_node(action, map, goal, node)
                frontier.append(child_node)
            elif action in frontier:
                child_node = create_node(action, map, goal, node)
                """frontier[child_node] = node with same state as child_node"""
                if child_node['f'] < frontier[child_node]['f']:
                    del frontier[frontier[child_node]]
                    frontier.append(child_node)            
    return None           
示例#16
0
def dijkstras(start):
    queue = PriorityQueue()
    queue.put(start, 0)
    visited = []
    distance = {start: 0}
    previous = {start: None}
    inf = float('inf')

    while not queue.empty():
        u = queue.get()
        visited.append(u)

        for v in u.neighbors:
            if v not in visited:
                tempDistance = distance.get(u, inf) + u.getWeight(v)
                if tempDistance < distance.get(v, inf):
                    distance[v] = tempDistance
                    queue.put(v, tempDistance)
                    previous[v] = u

    return distance
示例#17
0
def a_search(graph, start, goals):
    my_heap = PriorityQueue(
    )  #not really a heap just easier to call it that than queue
    my_heap.push(start, 0)
    pathway = []
    cost_so_far = {}
    came_from = {}
    cost_so_far[start] = 0
    came_from[start] = None
    the_sum = 0
    ordered_goals = []
    while not my_heap.empty():
        current = my_heap.pop()
        #print("here")
        if current in goals:
            ordered_goals.append(current)
            goals.remove(current)
            for i in graph:
                if i.parent:
                    the_sum += 1
            while current.parent:
                pathway.append(current)
                x = current.parent
                current.parent = None
                current = x
        if len(goals) == 0:
            break
        for i in current.edges:
            new_score = current.gscore + 1  #increment g(n)
            if i not in cost_so_far or new_score < i.gscore:
                cost_so_far[i] = new_score
                i.gscore = new_score
                i.hscore = findMST(i, goals)
                #print(i.hscore, current)
                i.fscore = i.gscore + i.hscore
                my_heap.push(i, i.fscore)
                if not i.parent:
                    i.parent = current
    return pathway, the_sum, ordered_goals
示例#18
0
 def dijkstra(self, label: str):
     self._vertices[label].set_weight(0)
     pq: PriorityQueue = PriorityQueue()
     for vertex_label in self._vertices:
         pq.insert(self._vertices[vertex_label])
     while not pq.is_empty():
         vertex: Vertex = pq.delete_min()
         for neighbour_label in self._adjacency_map[vertex.get_label()]:
             neighbour_from_adjacency_map: Vertex = self._adjacency_map[
                 vertex.get_label()][neighbour_label]
             neighbour_from_vertices: Vertex = self._vertices[
                 neighbour_label]
             if neighbour_from_vertices.get_weight() > \
                     vertex.get_weight() + neighbour_from_adjacency_map.get_weight():
                 neighbour_from_vertices.set_weight(
                     vertex.get_weight() +
                     neighbour_from_adjacency_map.get_weight())
                 self._prev[neighbour_from_vertices.get_label(
                 )] = vertex.get_label()
                 pq.decrease_key(neighbour_from_vertices.get_key())
示例#19
0
def prim(g, start):
    pq = PriorityQueue()
    for v in g:
        v.setPred(None)
        v.setdistance(sys.maxsize)
    start.setdistance(0)
    pq = buildheap([(v.getdistance(), v) for v in g])
    while not pq.isEmpty():
        currentvert = pq.delmin()
        for nextvert in currentvert.get_connections():
            newcost = currentvert.get_weight(nextvert)
            if nextvert in pq and newcost < nextvert.getdistance():
                nextvert.setpred(currentvert)
                nextvert.setdistance(newcost)
                pq.decreasekey(nextvert, newcost)
示例#20
0
def main():
    maze = Maze("maze2.png")
    paths = PriorityQueue()

    start = maze.getStart()
    end = maze.getEnd()
    paths.insert(PathHead(start[0], start[1], calcDistance(start, end)))
    current = paths.minimum()

    while paths.size() > 0 and current.getDistance() != 0.0:
        current = paths.extractMin()
        maze.setNodeVisited(current.getCords())
        surroundings = maze.checkSurroundings(current.getCords())
        insertSurroundings(paths, surroundings, current, end)

    solved = maze.getMaze()
    solved = numpy.array(solved)
    img = Image.fromarray(solved.astype('uint8'), 'RGB')
    img.save('solved.png')
    def prims(self, label: str):
        self.__vertices__[label].weight = 0
        pq: PriorityQueue = PriorityQueue()
        for label in self.__vertices__:
            pq.insert(self.__vertices__[label])

        result: str = ""
        while not pq.is_empty():
            v: Vertex = pq.delete_min()
            if self.__prev__[v.label] is not None:
                result += self.__prev__[v.label] + " - " + v.label + ", "
            for neighbour_label in self.__adjacency_map__[v.label]:
                neighbour: Vertex = self.__adjacency_map__[
                    v.label][neighbour_label]
                vertex: Vertex = self.__vertices__[neighbour_label]
                if neighbour.weight < vertex.weight:
                    self.__prev__[neighbour_label] = v.label
                    vertex.weight = neighbour.weight
                    pq.decrease_key(vertex.key)

        print(result)
示例#22
0
def dijkstra(source, graph):
    pQueue = PriorityQueue()
    graph[source]['dist'] = 0

    for v in graph:
        pQueue.enqueue(v, graph[v]['dist'])

    while not pQueue.isEmpty():
        u = pQueue.dequeue()
        baseDist = graph[u]['dist']
        for w in graph[u]['edgeTo']:
            edgeLen = graph[u]['edgeTo'][w]
            newDist = baseDist + edgeLen
            currentDist = graph[w]['dist']
            if newDist < currentDist:
                graph[w]['dist'] = newDist
                pQueue.changePriority(w, newDist)

    distanceList = []
    for v in graph:
        distanceList.append((v, graph[v]['dist']))

    return distanceList
def Astar(puzzle8, came_from):
    frontier = PriorityQueue()
    cost_so_far = {}
    frontier.enqueue(puzzle8, 0)
    cost_so_far[puzzle8.ToString()] = puzzle8.cost
    came_from[puzzle8.ToString()] = None
    while not frontier.is_empty():
        puzzle8 = frontier.dequeue()
        
        if puzzle8.isGoal():
            return puzzle8
        else:
            moves = puzzle8.getAllMoves()
            for move in moves:
                newpuzzle8 = puzzle8.clone()
                newpuzzle8.move(*move)
                new_cost = newpuzzle8.cost
                if cost_so_far.get(newpuzzle8.ToString()) == None or \
                   new_cost < cost_so_far[newpuzzle8.ToString()]:
                    cost_so_far[newpuzzle8.ToString()] = new_cost
                    priority = new_cost + newpuzzle8.heuristics
                    frontier.enqueue(newpuzzle8, priority)
                    came_from[newpuzzle8.ToString()] = puzzle8
    return None
示例#24
0
def djkistra(sourceId: int, vertices: list, vertexDict: dict, edgeList: list):
    sourcePair = Pair(sourceId)

    visited = set()
    unvisited = PriorityQueue(contents=[sourcePair])

    # build mapping labels -> vertexId & vertexId -> labels
    labelsDict = {
        int(v.attributes["label"].value): int(v.attributes["vertexId"].value)
        for v in vertices
    }
    labels = [labelsDict[i] for i in range(len(labelsDict))]
    previousLabelsDict = {v: k for k, v in labelsDict.items()}

    vertexDict[sourceId].setCost(0)

    vertexDict[sourceId].setPrevious(sourceId)

    while not unvisited.isEmpty():
        currentPair = unvisited.dequeue()

        visited.add(currentPair.getVertexId())

        currentVertex = vertexDict[currentPair.getVertexId()]
        # grab adjacents.
        adjacents = currentVertex.getAdjacents(edgeList)

        for e in adjacents:
            dist = vertexDict[currentVertex.vertexId].getCost() + e.weight
            for vertex in [e.v1, e.v2]:
                if vertex not in visited:
                    if vertexDict[vertex].getCost() > dist:
                        vertexDict[vertex].setCost(dist)
                        vertexDict[vertex].setPrevious(
                            currentVertex.getVertexId())
                        # heapq.heappush(unvisited, Pair(vertex, dist))
                        unvisited.enqueue(Pair(vertex, dist))

    for i in range(len(visited)):
        print("Vertex:")
        print("  label: {}".format(i))
        print("  cost: {:.2f}".format(vertexDict[labels[i]].getCost()))
        print("  previous: {}\n".format(
            previousLabelsDict[vertexDict[labelsDict[i]].getPrevious()]))

    return labelsDict
示例#25
0
def prims_algorithm_mst(graph):
    """
  Prim's algorithm, this algorithm
  has the same time complexity as Djikstra's
  single source shorted path algorithm.

  This particular algorithm is

  O((V ** 2) + (V * E))

  but with a priority queue or vEB tree this can be reduced
  to

  O((V * log(V)) + (V * E))

  a time complexity equivalent to Djikstra's

  """
    if not isinstance(graph, Graph):
        raise TypeError('this function expects an instance of Graph')
    queue = PriorityQueue(graph)
    root = None
    nodes = {u: TreeNode(u) for u in graph.vertices}
    while not queue.is_empty():
        u = queue.pop_min()
        if root is None:
            root = nodes[u]
        for v in graph.adj[u]:
            if queue.contains(v):
                queue.update(v, graph.weights[(u, v)])
                nodes[v].parent = nodes[u]
    for n in nodes:
        node = nodes[n]
        if node.parent is not None:
            node.parent.children.append(node)
    return root
 def setUp(self):
     self.pq = PriorityQueue(":memory:")
示例#27
0
    """Pretty-print a tree."""
    output = StringIO()
    last_row = -1
    for i, n in enumerate(tree):
        if i:
            row = int(math.floor(math.log(i+1, 2)))
        else:
            row = 0
            if row != last_row:
                output.write('\n')
                columns = 2**row
                col_width = int(math.floor((total_width * 1.0) / columns))
                output.write(str(n).center(col_width, fill))
                last_row = row
                print output.getvalue()
                print '-' * total_width
                print
                return

pq = PriorityQueue()

pq.add(5, "Sam")
pq.add(23, "Sam")
pq.add(3, "Sam")
pq.add(45, "Sam")

print pq.remove_min()
print pq.remove_min()
print pq.remove_min()
print pq.remove_min()
示例#28
0
def minimum_spanning_tree(graph):

    min_heap = PriorityQueue(True)
    vertex_to_edge = {}
    result = []

    for vertex in graph.all_vertex.values():
        min_heap.add_task(sys.maxsize, vertex)

    start_vertex = next(iter((graph.all_vertex.values())))
    min_heap.change_task_priority(0, start_vertex)
    while min_heap.is_empty() is False:
        current = min_heap.pop_task()

        if (current in vertex_to_edge):
            spanning_tree_edge = vertex_to_edge[current]
            result.append(spanning_tree_edge)

        for edge in current.edges:
            adjacent = get_other_vertex_for_edge(current, edge)
            if min_heap.contains_task(
                    adjacent) is True and min_heap.get_task_priority(
                        adjacent) > edge.weight:
                min_heap.change_task_priority(edge.weight, adjacent)
                vertex_to_edge[adjacent] = edge

    return result
class TestPriorityQueue(unittest.TestCase):

    def setUp(self):
        self.pq = PriorityQueue(":memory:")

    def test_empty(self):
        result = self.pq.is_empty()
        self.assertTrue(result)

    def test_order(self):
        self.assertEqual("hello", self.pq.push(10, "hello"))
        self.pq.push(1, "foo")
        self.pq.push(30, "bar")
        self.pq.push(5, "baz")

        self.assertEqual("bar", self.pq.pop())
        self.assertEqual("hello", self.pq.pop())
        self.assertEqual("baz", self.pq.pop())
        self.assertEqual("foo", self.pq.pop())
示例#30
0
def shortest_path(graph, sourceVertex):

    min_heap = PriorityQueue(True)
    distance = {}
    parent = {}

    for vertex in graph.all_vertex.values():
        min_heap.add_task(sys.maxsize, vertex)

    min_heap.change_task_priority(0, sourceVertex)
    distance[sourceVertex] = 0
    parent[sourceVertex] = None

    while min_heap.is_empty() is False:
        task = min_heap.peek_task()
        weight = min_heap.get_task_priority(task)               
        current =  min_heap.pop_task()
        distance[current] = weight

        for edge in current.edges:
            adjacent = get_other_vertex_for_edge(current, edge)
            if min_heap.contains_task(adjacent) is False:
                continue

            new_distance = distance[current] + edge.weight;
            if min_heap.get_task_priority(adjacent) > new_distance:
                min_heap.change_task_priority(new_distance, adjacent)
                parent[adjacent] = current
                

    return distance
示例#31
0
def setup(N):
    global pq
    pq = PriorityQueue([random.randrange(0, N) for i in range(0, N)])
class PQueueTestCase(unittest.TestCase):
    '''Test creation and use of a priority queue.'''
    
    def setUp(self):
        self.pq = PriorityQueue()
        self.r1 = Rectangle(0, 150, 200, 50, media.forestgreen, 1)
        self.o1= Oval(120, 160, 60, 60, media.white, 4)
        self.o2 = Oval(120, 115, 45, 45, media.yellow, 3)
        self.o3 = Oval(120, 80, 30, 30, media.orange, 2)

    def tearDown(self):
        self.pq = None
        self.r1 = None
        self.o1 = None
        self.o2 = None
        self.o3 = None
            
    def testSize(self):
        assert self.pq.size() == 0, 'mismatch in predicted pqueue size'
        
    def testEnqueueSize(self):
        self.pq.enqueue(self.r1)
        assert self.pq.size() == 1, \
               'mismatch in pqueue size after enqueue'

    def testDequeue(self):
        self.pq.enqueue(self.r1)
        result = self.pq.dequeue()
        assert result is self.r1, \
               'mismatch in dequeued value'

    def testMultipleEnqueueSize(self):
        self.pq.enqueue(self.o1)
        self.pq.enqueue(self.o2)
        self.pq.enqueue(self.o3)
        assert self.pq.size() == 3, \
               'mismatch in pqueue size after enqueues'

    def testMultipleDequeue(self):
        self.pq.enqueue(self.o1)
        self.pq.enqueue(self.o2)
        self.pq.enqueue(self.o3)
        result = self.pq.dequeue()
        assert result is self.o3, 'mismatch in dequeuing correct value'
示例#33
0
        print ("outfile: a GeoJSON featurecollection of points and polygons\n")
        exit(0)

    pointList = parse_input(sys.argv[1])

    pointList = []
    #import random

    #for a in range(0,200):
    #    pointList.append(((random.randint(0,1000), random.randint(0,1000)), None))

    pointList.append(((8,12), None))
    pointList.append(((16,9), None))
    pointList.append(((3,5), None))
    pointList.append(((6,1), None))
    sites = PriorityQueue(pointList[:200])



    #Test
    counter = 1
    # Go through sites
#    while sites and counter < 20:
    while sites:
#        try:
        s = sites.pop()
        #Check if site event
        if s[1] == None:
            #print (s)
            handle_site(s[0])
        else:
示例#34
0
文件: astar.py 项目: zfq308/pylibs
class AStar():
    '''
    Properties:

    public:
    - world: 2D array of Nodes

    internal:
    - size: (width, height) tuple of world
    - open: Nodes queue to evaluate (heap-based priority queue)
    '''

    #----------------------------------------------------------------------
    def __init__(self, world):
        self.world = world
        self.size = (len(world), len(world[0]))
#        self.open = SortedList()
        self.open = PriorityQueue()
        self.openValue = 1
        self.closedValue = 2

    #----------------------------------------------------------------------
    def initSearch(self, start, goal, obstacles):
        ''' first, check we can achieve the goal'''
        if goal.type in obstacles:
            return False

        ''' clear open list and setup new open/close value state to avoid the clearing of a closed list'''
        self.open.clear()
        self.openValue += 2
        self.closedValue += 2
        
        ''' then init search variables'''
        self.start = start
        self.goal = goal
        self.obstacles = obstacles
        self.start.cost = 0
        self.addToOpen(self.start)
        self.goal.parent = None
        return True

    #----------------------------------------------------------------------
    def search(self):
        while not self.openIsEmpty():
            current = self.popFromOpen()
            if current == self.goal:
                break
            self.removeFromOpen(current)
            self.addToClosed(current)

            ''' generator passes : look at the 8 neighbours around the current node from open'''
            for (di, dj) in [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)]:
                neighbour = self.getNode(current.i + di, current.j + dj)
                if (not neighbour) or (neighbour.type in self.obstacles):
                    continue

                '''the cost to get to this node is the current cost plus the movement
                cost to reach this node. Note that the heuristic value is only used
                in the open list'''
                nextStepCost = current.cost + self.getNeighbourCost(current, neighbour)
                
                '''if the new cost we've determined for this node is lower than 
                it has been previously makes sure the node has not been
                determined that there might have been a better path to get to
                this node, so it needs to be re-evaluated'''
                
                if nextStepCost < neighbour.cost and (self.inOpenList(neighbour) or self.inClosedList(neighbour)):
                    self.invalidateState(neighbour)
                        
                '''if the node hasn't already been processed and discarded then
                step (i.e. to the open list)'''
                if (not self.inOpenList(neighbour)) and (not self.inClosedList(neighbour)):
                    neighbour.cost = nextStepCost
                    neighbour.heuristic = self.getHeuristicCost(neighbour, self.goal)
                    neighbour.parent = current
                    self.addToOpen(neighbour)

            ''' exit with None = path not yet found'''
            yield None

        '''since we've run out of search 
        there was no path. Just return'''
        if self.goal.parent is None:
            return
        
        '''At this point we've definitely found a path so we can uses the parent
        references of the nodes to find out way from the target location back
        to the start recording the nodes on the way.'''
        path = []
        goal = self.goal
        while goal is not self.start:
            path.insert(0, (goal.i, goal.j))
            goal = goal.parent
        
        ''' done, exit with path'''
        yield path

    #-----------------------------------------------------------------------------
    def getNode(self, i, j):
        if i >=0 and i < self.size[0] and j >= 0 and j < self.size[1]:
            return self.world[i][j]
        else:
            return None

    #----------------------------------------------------------------------
    def getNeighbourCost(self, n1, n2):
        return (abs(n2.i - n1.i) + abs(n2.j - n1.j))
    
    #----------------------------------------------------------------------
    def getHeuristicCost(self, n1, n2):
        return (abs(n2.i - n1.i) + abs(n2.j - n1.j))
    
    #----------------------------------------------------------------------
    def invalidateState(self, node):
        node.state = 0

    #----------------------------------------------------------------------
    def popFromOpen(self):
#        return self.open.first()
        return self.open.pop()

    #----------------------------------------------------------------------
    def addToOpen(self, node):
#        self.open.add(node)
        self.open.insert(node)
        node.state = self.openValue
        
    #----------------------------------------------------------------------
    def inOpenList(self, node):
        return node.state is self.openValue
   
    #----------------------------------------------------------------------
    def removeFromOpen(self, node):
#        self.open.remove(node)
        self.open.remove(node)
        node.state = 0

    #----------------------------------------------------------------------
    def openIsEmpty(self):
#        return not self.open.size()
        return self.open.isEmpty()
        
    #----------------------------------------------------------------------
    def addToClosed(self, node):
        node.state = self.closedValue
        
    #----------------------------------------------------------------------
    def inClosedList(self, node):
        return node.state is self.closedValue
示例#35
0
 def test_init(self):
     q = PriorityQueue()
     assert q.front() is None
     assert q.length() == 0
     assert q.is_empty() is True
示例#36
0
 def test_front(self):
     q = PriorityQueue()
     assert q.front() is None
     q.enqueue('A', 6)
     assert q.front() == 'A'
     q.enqueue('B', 10)
     assert q.front() == 'A'
     q.dequeue()
     assert q.front() == 'B'
     q.dequeue()
     assert q.front() is None
示例#37
0
 def test_enqueue(self):
     q = PriorityQueue()
     q.enqueue('A', 3)
     assert q.front() == 'A'
     assert q.length() == 1
     q.enqueue('B', 1)
     assert q.front() == 'B'
     assert q.length() == 2
     q.enqueue('C', 4)
     assert q.front() == 'B'
     assert q.length() == 3
     assert q.is_empty() is False
示例#38
0
 def test_length(self):
     q = PriorityQueue()
     assert q.length() == 0
     q.enqueue('A', 5)
     assert q.length() == 1
     q.enqueue('B', 1)
     assert q.length() == 2
     q.dequeue()
     assert q.length() == 1
     q.dequeue()
     assert q.length() == 0
示例#39
0
from priorityqueue import PriorityQueue
import random


""" A script representing one round of stock trading we assume each buyer and
seller is looking to buy or sell exactly 100 shares. """

buyers = [{"name": "Sam", "bought": 0},
          {"name": "Rickie", "bought": 0},
          {"name": "Matt", "bought": 0}]

sellers = [{"name": "Alex", "sold": 0},
           {"name": "Daniel", "sold": 0},
           {"name": "Thomas", "sold": 0}]

buy_orders, sell_orders = PriorityQueue(), PriorityQueue()

for e in buyers:
    buy_orders.add(random.randint(5, 100), e)

for e in sellers:
    sell_orders.add(random.randint(5, 100), e)

while len(buy_orders) != 0:
    buy = buy_orders.remove_min()
    if buy[0] < sell_orders.min()[0]:
        # add to a list for next round
        pass
    else:
        buy[1]["bought"] += 100
        sell_orders.remove_min()[1]["sold"] += 100
示例#40
0
import priorityqueue
from priorityqueue import PriorityQueue
import numpy as np

pq = PriorityQueue(0,20)
ints = np.random.randint(1,100, size=20)
print("Inserting 20 integers into pq: {0}".format(ints))
[pq.insert(i) for i in ints]
print("pq is full: {0}".format(pq.isFull()))
print("pq size: {0}".format(pq.size()))
print("Deleting 20 integers from pq: {0}".format([pq.delMin() for i in range(20)], sep=','))
print("pq is empty: {0}".format(pq.isEmpty()))
print("pq size: {0}".format(pq.size()))
示例#41
0
 def test_dequeue(self):
     q = PriorityQueue()
     q.enqueue('A', 1)
     q.enqueue('B', 2)
     q.enqueue('C', 3)
     assert q.dequeue() == 'A'
     assert q.length() == 2
     assert q.dequeue() == 'B'
     assert q.length() == 1
     assert q.dequeue() == 'C'
     assert q.length() == 0
     assert q.is_empty() is True
     with self.assertRaises(ValueError):
         q.dequeue()
示例#42
0
import priorityqueue
from priorityqueue import PriorityQueue
import numpy as np

pq = PriorityQueue(0, 20)
ints = np.random.randint(1, 100, size=20)
print("Inserting 20 integers into pq: {0}".format(ints))
[pq.insert(i) for i in ints]
print("pq is full: {0}".format(pq.isFull()))
print("pq size: {0}".format(pq.size()))
print("Deleting 20 integers from pq: {0}".format(
    [pq.delMin() for i in range(20)], sep=','))
print("pq is empty: {0}".format(pq.isEmpty()))
print("pq size: {0}".format(pq.size()))
示例#43
0
class Navi:
    def __init__(self, position_start, position_finish, map):
        tiles = []
        self.open_list = PriorityQueue()
        self.closed_list = PriorityQueue()
        # queue = PriorityQueue()
        self.map = map
        self.finish_reached = False
        self.route = []
        self.position_start = position_start
        self.position_finish = position_finish
        self.open_list.insert(
            TileInfo(position_start,
                     self.get_estimated_cost_to_finish(position_start), 0, -1,
                     -1))
        for y in range(0, map.height):
            tiles.append([])
            for x in range(0, map.width):
                tile = TileInfo((y, x), map.tiles[y][x],
                                self.get_estimated_cost_to_finish((y, x)),
                                99999, -1)
                tiles[y].append(tile)
        self.tiles = tiles
        self.navi_active = False
        self.recursion_level = 0
        self.max_recursion_level = 100
        self.use_diagonal_tiles = True

        # Array für die Abfrage der umgebenden Tiles
        self.surroundings = []
        if self.use_diagonal_tiles == True:
            self.surroundings.append((-1, -1))
            self.surroundings.append((-1, +1))
            self.surroundings.append((+1, -1))
            self.surroundings.append((+1, +1))
        self.surroundings.append((-1, 0))
        self.surroundings.append((0, -1))
        self.surroundings.append((0, +1))
        self.surroundings.append((+1, 0))

    def navi_step(self, tile_work='next'):
        # map = self.map
        # print('navistep')
        self.recursion_level += 1
        if tile_work == 'next':
            tile_work = self.open_list.get_and_delete()

        # pre_tile = self.tiles[tile_work.position[0]][tile_work.position[1]].pre_tile

        # Den Vorgänger-Tile des work-Tiles holen
        pre_tile = self.get_pre_tile(tile_work)
        # Wenn der Tile > -1 ist, hole die Kosten zum Start.
        if not pre_tile == -1:
            pre_tile_cost_from_start = self.tiles[pre_tile[0]][
                pre_tile[1]].cost_from_start
        else:
            pre_tile_cost_from_start = -1

        # Wenn der Work-Tile die Zielposition, also das Ziel erreicht ist.
        if tile_work.position == self.position_finish:
            self.map.add_status_text_with_clear("FINISH")
            tile_work.set_route_cost(pre_tile_cost_from_start + 1)
            self.route_finished(tile_work)
            self.finish_reached = True
        if pre_tile_cost_from_start >= 99999:
            pre_tile_cost_from_start = 0

        # Work-Tile: Die Kosten zum Start sind Pre-Tile + 1
        tile_work_cost_from_start = pre_tile_cost_from_start + 1
        tile_work.set_cost_from_start(tile_work_cost_from_start)
        tile_work.set_route_cost(
            self.get_estimated_cost_to_finish(tile_work.position) +
            tile_work.cost_from_start)
        tile_work.status = 0
        # Der Work-Tile wurde berechnet und kann also auf die Closed-List
        self.closed_list.insert(tile_work)
        self.tiles[tile_work.position[0]][
            tile_work.position[1]].type = "closed"

        # Um weiter zu machen, holen wir uns die umgebenden Tiles
        surrounding_tiles = self.get_surrounding_tiles(tile_work.position)

        # Solange wir noch nicht alle Tiles bearbeitet haben, durchlaufen wir die while-Schleife
        while not surrounding_tiles.isEmpty():
            # print(surrounding_tiles.get_size())
            surrounding_tile = surrounding_tiles.get_and_delete()

            if surrounding_tile == False:
                # print("Surround: no next tiles")
                break
            if surrounding_tile.type == "wall":
                # print('Surround: wall')
                continue

            tile_cost_from_start = tile_work_cost_from_start + 1

            if self.closed_list.exist(surrounding_tile):
                # Wenn ein Tile bereits in der closedlist ist, wurde er schon mal hinzugefügt
                # Es wird dann gecheckt, ob ...?
                # print('Surround: is in closedlist')
                continue
            elif self.open_list.exist(surrounding_tile):
                # Wenn ein Tile bereits in der openlist ist, wurde er schon mal hinzugefügt
                # Es wird dann gecheckt, ob ...?
                # print('Surround: is in openlist')
                tile_from_open_list = self.open_list.get_tile_and_delete(
                    surrounding_tile)
                # print(tile_from_open_list.cost_from_start, tile_cost_from_start)
                if tile_from_open_list.cost_from_start + 1 >= tile_cost_from_start:
                    # print('Surround: Neuer Weg ist teurer')
                    continue
                else:
                    # print('Surround: Neuer Weg ist günstiger')
                    tile_from_open_list.cost_from_start = surrounding_tile.cost_from_start + 1
                    tile_from_open_list.set_route_cost(
                        self.get_estimated_cost_to_finish(
                            tile_from_open_list.position) +
                        tile_work_cost_from_start)
                    self.open_list.insert(tile_from_open_list)
                    continue
            else:
                if surrounding_tile.position == tile_work.pre_tile:
                    # Wenn der umliegende Tile der vorherige vom tile_work ist, kann er ignoriert werden
                    continue
                # Wenn bis hierher nichts dagegen spricht, ist der Tile legitim, um ihn in nem navistep zu bearbeiten
                # pre-tile festlegen
                surrounding_tile.pre_tile = tile_work.position
                # Den pre-tile auch in der tiles.Liste festlegen
                self.tiles[surrounding_tile.position[0]][
                    surrounding_tile.position[1]].pre_tile = tile_work.position

                # In die open-list einfügen
                self.open_list.insert(surrounding_tile)

                # Entsprechenden Tile als open markieren
                self.tiles[surrounding_tile.position[0]][
                    surrounding_tile.position[1]].type = "open"

        # print("Open List: ", self.open_list.get_size())
        # print("Closed List: ", self.closed_list.get_size())
        # print(self.finish_reached)
        # if self.finish_reached == False and self.recursion_level < self.max_recursion_level:

        #     self.navi_step()
        self.recursion_level = 0
        return (tile_work.position, tile_work.route_cost)

        # self.navi_step(tile.position,position)

    def route_finished(self, tile):
        """ Route wurde gefunden! """
        route = []
        route.append(tile.position)
        next_tile = tile.pre_tile
        while True:
            route.append(next_tile)
            if len(route) > 1000:
                print('Finish: Route > 1000')
                break
            # print(next_tile)
            next_tile = self.tiles[next_tile[0]][next_tile[1]].pre_tile
            if next_tile == self.position_start:
                print('Finish: Start erreicht.')
                break
            if next_tile == -1:
                break

        for tile_position in route:
            self.tiles[tile_position[0]][tile_position[1]].type = "route"
        self.map.add_status_text("Kosten: " + str(tile.get_route_cost()))
        print("Kosten: ", tile.get_route_cost())
        self.map.add_status_text("Länge Route: " + str(len(route)))
        print("Länge Route: ", len(route))
        # print(route)
        self.navi_active = False
        self.position_start = tile.position

    def get_next_navi_tile(self, surrounding_tiles, position, last_position):
        """ Liefert den nächsten Navi-Tile zurück. Checkt, ob alle Bedingungen eingehalten werden."""
        # Bedingungen:
        # 1. Tiletype != wand
        # 2. Tiletype != navi
        # 3. Tiletype != last_position
        # 4. Tile ist in self.queue
        for tile in surrounding_tiles:
            if not tile:
                return False
            tile_type = self.map.get_tile_type(tile.position)
            print(tile.position, tile_type)
            if not tile_type == "wall" and not tile_type == "navi" and not tile.position == last_position:
                return tile

        print("Sackgasse?")
        return False
        # if tile_surround.position == self.position_finish:
        #     print("FINISH")
        #     print("Routenlänge: ",len(self.route))

    def get_estimated_cost_to_finish(self, position):
        """ Liefert die estimated cost an gegebener Position zurück."""
        distance_to_point = float(
            sqrt((position[0] - self.position_finish[0])**2 +
                 (position[1] - self.position_finish[1])**2))
        return distance_to_point

    def get_pre_tile(self, tile):
        """ Liefert den Vorgänger zurück """
        # print('get_pre_tile()')
        surrounding_tiles = self.get_surrounding_tiles(tile.position,
                                                       order='start')
        # print('surrounding_tiles: ', surrounding_tiles)
        pre_tile = surrounding_tiles.get_and_delete()
        # print('pre_tile: ', pre_tile)
        return pre_tile.position

    def get_surrounding_tiles(self, position, order='finish'):
        """ Liefert eine Queue der angrenzenden Tiles zurück."""
        tiles = PriorityQueue(order)
        # print('Order: ', order)
        # self.surroundings

        for surround in self.surroundings:
            # Ränder abfragen
            # y unten
            if position[0] == len(self.tiles) - 1 and surround[0] == +1:
                continue
            # y oben
            if position[0] == 0 and surround[0] == -1:
                continue
            # x rechts
            if position[1] == len(self.tiles[0]) - 1 and surround[1] == +1:
                continue
            # x links
            if position[1] == 0 and surround[1] == -1:
                continue

            x = position[1] + surround[1]
            y = position[0] + surround[0]
            tiles.insert(self.tiles[y][x])

        # Wenn Position am unteren Rande der y-Achse ist

        # tiles.sort(key=lambda x: x.estimated_cost_to_finish, reverse=False)
        return tiles

    def show_open_list(self):
        for item in self.open_list.queue:
            print(item.position, item.get_estimated_cost_to_finish())

    def get_open_list(self):
        return self.open_list.queue

    def get_closed_list(self):
        return self.closed_list.queue

    def show_closed_list(self):
        for item in self.closed_list.queue:
            print(item.position)

    def get_finish_tile(self):
        return self.tiles[self.position_finish[0]][self.position_finish[1]]
 def setUp(self):
     self.pq = PriorityQueue()
     self.r1 = Rectangle(0, 150, 200, 50, media.forestgreen, 1)
     self.o1= Oval(120, 160, 60, 60, media.white, 4)
     self.o2 = Oval(120, 115, 45, 45, media.yellow, 3)
     self.o3 = Oval(120, 80, 30, 30, media.orange, 2)
示例#45
0
文件: prim.py 项目: lalitzz/DS
def prim(G):
  cost = {}
  parent = {}
  u = None
  P = PriorityQueue()
  for v in G.vertexes:
    if u is None:
      u = v
    cost[v] = float('inf')
    P.add(float('inf'), v)
    parent[v] = None

  cost[u] = 0
  P.change_priority(u, 0)
  for i in P.Q:
    print(i)
  while not P.isEmpty():
    print('wtf')
    v_ele = P.get_min()
    vertex = v_ele.data
    print('minimum', v_ele)
    for u, v, w in G.get_all_vertex(vertex):
      print(u, v, w)
      if P.check_ele(v) and cost[v] > cost[u] + w:
        cost[v] = cost[u] + w
        parent[v] = u
        P.change_priority(v, cost[v])
  print(cost)
  print(parent)
示例#46
0
def find(mapdata, width, height, start, end):
    """ mapdata is a one-dimensional list of values, start and end are vectors of size 2 """
    # WRITE THIS FUNCTION

    open = PriorityQueue()
    closed = []
    curTile = MapTile(start, None, None, None, None)
    print(width, height, start, end)

    while curTile.coords != end:
        if onMap(curTile.coords, width, height):
            n = north(curTile.coords)
            nter = terraintype(mapdata, width, height, n)
            ntile = MapTile(n, LAT_COST, mandistance(n, end), nter, curTile)
            if nter and (ntile not in closed):
                print(ntile)
                open.insert(ntile)

            s = south(curTile.coords)
            ster = terraintype(mapdata, width, height, s)
            stile = MapTile(s, LAT_COST, mandistance(s, end), ster, curTile)
            if ster and (stile not in closed):
                print(stile)
                open.insert(stile)

            e = east(curTile.coords)
            eter = terraintype(mapdata, width, height, e)
            etile = MapTile(e, LAT_COST, mandistance(e, end), eter, curTile)
            if eter and (etile not in closed):
                print(etile)
                open.insert(etile)

            w = west(curTile.coords)
            wter = terraintype(mapdata, width, height, w)
            wtile = MapTile(w, LAT_COST, mandistance(w, end), wter, curTile)
            if wter and (wtile not in closed):
                print(wtile)
                open.insert(wtile)

            nw = northwest(curTile.coords)
            nwter = terraintype(mapdata, width, height, nw)
            nwtile = MapTile(nw, DIAG_COST, mandistance(nw, end), nwter, curTile)
            if nwter and (nwtile not in closed):
                print(nwtile)
                open.insert(nwtile)

            ne = northeast(curTile.coords)
            neter = terraintype(mapdata, width, height, ne)
            netile =  MapTile(ne, DIAG_COST, mandistance(ne, end), neter, curTile)
            if neter and (netile not in closed):
                print(netile)
                open.insert(netile)

            sw = southwest(curTile.coords)
            swter = terraintype(mapdata, width, height, sw)
            swtile = MapTile(sw, DIAG_COST, mandistance(sw, end), swter, curTile)
            if swter and (swtile not in closed):
                print(swtile)
                open.insert(swtile)

            se = southeast(curTile.coords)
            seter = terraintype(mapdata, width, height, se)
            setile = MapTile(se, DIAG_COST, mandistance(se, end), seter, curTile)
            if seter and (setile not in closed):
                print(setile)
                open.insert(setile)

        closed.append(curTile)
        print(open)
        curTile = open.remove()

    path = []
    if curTile.coords == end:
        while curTile.parent is not None:
            path.append(curTile.parent)
            curTile = curTile.parent
        print(path)