Exemplo n.º 1
0
def resolver(metodo_busqueda, posiciones_personas):
    """ Devuelve un nodo resultado, a partir de una búqueda especificada.

    Argumentos:
    metodo_busqueda -- nombre de método a usar (string);
    posiciones_personas -- lista de tuplas. Cada tupla representa la posicion 
    de una persona en la grilla (aún por rescatar).

    """
    """
    Estado inicial: Lista compuesta de 4 posiciones:
    1era posicion: Tupla. Posicion del robot en la grilla.
    2da posicion: Lista de tuplas. Posiciones de la grilla que el robot va 
    hundiendo (inutilizando).
    3era posicion: Lista de tuplas. Posiciones de la grilla donde se ubican 
    las personas aún no rescatadas.
    4ta posicion: Booleano. Es True si el robot esta 'ocupado' (esta cargando 
    personas), caso contrario False.
    """
    ESTADO_INICIAL = ((0, 0), (), posiciones_personas, False)
    problema = RescatePersonas(ESTADO_INICIAL)

    if metodo_busqueda == 'astar':
        return astar(problema, graph_search=True)
    elif metodo_busqueda == 'depth_first':
        return depth_first(problema, graph_search=True)
    elif metodo_busqueda == 'breadth_first':
        return breadth_first(problema, graph_search=True)
    elif metodo_busqueda == 'greedy':
        return greedy(problema, graph_search=True)
Exemplo n.º 2
0
def doDepthFirst(NEWMAP, problem, myviewer):
    result = depth_first(problem, graph_search=True, viewer=myviewer)
    path = [x[1] for x in result.path()]
    # print(result.state)
    # print(result.path())
    print("Ruta realizada Profundidad:")
    print(result.path())
    print(printMap(NEWMAP, problem, path))
Exemplo n.º 3
0
def DFS(SearchingProblem):
    print("---Depth First Search---")    
    before = datetime.now()
    search = depth_first(SearchingProblem,graph_search=(True))
    #search = depth_first(SearchingProblem,graph_search=(True),viewer=my_viewer)
    after = datetime.now()
    print("Path -->",search.path())
    print("Time -->", (after - before).total_seconds())
    print("Path cost-->",search.cost)
    print("-" * 40)
Exemplo n.º 4
0
def main():
    start_board = Board.board_from_file(sys.argv[1])
    duplication_checks = sys.argv[2]
    method = sys.argv[3]
    heuristic = ''
    check_duplicates = 'graph' in duplication_checks

    if 'star' in method:
        heuristic = sys.argv[4]

        if heuristic == 'max_moves':
            start_board.heuristic = heuristics.max_moves
        elif heuristic == 'min_moves':
            start_board.heuristic = heuristics.min_moves
        elif heuristic == 'max_movable_pegs':
            start_board.heuristic = heuristics.max_movable_pegs
        elif heuristic == 'man':
            start_board.heuristic = heuristics.manhattan_distance
        else:
            print('You did not pick a viable heuristic. Exiting...')
            return

    start = time.time()
    if method == 'dfs':
        result = depth_first(start_board, check_duplicates)
    elif method == 'bfs':
        result = breadth_first(start_board, check_duplicates)

    elif method == 'astar':
        result = astar(start_board, check_duplicates)

    elif method == 'ildf':
        result = iterative_limited_depth_first(start_board, check_duplicates)

    else:
        print('You must choose a valid search method. Exiting...')
        return

    end = time.time()

    print("-" * 30)
    print('Search:', sys.argv[2], 'on', sys.argv[3], sys.argv[4] if len(sys.argv) > 4 else '')
    print('Input File:', sys.argv[1])
    if result:
        path = result.path()
        for step in path:
            print(step[0], '-->', Board.board_from_state(step[1]))
        print('Duration: {0:.4f} seconds'.format(end - start))
        print('Nodes Visited:', len(path))

    else:
        print("No solution found!")


    print("-" * 30)
def resolver(metodo_busqueda, posicion_rey, controlar_estados_repetidos):
    problema = HnefataflProblem(posicion_rey)
    visor = BaseViewer()
    if metodo_busqueda == "breadth_first":
        resultado = breadth_first(problema, graph_search=controlar_estados_repetidos)
        return resultado
    if metodo_busqueda == "depth_first":
        return depth_first(problema, graph_search=controlar_estados_repetidos)
    if metodo_busqueda == "greedy":
        return greedy(problema, graph_search=controlar_estados_repetidos)
    if metodo_busqueda == "astar":
        return astar(problema, graph_search=controlar_estados_repetidos)
Exemplo n.º 6
0
def resolver(metodo_busqueda, posiciones_aparatos):
	Inicial = [(3,3)]
	for ap in posiciones_aparatos:
		Inicial.append((ap[0], ap[1], 300))
	if metodo_busqueda == "breadth_first":
		return breadth_first(Problem(tuple(Inicial)), graph_search=True)
	if metodo_busqueda == "astar":
		return astar(Problem(tuple(Inicial)), graph_search=True)
	if metodo_busqueda == "greedy":
		return greedy(Problem(tuple(Inicial)), graph_search=True)
	if metodo_busqueda == "depth_first":
		return depth_first(Problem(tuple(Inicial)), graph_search=True)
def createProblem(listaSnake):
    problem = SnakeGame((listaSnake[0].rect.x, listaSnake[0].rect.y), (food.rect.x, food.rect.y))
    result = depth_first(problem, graph_search=True)
    path = [x[1] for x in result.path()]
    moves = result.path()
    moves = moves[1:]
    lm = []

    for i in moves:
        lm.append(i[0])

    lm.reverse()
    return lm
def resolver(metodo_busqueda):
    visor = BaseViewer()
    if metodo_busqueda == 'breadth_first':
        result = breadth_first(entrega1tradicional(INITIAL), graph_search=True, viewer=visor)
    if metodo_busqueda == 'depth_first':
        result = depth_first(entrega1tradicional(INITIAL), graph_search=True, viewer=visor)
    if metodo_busqueda == 'limited_depth_first':
        result = iterative_limited_depth_first(entrega1tradicional(INITIAL),10, viewer=visor)
    if metodo_busqueda == 'greedy':
        result = greedy(entrega1tradicional(INITIAL), graph_search=True, viewer=visor)
    if metodo_busqueda == 'astar':
        result = astar(entrega1tradicional(INITIAL), graph_search=True, viewer=visor)

    return result
Exemplo n.º 9
0
def resolver(metodo_busqueda, posicion_rey, controlar_estados_repetidos):

    INITIAL = posicion_rey
    problema = HnefataflProblema(posicion_rey)
    visor = BaseViewer()

    #Busqueda en amplitud
    if (metodo_busqueda == 'breadth_first'):
        resultado = breadth_first(problema,
                                  graph_search=controlar_estados_repetidos,
                                  viewer=visor)
        return resultado

    #Busqueda en profundidad
    if (metodo_busqueda == 'depth_first'):
        resultado = depth_first(problema,
                                graph_search=controlar_estados_repetidos,
                                viewer=visor)
        return resultado

    #Busqueda avara
    if (metodo_busqueda == 'greedy'):
        resultado = greedy(problema,
                           graph_search=controlar_estados_repetidos,
                           viewer=visor)
        return resultado

    #Busqueda A Estrella
    if (metodo_busqueda == 'astar'):
        resultado = astar(problema,
                          graph_search=controlar_estados_repetidos,
                          viewer=visor)
        return resultado


#   for action, state in resultado.path():
#        print action

#    print resultado.path()
#   print 'produndidad: ' + str(resultado.depth)

#    print state
#    print 'El costo es: ' + str(resultado.cost)
#    print visor.stats

#if __name__ == '__main__':
#    resolver('breadth_first', (5,3),True)
Exemplo n.º 10
0
def resolver(metodo_busqueda, posiciones_personas):
    inicial = GenerarEstado(posiciones_personas)
    problema = RescateHieloProblem(inicial)

    if metodo_busqueda == "breadth_first":
        return breadth_first(problema,
                             graph_search=True,
                             viewer=ConsoleViewer())

    if metodo_busqueda == "greedy":
        return greedy(problema, graph_search=True, viewer=ConsoleViewer())

    if metodo_busqueda == "depth_first":
        return depth_first(problema, graph_search=True, viewer=ConsoleViewer())

    if metodo_busqueda == "astar":
        return astar(problema, graph_search=True, viewer=ConsoleViewer())
Exemplo n.º 11
0
def main():
    problem = GameWalkPuzzle(MAP)
    #result = astar(problem, graph_search=True)
    result = depth_first(problem, graph_search=True)
    path = [x[1] for x in result.path()]

    for y in range(len(MAP)):
        for x in range(len(MAP[y])):
            if (x, y) == problem.initial:
                print("o", end='')
            elif (x, y) == problem.goal:
                print("x", end='')
            elif (x, y) in path:
                print("·", end='')
            else:
                print(MAP[y][x], end='')
        print()
Exemplo n.º 12
0
def resolver(metodo_busqueda, posiciones_personas):
    state = ((0, 0), (posiciones_personas), ())

    my_viewer = BaseViewer()
    if 'astar':
        result = astar(TpProblem(state), graph_search=True, viewer=my_viewer)
    elif 'breadth_first':
        result = breadth_first(TpProblem(state),
                               graph_search=True,
                               viewer=my_viewer)
    elif 'depth_first':
        result = depth_first(TpProblem(state),
                             graph_search=True,
                             viewer=my_viewer)
    elif 'greedy':
        result = greedy(TpProblem(state), graph_search=True, viewer=my_viewer)

    return result
Exemplo n.º 13
0
def resolver(metodo_busqueda, franceses, piratas):
    viewer = None
    letra = 0
    franceses = list(franceses)
    piratas = list(piratas)
    for barcos in piratas:
        if letra == 0:
            piratas[0] = list(piratas[0])
            piratas[0].insert(0, 'A')
            piratas[0].append(0)
            piratas[0].append(0)
            piratas[0] = tuple(piratas[0])

        if letra == 1:
            piratas[1] = list(piratas[1])
            piratas[1].insert(0, 'B')
            piratas[1].append(0)
            piratas[1].append(0)
            piratas[1] = tuple(piratas[1])

        if letra == 2:
            piratas[2] = list(piratas[2])
            piratas[2].insert(0, 'C')
            piratas[2].append(0)
            piratas[2].append(0)
            piratas[2] = tuple(piratas[2])
        letra = letra + 1
    
    estado = ((tuple(piratas), tuple(franceses)))
    
    problem = Barcos_Piratas(estado)

    if metodo_busqueda == "breadth_first":    
        resultado = breadth_first(problem, graph_search=True, viewer = viewer)
    elif metodo_busqueda == "greedy":    
        resultado = greedy(problem, graph_search=True, viewer = viewer)
    elif metodo_busqueda == "depth_first":    
        resultado = depth_first(problem, graph_search=True, viewer = viewer)
    elif metodo_busqueda == "astar":
        resultado = astar(problem, graph_search=True, viewer = viewer)
    elif metodo_busqueda == "uniform_cost":
        resultado = uniform_cost(problem, graph_search=True, viewer = viewer)

    return resultado
Exemplo n.º 14
0
def createProblem(listaSnake, food, method, direction):
    problem = SnakeGame((listaSnake[0].rect.x, listaSnake[0].rect.y), (food.rect.x, food.rect.y), listaSnake, direction)
    if method == "astar":
        result = astar(problem, graph_search=True)
    elif method == "dfs":
        result = depth_first(problem, graph_search=True)
    else:
        result = breadth_first(problem, graph_search=True)

    if result == None:
        return False
    moves = result.path()
    moves = moves[1:]
    lm = []

    for i in moves:
        lm.append(i[0])

    lm.reverse()
    return lm
def resolver(metodo_busqueda, posicion_rey, controlar_estados_repetidos):
    problema = HnefataflProblema(posicion_rey)
    visor = BaseViewer()
    #Busquedas, Grafo -> graph_search=True
    if (metodo_busqueda == 'breadth_first'):  # En amplitud
        resultado = breadth_first(problema,
                                  graph_search=controlar_estados_repetidos,
                                  viewer=visor)
    elif (metodo_busqueda == 'depth_first'):  # Profundidad
        resultado = depth_first(problema,
                                graph_search=controlar_estados_repetidos,
                                viewer=visor)
    elif (metodo_busqueda == 'greedy'):  # Avara
        resultado = greedy(problema,
                           graph_search=controlar_estados_repetidos,
                           viewer=visor)
    elif (metodo_busqueda == 'astar'):  # Estrella
        resultado = astar(problema,
                          graph_search=controlar_estados_repetidos,
                          viewer=visor)
    print(visor.stats)
    return resultado
def resolver(metodo_busqueda, posiciones_aparatos):
    estado = [
        (3, 3, 0),
    ]
    nuevo_estado = ((), )
    lista_aparatos = []

    posiciones_aparatos = list(posiciones_aparatos)
    for artefacto in posiciones_aparatos:
        lista_artefacto = list(artefacto)
        lista_aparatos.append(lista_artefacto)

    posiciones_aparatos = tuple(posiciones_aparatos)

    for aparato in lista_aparatos:
        aparato.append(300)

    for aparato in lista_aparatos:
        tupla_aparato = tuple(aparato)
        estado.append(tupla_aparato)

    nuevo_estado = tuple(estado)
    problema = BomerobotProblem(nuevo_estado)

    if metodo_busqueda == 'breadth_first':
        resultado = breadth_first(problema, graph_search=True)
        return resultado
    if metodo_busqueda == 'depth_first':
        resultado = depth_first(problema, graph_search=True)
        return resultado
    if metodo_busqueda == 'greedy':
        resultado = greedy(problema, graph_search=True)
        return resultado
    if metodo_busqueda == 'astar':
        resultado = astar(problema, graph_search=True)
        return resultado
Exemplo n.º 17
0
 def test_depth_first(self):
     result = depth_first(self.problem)
     self.assertEquals(result.state, GOAL)
Exemplo n.º 18
0
        return (action,
                tuple([food_pos for food_pos in foods if food_pos != action]))

    def heuristic(self, state):
        rat_pos, foods = state
        distances = [manhattan(rat_pos, EXIT)]
        for food_pos in foods:
            distances.append(
                manhattan(rat_pos, food_pos) + manhattan(food_pos, EXIT))

        return max(distances)


print('Searching for a solution...')
# result = astar(RatsProblem(INITIAL), graph_search=True,
# viewer=WebViewer())
viewer = BaseViewer()
# result = astar(RatsProblem(INITIAL), graph_search=True, viewer=viewer)
result = depth_first(RatsProblem(INITIAL), graph_search=True, viewer=viewer)

print('Solution found!')
print('State:', result.state)
print('Solution cost:', result.cost)
print('Stats:', viewer.stats)
print('Path from initial:')

for action, resulting_state in result.path():
    print('action:', action)
    print('state:', resulting_state)
    print('-' * 40)
Exemplo n.º 19
0
    def is_goal(self, state):
        """ 
            This method evaluates whether the specified state is the goal state.

            state : The game state to test.
        """
        return state == self.goal


#------------------------------------------------------------------------------------------------------------------
#   Program
#------------------------------------------------------------------------------------------------------------------

# Create solver object\
print("Depth First search")
result = depth_first(MissionariesAndCannibals(), graph_search=True)

# Print results
for i, (action, state) in enumerate(result.path()):
    print()
    if action == None:
        print('Initial configuration')
    elif i == len(result.path()) - 1:
        print('Movement: ' + str(i) + ' After moving', action,
              'Goal achieved!')
    else:
        print('Movement: ' + str(i) + ' After moving', action)

    print(state)

print("------------------------------------------------------")
Exemplo n.º 20
0
        elif state == [[0, 0], [3, 3, "B"]]:
            return ["C2", "C1", "C1M1"]
        elif state == [[1, 0, "B"], [2, 3]]:
            return ["C1"]
        else:
            return []

    def result(self, state, action):
        '''Transition model'''
        state = from_string_to_list_2(state)
        if "B" in state[0]:
            state[1] = state[1] + (list(state[0].pop()))
            return from_list_to_string(actions_helper(state, action))
        if "B" in state[1]:
            state[0] = state[0] + (list(state[1].pop()))
            return from_list_to_string(actions_helper(state, action, x=1, y=0))

    def is_goal(self, state):
        ''' Checks if particular state is a goal state'''
        return state == GOAL


problem = MissionriesCannibals(initial_state)
result = depth_first(problem, graph_search=True)
print(result.path())
print(result.state)

#for act, state in result.path():
#    print("Action taken {}".format(act))
#    print("resulting state {}".format(state))
Exemplo n.º 21
0
# Starting point
INITIAL = '''1-e-2
6-3-4
7-5-8'''

# Create a cache for the goal position of each piece
goal_positions = {}
rows_goal = string_to_list(GOAL)
for number in '12345678e':
    goal_positions[number] = get_location(rows_goal, number)

# Create the solver object
#result = astar(PuzzleSolver(INITIAL), graph_search=True)
#result = breadth_first(PuzzleSolver(INITIAL), graph_search=True)
#result = iterative_limited_depth_first(PuzzleSolver(INITIAL), graph_search=True)
result = depth_first(PuzzleSolver(INITIAL), graph_search=True)
#result = idastar(PuzzleSolver(INITIAL), graph_search=True)

# Print the results
for i, (action, state) in enumerate(result.path()):
    print()
    if action == None:
        print('Initial configuration')
    elif i == len(result.path()) - 1:
        print('After moving', action, 'into the empty space. Goal achieved!')
    else:
        print('After moving', action, 'into the empty space')

    print(state)
Exemplo n.º 22
0
        '''Returns true if a state is the goal state.'''
        return state == GOAL

    def cost(self, state1, action, state2):
        '''Returns the cost of performing an action. No useful on this problem, i
           but needed.
        '''
        return 1

    def heuristic(self, state):
        '''Returns an *estimation* of the distance from a state to the goal.
           We are using the manhattan distance.
        '''
        rows = string_to_list(state)

        distance = 0

        row_c, col_c = find_location(rows, 'c')
        row_c_goal, col_c_goal = goal_positions['c']

        distance += abs(row_c - row_c_goal) + abs(col_c - col_c_goal)
        
        return distance


result = depth_first(SnakeProblem(INITIAL),graph_search=True)

for action, state in result.path():
    print('Move ', action)
print(state)
Exemplo n.º 23
0
				distancia = n*2 - state[ap][0] - state[ap][1] + abs(state[ap][0]-rx) + abs(state[ap][1]-ry)
				for otroAp in range(1,len(state)):
					if otroAp != ap:
						distancia += (n*2 - state[otroAp][0] - state[otroAp][1])*2
				if menor == 0 or menor > distancia:
					menor = distancia
		return menor

def resolver(metodo_busqueda, posiciones_aparatos):
	Inicial = [(3,3)]
	for ap in posiciones_aparatos:
		Inicial.append((ap[0], ap[1], 300))
	if metodo_busqueda == "breadth_first":
		return breadth_first(Problem(tuple(Inicial)), graph_search=True)
	if metodo_busqueda == "astar":
		return astar(Problem(tuple(Inicial)), graph_search=True)
	if metodo_busqueda == "greedy":
		return greedy(Problem(tuple(Inicial)), graph_search=True)
	if metodo_busqueda == "depth_first":
		return depth_first(Problem(tuple(Inicial)), graph_search=True)
        
if __name__ == '__main__':
	Inicial = ((3,3),(1,2,300),(2,0,300),(3,0,300))
	print('Prueba depth_first')	
	visor = BaseViewer()
	resultado = depth_first(Problem(Inicial), graph_search = True, viewer = visor)
	#print(resultado.path())
	print(resultado.state)
	print(resultado.cost)
	print(visor.stats)