Esempio n. 1
0
def resolver(metodo_busqueda, posiciones_aparatos):
    viewer = BaseViewer()

    initial = []

    robot = [3, 3, 1]

    namespace = __import__(__name__)

    initial.append(robot)

    for a in posiciones_aparatos:
        aparato = [a[0], a[1], 300]
        initial.append(aparato)

    initial = list2tuple(initial)

    result = getattr(namespace, metodo_busqueda)(Bomberobot(initial),
                                                 viewer=viewer,
                                                 graph_search=True)

    print('Result state: ')
    print(result.state)
    print('Result path: ')
    for action, state in result.path():
        print('Action: ', action)
        print('State: ', state)
        print('')

    print(viewer.stats)

    return result
Esempio n. 2
0
def try_search_method(search_method, problem_class, initial_state):
    print()
    print('=' * 50)

    print("corriendo:", search_method.__name__)
    visor = BaseViewer()
    problem = problem_class(initial_state)
    result = search_method(problem, graph_search=True, viewer=visor)

    print('estado final:')
    if result is None:
        print("RESULTADO NO ENCONTRADO")
        return
    else:
        print(result.state)

    print('-' * 50)

    print('estadísticas:')
    print('cantidad de acciones hasta la meta:', len(result.path()))
    print(visor.stats)

    draw_path = input("Do you want to draw the path? [y/N]: ")
    if draw_path.lower() == "y":
        for _, state in result.path():
            problem.print_state_representation(state)
            continue_printing = input("Print the next state [Y/n]: ")

            if continue_printing.lower() == "n":
                break
Esempio n. 3
0
def resolver(metodo_busqueda, posiciones_personas, mostrar_stats=False):
    problema = ProblemaRobot(posiciones_personas)
    if mostrar_stats:
        viewer = BaseViewer()
    else:
        viewer = None

    funciones = {
        'breadth_first': breadth_first,
        'depth_first': depth_first,
        'greedy': greedy,
        'astar': astar
    }
    funcion_busqueda = funciones[metodo_busqueda]

    resultado = funcion_busqueda(problema, graph_search=True, viewer=viewer)

    if mostrar_stats:
        print(
            "Metodo: {}, Costo: {}, Tamanio maximo frontera: {}, Nodos visitados: {}"
            .format(metodo_busqueda, resultado.cost,
                    viewer.stats['max_fringe_size'],
                    viewer.stats['visited_nodes']))

    return resultado
Esempio n. 4
0
def searchSolution(map, configuration, state, aiBaseName, tracep):
    ''' Creates a gameProblem object, and calls its initialization
        Passes the description of the map both in matrix and in dictionary form
        Then executes the search algorithm defined upon initialization
        Transforms the solution in a plan in the format required by the game
    '''

    result = False

    if tracep:
        debugCall(map, configuration, state)

    mapAsPositions = transformMap(map, configuration)

    problem = GameProblem()
    problem.initializeProblem(map=map,
                              positions=mapAsPositions,
                              conf=configuration,
                              aiBaseName=aiBaseName)
    algorithm = problem.ALGORITHM
    useViewer = BaseViewer()

    print("----------------------- PROBLEM INFORMATION ------------------")
    print("-- Initial State  --")
    print(problem.initial_state)

    print("-- Final State  --")
    print(problem.GOAL)

    print("-- Search Algorithm --")
    print(problem.ALGORITHM)

    print("-------------   EXECUTING SEARCH   -------------------")
    result = algorithm(problem, graph_search=True, viewer=useViewer)

    if result:
        print("-------------   SEARCH RESULTS   -------------------")
        print("Reached final state: {0}".format(result.state))

        print(searchInfo(problem, result, useViewer))

        print("Solution as path (length:{0}): {1}".format(
            len(result.path()), result.path()))

        detailed_path = result.path()[1:]

        plan = list((a[0], {
            'showText':
            'Executing {0} -> State {1}'.format(a[0], problem.printState(
                a[1])),
            'onState':
            problem.getStateData(a[1])
        }) for a in detailed_path)

        return plan, problem, result, useViewer
    else:
        print("WARNING: A solution was not found for the final state: {0}".
              format(problem.GOAL))
        return None, None, None, None
Esempio n. 5
0
def resolver(metodo_busqueda, posiciones_personas):

    state = (posicionRobot, hielosRotos, posiciones_personas)

    if metodo_busqueda == 'astar':
        visor=BaseViewer()
        result = astar(RescateSobreHielo(state),graph_search=True, viewer=visor)
    elif metodo_busqueda =='breadth_first':
        visor=BaseViewer()
        result = breadth_first(RescateSobreHielo(state),graph_search=True, viewer=visor)
    elif metodo_busqueda =='depth_first':
        visor=BaseViewer()
        result = depth_first(RescateSobreHielo(state),graph_search=True,viewer=visor)
    elif metodo_busqueda =='greedy':
        visor=BaseViewer()
        result = greedy(RescateSobreHielo(state),graph_search=True,viewer=visor)
    return result
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)
Esempio n. 7
0
def planear_camiones(metodo, camiones=TRUCKS_EXAMPLE, paquetes=PACKAGES_EXAMPLE, debug=False):
    # a state is defined by a tuple of two elements:
    # - trucks with info wich is a tuple of (id, city, oil_liters)
    # - packages info wich is a tuple of (id, city)
    initial_state = (tuple(camiones), tuple(x[:-1] for x in paquetes))
    packages_goal = tuple((x[0], x[2]) for x in paquetes)
    trucks_liters = {x[0]: x[-1] for x in camiones}

    problem = MercadoArtificalProblem(trucks_liters, packages_goal, initial_state)

    search_methods = {
        "astar": astar,
        "breadth_first": breadth_first,
        "depth_first": depth_first,
        "uniform_cost": uniform_cost,
        "greedy": greedy,
    }

    method = search_methods[metodo]

    if debug:
        visor = ConsoleViewer()
        # visor = WebViewer()
    else:
        visor = BaseViewer()
    result = method(problem, graph_search=True, viewer=visor)

    if debug:
        print('estadísticas:')
        print('cantidad de acciones hasta la meta:', len(result.path()))
        print(visor.stats)
        print("FINAL STATE:")
        print(result.state)

        for i, step in enumerate(result.path()):
            cont = input("print step by step? Y/n")
            if cont.upper() == "N":
                break

            print(f"----------- STEP {i} ----------")
            action, state = step

            print("ACTION")
            print(action)

            print("STATE")
            print(state)


    return [action for action, _ in result.path() if action is not None]
Esempio n. 8
0
def main():
    problema = PresidentesProblem()

    visor = BaseViewer()
    inicio = datetime.datetime.now()
    resultado = astar(problema, graph_search=True, viewer=visor)
    tiempo = (datetime.datetime.now() - inicio).total_seconds()

    for i, (accion, estado) in enumerate(resultado.path()):
        print('Acción N: {} {} ## Estado: {}'.format(i, accion, estado))

    print("Costo: {}".format(resultado.cost))
    print("Nodos explorados: {}".format(visor.stats['visited_nodes']))
    print("Tamaño máximo frontera: {}".format(visor.stats['max_fringe_size']))
    print("Tiempo transcurrido: {} segundos".format(tiempo))
Esempio 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)
Esempio n. 10
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
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
Esempio n. 12
0
def resolver(metodo_busqueda, franceses, piratas):
    viewer = BaseViewer()
    barcos_piratas = []

    for pirata in piratas:
        barcos_piratas.append((pirata, 0))

    initial = (tuple(franceses), tuple(barcos_piratas))

    problem = entrega1(initial)

    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
def resolver(metodo_busqueda, iteraciones, haz, reinicios):
    print '··· Se van a ejecutar las 10 iteraciones para la busqueda {} ···'.format(
        metodo_busqueda)
    #print 'Haz:', haz
    #print 'Reinicios:', reinicios
    prob = HnefataflProblem(INITIAL)
    visor = BaseViewer()
    if (metodo_busqueda == 'hill_climbing'):  # Ascenso de colina
        for x in range(10):
            print 'Ejecutando Iteracion {} ...'.format(x)
            inicio = datetime.now()
            resultado = hill_climbing(problem=prob,
                                      iterations_limit=iteraciones)
            fin = datetime.now()
            print 'Tiempo de iteracion {} : {} segundos.'.format(
                x, (fin - inicio).total_seconds())
        grabar('1', max(apuntos))
    elif (metodo_busqueda == 'hill_climbing_stochastic'
          ):  # Ascenso de colina, variante estocástica
        for x in range(10):
            print 'Ejecutando Iteracion {} ...'.format(x)
            inicio = datetime.now()
            resultado = hill_climbing_stochastic(problem=prob,
                                                 iterations_limit=iteraciones)
            fin = datetime.now()
            print 'Tiempo de iteracion {} : {} segundos.'.format(
                x, (fin - inicio).total_seconds())
        grabar('2', max(apuntos))
    elif (metodo_busqueda == 'beam'):  # Haz local
        for x in range(10):
            print 'Ejecutando Iteracion {} ...'.format(x)
            inicio = datetime.now()
            resultado = beam(problem=HnefataflProblem(None),
                             iterations_limit=iteraciones,
                             beam_size=haz)
            fin = datetime.now()
            print 'Tiempo de iteracion {} : {} segundos.'.format(
                x, (fin - inicio).total_seconds())
        grabar('3', max(apuntos))
    elif (metodo_busqueda == 'hill_climbing_random_restarts'
          ):  # Ascenso de colina con reinicios aleatorios
        for x in range(10):
            print 'Ejecutando Iteracion {} ...'.format(x)
            inicio = datetime.now()
            resultado = hill_climbing_random_restarts(
                problem=HnefataflProblem(None),
                iterations_limit=iteraciones,
                restarts_limit=reinicios)
            fin = datetime.now()
            print 'Tiempo de iteracion {} : {} segundos.'.format(
                x, (fin - inicio).total_seconds())
        grabar('4', max(apuntos))
    elif (metodo_busqueda == 'simulated_annealing'):  # Temple simulado
        for x in range(10):
            print 'Ejecutando Iteracion {} ...'.format(x)
            inicio = datetime.now()
            resultado = simulated_annealing(problem=prob,
                                            iterations_limit=iteraciones)
            fin = datetime.now()
            print 'Tiempo de iteracion {} : {} segundos.'.format(
                x, (fin - inicio).total_seconds())
        grabar('5', max(apuntos))
    return resultado
Esempio n. 14
0
    
    if use_viewer:
        stats = [{'name': stat.replace('_', ' '), 'value': value}
                         for stat, value in list(use_viewer.stats.items())]
        for s in stats:
            print ('{0}: {1}'.format(s['name'],s['value']))
    return result

def getTotalCost (problem,result):
    originState = problem.initial_state
    totalCost = 0
    for action,endingState in result.path():
        if action is not None:
            totalCost += problem.cost(originState,action,endingState)
            originState = endingState
    return totalCost

# END MapExercise

# -------------------------  PROBLEM SOLVING ----------------------

initial_state = None
final_state = None
map_problem = None

problem = MapProblem(initial_state)
problem.mapProblem = map_problem
problem.final_state = final_state

MapExercise(problem,algorithm=breadth_first,use_viewer=BaseViewer())
Esempio n. 15
0
        # pero despues restamos los precios de las cosas "rotas" por conflicto
        for item_a, item_b in CONFLICTOS:
            if item_a in state and item_b in state:
                suma -= PRECIOS[item_a]
                suma -= PRECIOS[item_b]

        return suma

    def generate_random_state(self):
        items_disponibles = list(ITEMS)  # creamos una copia para nosotros
        random.shuffle(items_disponibles)

        items_equipados = []
        for i in range(4):
            items_equipados.append(items_disponibles.pop())

        return tuple(items_equipados)

print 'Hill climbing:'
v = BaseViewer()
result = hill_climbing(ItemsDota(('A', 'B', 'C', 'D')), viewer=v)
print result.state
print result.value
print v.stats


print 'Hill climbing random restarts'
result = hill_climbing_random_restarts(ItemsDota(), restarts_limit=100)
print result.state
print result.value
#
# REPRESENTACION DE LOS ESTADOS
#

#
# REPRESENTACION DE LAS ACCIONES
#

# -------------------------  RESOLUCION DE LOS PROBLEMAS ----------------------

# RESOLUCION DEL PROBLEMA 3.1.1
estado_inicial = None
estado_final = None
mapa = None

problem = MapProblem(estado_inicial)
problem.mapaProblema = mapa
problem.estado_final = estado_final

# NOTA: ejercicioMapa es una funcion de este modulo, no un metodo
# Aqui es donde podemos seleccionar WebViewer,ConsoleViewer o BaseViewer
#   BaseViewer() simplemente ejecuta y muestra las trazas y estadisticas
#   ConsoleViewer() permite ejecutar paso a paso por pantalla
#      NOTA: Para usar esto, mejor hacemos un parche a este viewer,
#            Si no, hay que poner la opcion entre comillas
#   WebViewer() usa el interfaz web
#
# ejercicioMapa(problem,algorithm=breadth_first,use_viewer=WebViewer())
ejercicioMapa(problem, algorithm=breadth_first, use_viewer=BaseViewer())
Esempio n. 17
0
            estimated_cost += distance

        return estimated_cost




INITIAL_HARDER = (
    (3, 0, 7),
    (8, 2, 1),
    (4, 6, 5),
)

problem = EightPuzzle(INITIAL_HARDER)
# viewer = WebViewer()
viewer = BaseViewer()

# result = limited_depth_first(problem, graph_search=True, viewer=viewer, depth_limit=3)
#result = astar(problem, graph_search=True)
#result = astar(problem, graph_search=True, viewer=viewer)
result = breadth_first(problem, graph_search=True, viewer=viewer)

print("Goal node:", result)

print("Path from initial to goal:")
for action, state in result.path():
    print("Action:", action)
    print("State:", state)

print("Stats:")
print(viewer.stats)
            lugar = 'A'
            duracion -= VALORES[z]
        return (lugar, duracion), tuple(alist), tuple(blist)

        def cost(self, state1, action, state2):
            mov, a = action

        if mov == 'Mover':
            x, y = a
            return max(VALORES[x], VALORES[y])
        else:
            return VALORES[a]

    def heuristic(self, state):
        linterna, a, b = state
        sincruzar = len(a)
        if linterna[0] == 'A':
            return sincruzar + (sincruzar - 1)
        else:
            if sincruzar == 0:
                return 0
            else:
                return sincruzar * 2


problema = Problema(ESTADO)
visor = BaseViewer()
respuesta = astar(problema, graph_search=True, viewer=visor)
for a in respuesta.path():
    print a
print 'respuesta final', respuesta
Esempio n. 19
0
        state = string2list(state)
        cost = 0
        for number, correct_position in GOAL_POSITIONS.items():
            current_position = find_number(state, number)
            diff_x = abs(current_position[0] - correct_position[0])
            diff_y = abs(current_position[1] - correct_position[1])
            cost += diff_x + diff_y

        return cost

    def heuristic_MALA(self, state):
        cost = 0
        for i in range(len(state)):
            if state[i] != '0' and state[i] != GOAL[i]:
                cost += 1

        return cost


visor = BaseViewer()  # o WebViewer() o ConsoleViewer()

result = astar(EightPuzzleProblem("7,2,4|5,0,6|8,3,1"),
               viewer=visor,
               graph_search=True)

print result.state
print result.path()
print len(result.path())

print visor.stats