Ejemplo n.º 1
0
def test_iterative_deepening_search_at_goal():
    # plan of length 0, start == goal
    task = dummy_task.get_search_space_at_goal()
    solution = iterative_deepening_search(task)
    print(solution)
    assert solution is not None
    assert len(solution) == 0
def main():
    problem = MissionariesAndCannibals()
    result = iterative_deepening_search(problem)
    list_arr = []
    for node in result.path():
        list_arr.append(node.state.value)
    return list_arr
Ejemplo n.º 3
0
def test_iterative_deepening_search_four_step():
    # plan of length 4
    task = dummy_task.get_simple_search_space_2()
    solution = iterative_deepening_search(task)
    print(solution)
    assert solution is not None
    assert len(solution) == 4
def test_iterative_deepening_search_no_solution():
    # plan with no solution
    task = dummy_task.get_search_space_no_solution()
    searcher = iterative_deepening_search(task, 10)
    solution = searcher.search(task)
    print(searcher.extract_solution(solution))
    assert solution is None
Ejemplo n.º 5
0
def huarong_pass_search(search_name):
    goal_actions = []

    hp = HuarongPass()

    if search_name == 'BFS':
        # print "Breadth first search...good choice. ", time.asctime()
        goal_actions = search.breadth_first_search(hp).solution()

    elif search_name == 'DFS':
        # print "Depth first search...really?", time.asctime()
        goal_actions = search.depth_first_graph_search(hp).solution()

    elif search_name == 'IDS':
        # print "Iterative deepening search...great choice!", time.asctime()
        goal_actions = search.iterative_deepening_search(hp).solution()

    elif search_name == 'BID':
        # print "Bidirectional search...not required...using BFS instead..."
        goal_actions = huarong_pass_search('BFS')

    elif search_name == 'DLS':
        # print "Depth limited search...", time.asctime()
        goal_actions = search.depth_limited_search(hp, DEPTH_LIMIT).solution()

    else:
        print "Invalid search_name given. Exiting..."

    return goal_actions
def test_iterative_deepening_search_three_step():
    # plan of length 3
    task = dummy_task.get_simple_search_space()
    searcher = iterative_deepening_search(task)
    solution = searcher.search(task)
    print(searcher.extract_solution(solution))
    assert solution is not None
    assert len(solution) == 3
Ejemplo n.º 7
0
 def run(self):
     from time import clock
     start_t = clock()
     results = \
         iterative_deepening_search(state, expanded_state, evaluate,
                                    search, max_depth)
     runtime = clock() - start_t
     self._results = (results, runtime)
Ejemplo n.º 8
0
def test_ids():
    global goal_state

    print "Testing IDS..."

    hp_0  = HuarongPass(initial_state)
    hp_24 = HuarongPass(step_24_state)
    hp_30 = HuarongPass(step_30_state)
    hp_41 = HuarongPass(step_41_state)
    hp_48 = HuarongPass(step_48_state)
    hp_59 = HuarongPass(step_59_state)
    hp_72 = HuarongPass(step_72_state)
    hp_81 = HuarongPass(step_81_state)

    # goal_state = step_24_state
    # acts_0_24 = search.iterative_deepening_search(hp_0).solution()

    # goal_state = step_30_state
    # acts_24_30 = search.iterative_deepening_search(hp_24).solution()

    # goal_state = step_41_state
    # acts_30_41 = search.iterative_deepening_search(hp_30).solution()

    # goal_state = step_48_state
    # acts_41_48 = search.iterative_deepening_search(hp_41).solution()                 

    # goal_state = step_59_state
    # acts_48_59 = search.iterative_deepening_search(hp_48).solution()  

    # goal_state = step_72_state
    # acts_59_72 = search.iterative_deepening_search(hp_59).solution()  

    goal_state = None
    acts_72_81 = search.iterative_deepening_search(hp_72).solution()


    # print len(acts_0_24), acts_0_24
    # print len(acts_24_30), acts_24_30
    # print len(acts_30_41), acts_30_41
    # print len(acts_41_48), acts_41_48
    # print len(acts_48_59), acts_48_59
    # print len(acts_59_72), acts_59_72
    # print len(acts_72_81), acts_72_81

    # acts = acts_0_24 + acts_24_30 + acts_30_41 + acts_41_48 + acts_48_59 + acts_59_72 + acts_72_81
    # print "Total steps: ", len(acts)

    # audit_state(hp_0.state_given(initial_state, acts))

    audit_state(hp_0.state_given(step_72_state, acts_72_81))

    print "IDS test complete."
Ejemplo n.º 9
0
def huarong_pass_search(desired_search_strategy):
    """The function returns a list of actions that when applied to the initial state lead to the goal
    state."""
    initTime = datetime.datetime.now()
    problem = HuarongPass()
    if desired_search_strategy == "BFS":
        s = search.breadth_first_tree_search(problem)
    elif desired_search_strategy == "DFS":
        s = search.depth_first_graph_search(problem)
    elif desired_search_strategy == "IDS":
        s = search.iterative_deepening_search(problem)
    else:
        print "Desired search strategy not found!"
    endTime = datetime.datetime.now()
    print "Time taken", endTime - initTime
    return s.solution()
Ejemplo n.º 10
0
def solve():
    """
    this function considers 10 random values for m and n and returns the solutions for all the values
    between (1 and max(m))
    """
    count = 0
    while count <= 10:
        m_choice = np.random.choice(list_m)
        n_choice = np.random.choice(list_n)

        # m should be be equal to n
        if m_choice != n_choice:
            if bltin_gcd(m_choice, n_choice) == 1:
                count = count + 1
                for i in range(1, m_choice + 1):
                    print(m_choice, n_choice, i)
                    puzzle = WaterJug(initial_state, m_choice, n_choice, i)
                    ans = iterative_deepening_search(puzzle)
                    print(ans.path())
 # comment out one copy, and modify the other to get things to run more quickly while you're debugging
 depths = (1, 2, 4, 8, 16)
 trials = 100
 path_lengths = {}
 state_counts = {}
 for depth in depths:
     print('Gathering data for depth ' + str(depth) + '...')
     path_lengths[depth] = {'BFS': [], 'IDS': [], 'A*-mis': [], 'A*-Man': []}
     state_counts[depth] = {'BFS': [], 'IDS': [], 'A*-mis': [], 'A*-Man': []}
     for trial in range(trials):
         puzzle = EightPuzzle(depth)
         p = search.InstrumentedProblem(puzzle)
         path_lengths[depth]['BFS'].append(len(search.breadth_first_search(p).path()))
         state_counts[depth]['BFS'].append(p.states)
         p = search.InstrumentedProblem(puzzle)
         path_lengths[depth]['IDS'].append(len(search.iterative_deepening_search(p).path()))
         state_counts[depth]['IDS'].append(p.states)
         p = search.InstrumentedProblem(puzzle)
         path_lengths[depth]['A*-mis'].append(len(search.astar_search(p, misplaced).path()))
         state_counts[depth]['A*-mis'].append(p.states)
         p = search.InstrumentedProblem(puzzle)
         path_lengths[depth]['A*-Man'].append(len(search.astar_search(p, manhattan).path()))
         state_counts[depth]['A*-Man'].append(p.states)
 print('Path lengths:')
 print('{:>5}  {:>8}  {:>8}  {:>8}  {:>8}'.format('Depth', 'BFS', 'IDS', 'A*-mis', 'A*-Man'))
 for depth in depths:
     print('{:>5}  {:>8}  {:>8}  {:>8}  {:>8}' \
           .format(depth,
                   mean(path_lengths[depth]['BFS']),
                   mean(path_lengths[depth]['IDS']),
                   mean(path_lengths[depth]['A*-mis']),
Ejemplo n.º 12
0
def solveIterativeDeepeningSearch():
    """Solves the puzzle using iterative_deepening_search"""
    return iterative_deepening_search(puzzle).solution()
Ejemplo n.º 13
0
    if action == Constants.up:
        return zero_place - row_length
    if action == Constants.down:
        return zero_place + row_length
    if action == Constants.right:
        return zero_place + 1
    return zero_place - 1


problem = EightPuzzle(Constants.begin, Constants.Goal)
goalnode = search.breadth_first_graph_search(problem)
# sammud (tegevused, käigud) algolekust lõppolekuni
print(goalnode.solution())
# olekud algolekust lõppolekuni
print("path", goalnode.path())
print("path_len", len(goalnode.path()))

problem = EightPuzzle(Constants.begin, Constants.Goal)
goalnode = search.iterative_deepening_search(problem)
# sammud (tegevused, käigud) algolekust lõppolekuni
print(goalnode.solution())
# olekud algolekust lõppolekuni
print("path", goalnode.path())
print("path_len", len(goalnode.path()))

search.compare_searchers([problem], ["name", "result"],
                         searchers=[
                             search.breadth_first_graph_search,
                             search.iterative_deepening_search
                         ])
Ejemplo n.º 14
0
def iterative_deepening_search(problem):
    return search.iterative_deepening_search(problem)
Ejemplo n.º 15
0
def solveIterativeDeepeningSearch(puzzle):
    """Solves the two jug problem using iterative_deepening_search"""
    return iterative_deepening_search(puzzle).solution()
Ejemplo n.º 16
0
Archivo: run.py Proyecto: GuzmanHrz/FSI
# Search methods

import search

ab = search.GPSProblem('A', 'B', search.romania)

af = search.GPSProblem('A', 'F', search.romania)

print("Anchura:")
print search.breadth_first_graph_search(ab).path()
print("Profundidad:")
print search.depth_first_graph_search(ab).path()
print search.iterative_deepening_search(ab).path()
print search.depth_limited_search(ab).path()
print search.depth_limited_search(ab).path()
print("Branch_and_Bound ab")
print search.branch_and_bound_search(ab).path()
print("Branch_and_Bound_with_Subestimation ab")
print search.branch_and_bound_with_subestimation_search(ab).path()

print("Branch_and_Bound af")
print search.branch_and_bound_search(af).path()
print("Branch_and_Bound_with_Subestimation af")
print search.branch_and_bound_with_subestimation_search(af).path()



# Result:
# [<Node B>, <Node P>, <Node R>, <Node S>, <Node A>] : 101 + 97 + 80 + 140 = 418
# [<Node B>, <Node F>, <Node S>, <Node A>] : 211 + 99 + 140 = 450
Ejemplo n.º 17
0
def test_iterative_deepening_search_no_solution():
    # plan with no solution
    task = dummy_task.get_search_space_no_solution()
    solution = iterative_deepening_search(task, 10)
    print(solution)
    assert solution is None
Ejemplo n.º 18
0
     }
     state_counts[depth] = {
         'BFS': [],
         'IDS': [],
         'A*-mis': [],
         'A*-Man': []
     }
     for trial in range(trials):
         puzzle = EightPuzzle(depth)
         p = search.InstrumentedProblem(puzzle)
         path_lengths[depth]['BFS'].append(
             len(search.breadth_first_search(p).path()))
         state_counts[depth]['BFS'].append(p.states)
         p = search.InstrumentedProblem(puzzle)
         path_lengths[depth]['IDS'].append(
             len(search.iterative_deepening_search(p).path()))
         state_counts[depth]['IDS'].append(p.states)
         p = search.InstrumentedProblem(puzzle)
         path_lengths[depth]['A*-mis'].append(
             len(search.astar_search(p, misplaced).path()))
         state_counts[depth]['A*-mis'].append(p.states)
         p = search.InstrumentedProblem(puzzle)
         path_lengths[depth]['A*-Man'].append(
             len(search.astar_search(p, manhattan).path()))
         state_counts[depth]['A*-Man'].append(p.states)
 print('Path lengths:')
 print('{:>5}  {:>8}  {:>8}  {:>8}  {:>8}'.format('Depth', 'BFS', 'IDS',
                                                  'A*-mis', 'A*-Man'))
 for depth in depths:
     print('{:>5}  {:>8}  {:>8}  {:>8}  {:>8}' \
           .format(depth,
Ejemplo n.º 19
0
import search
from graph import Graph

if __name__ == "__main__":
    # Setting graph we initiated to search class...
    graph = Graph()
    search.graph = graph

    search.depth_first_search()
    search.breath_first_search()
    search.iterative_deepening_search()
    search.uniform_cost_search()
    search.greedy_best_first_search()
    search.a_star_search()
Ejemplo n.º 20
0
def main():
    problem = MissionariesAndCannibals()
    result = iterative_deepening_search(problem)
    print_path(result.path())
Ejemplo n.º 21
0
        return state.board.is_goal_reached()

    def h(self, node: Node):
        """ Função heuristica utilizada para a procura A*. """
        # TODO
        robot, oX, oY = node.state.board.objective
        x, y = node.state.board.robots[robot]

        if oX == x or oY == y: return 1
        return 2


if __name__ == "__main__":
    # TODO:
    # Ler o ficheiro de input de sys.argv[1],
    # Usar uma técnica de procura para resolver a instância,
    # Retirar a solução a partir do nó resultante,
    # Imprimir para o standard output no formato indicado.
    board = parse_instance(sys.argv[1])
    #board = parse_instance("testing.txt")

    # Criar uma instância de RicochetRobots:
    problem = RicochetRobots(board)

    # Obter o nó solução usando a procura Iterative Deepening Search:
    solution_node = iterative_deepening_search(problem)

    print(len(solution_node.solution()))
    for i in solution_node.solution():
        print(i[0] + " " + i[1])