Ejemplo n.º 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)
Ejemplo n.º 2
0
Archivo: qsim.py Proyecto: 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
Ejemplo n.º 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
Ejemplo n.º 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
Ejemplo n.º 5
0
    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
Ejemplo n.º 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
 def setUp(self):
     self.pq = PriorityQueue(":memory:")
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())
Ejemplo n.º 9
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:
Ejemplo n.º 10
0
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'
Ejemplo n.º 11
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
Ejemplo n.º 12
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()
Ejemplo n.º 13
0
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
Ejemplo n.º 14
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()))
Ejemplo n.º 15
0
 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)
Ejemplo n.º 16
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
Ejemplo n.º 17
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)