Beispiel #1
0
def a_star_search(problem, fringe):
    # If there is no node on fringe, make one
    if len(fringe.queue) <= 0:
        initial_node = Node(problem)
        fringe.insert(initial_node)

    # If nodes don't have path cost for A* Search, give them one
    for node in fringe.queue:
        if node.a_star_cost == None:
            node.a_star_cost = a_star_evaluator(node)

    # Form a temporary priority queue
    a_star_fringe = Queue()
    a_star_fringe.insert_all(fringe.queue)

    # Sort them according to lowest path cost
    bubble_sort(a_star_fringe, False)

    # Iterate over the sorted nodes, to check visually
    for nodes in a_star_fringe.queue:
        print('Node: ' + str(nodes.a_star_cost) + ' Depth: ' + str(nodes.depth) + ' Action: ' + str(nodes.action))

    # Now do the good stuff
    # Get the first node in A* fringe and then pop it on the main fringe
    greed_node = a_star_fringe.pop()
    node = fringe.pop_specific(greed_node)

    # If the node is the goal, return it as goal; otherwise expand it
    if goal_test(node.state) == True:
        return True, solution(node), node
    else:
        if node.state.connor.death == False:
            fringe.insert_all(expand(node))
        return False, fringe, node
def search(grid,init,goal,cost):
    # ----------------------------------------
    # insert code here
    # ----------------------------------------
    Nr=len(grid)
    Nc=len(grid[0])

    def childNode(grid, loc, delta, delta_name):
        child=[]
        for i in range(len(delta)):
            move=delta[i]
            newloc=[loc[0]+move[0], loc[1]+move[1]]
            if loc[0]+move[0]>=0 and loc[0]+move[0]<Nr \
            and loc[1]+move[1]>=0 and loc[1]+move[1]<Nc \
            and grid[newloc[0]][newloc[1]] ==0:
                child.append([newloc,delta_name[i]])
        return child

    visited=[]
    frontier=Queue()
    frontier.push([init,0])

    while not frontier.isEmpty():
        loc, rlen=frontier.pop()
        if not loc in visited:
            visited.append(loc)
            if loc==goal:
                return [rlen, loc[0], loc[1]]

            for nextloc, move_name in childNode(grid, loc, delta, delta_name):
                if not nextloc in visited:
                    frontier.push([nextloc, rlen+cost])
    return 'fail'
Beispiel #3
0
def best_fs(problem, fringe):
    # If there is no node on fringe, make one
    if len(fringe.queue) <= 0:
        initial_node = Node(problem)
        fringe.insert(initial_node)

    # If nodes don't have path cost for Greedy BFS, give them one
    for node in fringe.queue:
        if node.greed_cost == None:
            node.greed_cost = best_fs_evaluator(node)

    # Form a temporary priority queue
    best_fs_fringe = Queue()
    best_fs_fringe.insert_all(fringe.queue)

    # Sort them according to lowest path cost
    bubble_sort(best_fs_fringe)

    # Now do the good stuff
    # Get the first node in Greedy BFS fringe and then pop it on the main fringe
    greed_node = best_fs_fringe.pop()
    node = fringe.pop_specific(greed_node)

    # If the node is the goal, return it as goal; otherwise expand it
    if goal_test(node.state) == True:
        return True, solution(node), node
    else:
        if node.state.connor.death == False:
            fringe.insert_all(expand(node))
        return False, fringe, node
Beispiel #4
0
 def test_pop_2(self):
     q = Queue()
     q.put(2)
     q.put(1)
     self.assertEqual(q.pop(), 2)
     self.assertEqual(q.pop(), 1)
     self.assertTrue(q.empty())
Beispiel #5
0
class EventsHub:
    """Implements an event aggregator to gather events from both interfaces as well as the application itself.
    Similar to an Observer pattern.

    Warning:
        Events need to be processed regularly by calling `.handle_events()`
        to avoid overflowing the event queue.

    Events types:
     - pygame events (mouse / key press / quit)
     - tkinter events (mouse / key press / quit)
        - all buttons
     - application events, like "AnimationFinished" event
    """
    def __init__(self):
        self._events = Queue()
        self._callbacks = {}

    def raise_event(self, event):
        self._events.put(event)

    def add_callback(self, event_name, callback):
        self._callbacks.setdefault(event_name, []).append(callback)

    def handle_events(self):
        while not self._events.empty():
            event = self._events.pop()
            if event.type in [Event.QUIT, Event.NEWFRAME]:
                # print("Handling", event, self._callbacks.get(event.type, []))
                pass
            for callback in self._callbacks.get(event.type, []):
                callback(event)
def search(grid, init, goal, cost):
    # ----------------------------------------
    # insert code here
    # ----------------------------------------
    Nr = len(grid)
    Nc = len(grid[0])
    expand = [[-1 for j in range(Nc)] for i in range(Nr)]
    policy = [[' ' for j in range(Nc)] for i in range(Nr)]
    path = [[' ' for j in range(Nc)] for i in range(Nr)]
    count = 0

    def childNode(grid, loc, delta, delta_name):
        child = []
        for i in range(len(delta)):
            move = delta[i]
            newloc = [loc[0] + move[0], loc[1] + move[1]]
            if loc[0]+move[0]>=0 and loc[0]+move[0]<Nr \
            and loc[1]+move[1]>=0 and loc[1]+move[1]<Nc \
            and grid[newloc[0]][newloc[1]] ==0:
                child.append([newloc, delta_name[i]])
        return child

    visited = []
    frontier = Queue()
    frontier.push([init, ' ', 0])

    while not frontier.isEmpty():
        loc, mov, rlen = frontier.pop()
        if not loc in visited:
            visited.append(loc)
            policy[loc[0]][loc[1]] = mov

            if loc == goal:
                path[goal[0]][goal[1]] = '*'
                while loc != init:
                    x, y = loc
                    if policy[x][y] == 'v':
                        loc = [x - 1, y]
                        path[loc[0]][loc[1]] = 'v'
                    elif policy[x][y] == '^':
                        loc = [x + 1, y]
                        path[loc[0]][loc[1]] = '^'
                    elif policy[x][y] == '>':
                        loc = [x, y - 1]
                        path[loc[0]][loc[1]] = '>'
                    elif policy[x][y] == '<':
                        loc = [x, y + 1]
                        path[loc[0]][loc[1]] = '<'

                return path

            for nextloc, move_name in childNode(grid, loc, delta, delta_name):
                if not nextloc in visited:
                    frontier.push([nextloc, move_name, rlen + cost])
    return 'fail'
Beispiel #7
0
 def print_weights(self):
     q = Queue()
     layer = 0
     for neuron in self.input_layer:
         q.put((neuron, layer + 1))
     while not q.empty():
         neuron, cur_layer = q.pop()
         if cur_layer > layer and cur_layer < self.nlayers:
             print "\nlayer %d:" % cur_layer,
             layer = cur_layer
             for connection in neuron.outputs:
                 q.put((connection.tar, layer + 1))
         for connection in neuron.outputs:
             print connection.w,
     print  # print new line
def search(grid, init, goal, cost):
    # ----------------------------------------
    # modify code below
    # ----------------------------------------
    Nr = len(grid)
    Nc = len(grid[0])
    expand = [[-1 for j in range(Nc)] for i in range(Nr)]
    count = 0

    def childNode(grid, loc, delta, delta_name):
        child = []
        for i in range(len(delta)):
            move = delta[i]
            newloc = [loc[0] + move[0], loc[1] + move[1]]
            if loc[0]+move[0]>=0 and loc[0]+move[0]<Nr \
            and loc[1]+move[1]>=0 and loc[1]+move[1]<Nc \
            and grid[newloc[0]][newloc[1]] ==0:
                child.append([newloc, delta_name[i]])
        return child

    visited = []
    frontier = Queue()
    frontier.push([init, 0])

    while not frontier.isEmpty():
        loc, rlen = frontier.pop()
        if not loc in visited:
            visited.append(loc)
            expand[loc[0]][loc[1]] = count
            count += 1

            if loc == goal:
                return expand

            for nextloc, move_name in childNode(grid, loc, delta, delta_name):
                if not nextloc in visited:
                    frontier.push([nextloc, rlen + cost])
    return 'fail'
def general_search(problem):
    """Problem: {doamin, method, graph, coords, start, goal}
    method: B, D, I, U, A

    route: graph search (maintain a closed set) except Astar
    tsp: tree search
    """
    method = problem['method']

    if method not in ['B', 'D', 'I', 'U', 'A']:
        print("Enter Correct method!")
        return None
    if problem['start'] not in problem['graph'].get_nodes() or (
            problem['domain'] == 'route' and problem['goal'] not in problem['graph'].get_nodes()):
        print("Enter Correct Start/Goal!")
        return None

    # BFS, DFS
    if method in ['B', 'D']:
        if method == 'B':
            frontier = Queue()
        else:
            frontier = Stack()
        start_node = Node(problem['start'])
        frontier.push(start_node)
        closed_set = set()
        while not frontier.isEmpty():
            node = frontier.pop()
            closed_set.add(node.value)
            if goal_test(problem, node):
                path = node.get_path()
                cost = cal_path_cost(problem['graph'], path)
                return path, cost, frontier.count

            # Expansion
            closed_set.add(node.value)
            adj = problem['graph'].adj(node.value)
            for child_value in quicksort(adj):
                if push_or_not(problem, node, child_value, closed_set):
                    child_node = Node(child_value, node)
                    frontier.push(child_node)
        return None

    """Uniform Cost Search / Astar Search"""
    if method in ['U', 'A']:
        frontier = PriorityQueue()
        start_node = Node(problem['start'])
        priority = 0 if method == 'U' else astar_heuristic(problem, start_node)
        frontier.push(priority, start_node)

        closed_set = set()

        while not frontier.isEmpty():
            node = frontier.pop()
            closed_set.add(node.value)
            if goal_test(problem, node):
                path = node.get_path()
                cost = cal_path_cost(problem['graph'], path)
                return path, cost, frontier.count
            # Expansion
            adj = problem['graph'].adj(node.value)
            for child_value in quicksort(adj):
                if push_or_not(problem, node, child_value, closed_set):
                    child_cost = node.cost_so_far + \
                        problem['graph'].get_cost(node.value, child_value)  # g_n
                    child_node = Node(child_value, node, child_cost)
                    priority = child_cost if method == 'U' else child_cost + \
                        astar_heuristic(problem, child_node)
                    frontier.push(priority, child_node)
        return None

    """Iterative Deepening Search"""
    if method == 'I':
        def depth_limited(problem, limit):
            """Depth Limited Search"""
            frontier = Stack()
            start_node = Node(problem['start'])
            frontier.push(start_node)
            closed_set = set()
            while not frontier.isEmpty():
                node = frontier.pop()
                closed_set.add(node.value)
                if goal_test(problem, node):
                    path = node.get_path()
                    cost = cal_path_cost(problem['graph'], path)
                    return path, cost, frontier.count
                if node.depth == limit:
                    pass
                else:
                    # Expansion
                    adj = problem['graph'].adj(node.value)
                    for child_value in quicksort(adj):
                        if push_or_not(problem, node, child_value, closed_set):
                            child_node = Node(child_value, node)
                            frontier.push(child_node)
            return None
        max_depth = 20
        for i in range(max_depth):
            result = depth_limited(problem, i)
            if result:
                return result
Beispiel #10
0
 def test_pop_exception(self):
     with self.assertRaises(AssertionError):
         q = Queue()
         q.put(1)
         q.pop()
         q.pop()