Ejemplo n.º 1
0
def main():
    metodo = raw_input(
        "Ingrese el metodo de busqueda-- (greedy,depth_first,breadth_first,astar)\n"
    )
    STATE = generarEstado(LABERINTO)
    problema = rataProblem(STATE)
    if metodo == "breadth_first":
        r = breadth_first(problema, graph_search=True, viewer=ConsoleViewer())

    if metodo == "greedy":
        r = greedy(problema, graph_search=True, viewer=ConsoleViewer())

    if metodo == "depth_first":
        r = depth_first(problema, graph_search=True, viewer=ConsoleViewer())

    if metodo == "astar":
        r = astar(problema, graph_search=True, viewer=ConsoleViewer())

    print(
        "=======================================================================\n"
    )
    print "Estado final :", r.state, "\n"
    print "Path :", r.path(), "\n"
    l = [x[0] for x in r.path()]
    print "Acciones tomadas", l, "\n"
    print "Costo :", r.cost, "\n"
Ejemplo n.º 2
0
def resolver(metodo_busqueda, iteraciones, haz, reinicios):

    visor = ConsoleViewer()

    if (metodo_busqueda == 'hill_climbing'):
        resultado = hill_climbing(problem=HnefataflProblema(INITIAL),
                                  iterations_limit=iteraciones)
        return resultado

    if (metodo_busqueda == 'hill_climbing_stochastic'):
        resultado = hill_climbing_stochastic(
            problem=HnefataflProblema(INITIAL), iterations_limit=iteraciones)
        return resultado

    if (metodo_busqueda == 'beam'):
        resultado = beam(problem=HnefataflProblema(None),
                         beam_size=haz,
                         iterations_limit=iteraciones)
        return resultado

    if (metodo_busqueda == 'hill_climbing_random_restarts'):
        resultado = hill_climbing_random_restarts(
            problem=HnefataflProblema(None),
            restarts_limit=reinicios,
            iterations_limit=iteraciones)
        return resultado

    if (metodo_busqueda == 'simulated_annealing'):
        resultado = simulated_annealing(problem=HnefataflProblema(INITIAL),
                                        iterations_limit=iteraciones)
        return resultado
Ejemplo n.º 3
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())
Ejemplo 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
    use_viewer = ConsoleViewer()

    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=use_viewer)

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

        print(searchInfo(problem, result, use_viewer))

        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], a[1])
            }) for a in detailed_path)

        return plan, problem, result, use_viewer
    else:
        print("WARNING: A solution was not found for the final state: {0}".
              format(problem.GOAL))
        return None, None, None, None
Ejemplo n.º 5
0
def main():
	estado = "{}|0|I|".format("1-3-6-8-12")
	problema = problemaLinterna(estado)
	metodo = raw_input("Ingrese el metodo de busqueda-- (greedy,depth_first,breadth_first)\n")

	if metodo == "breadth_first":    
 		p = breadth_first(problema,graph_search=True,viewer=ConsoleViewer())
    	
	if metodo == "greedy":    
		p = greedy(problema,graph_search=True,viewer=ConsoleViewer())

	if metodo == "depth_first":    
		p = depth_first(problema,graph_search=True,viewer=ConsoleViewer())

	
	print("=======================================================================\n")
	print "Estado final :",p.state,"\n"
	print "Path :",p.path(),"\n"
	l = [x[0] for x in p.path()]
	print "Acciones tomadas",l,"\n"
	print "Costo :",p.cost*10,"segundos","\n"
Ejemplo n.º 6
0
def main():

    metodo = raw_input(
        "Ingrese el metodo de busqueda-- (greedy,depth_first,breadth_first)\n")
    problema = problemaLaberinto("1")

    if metodo == "breadth_first":
        p = breadth_first(problema, graph_search=True, viewer=ConsoleViewer())

    if metodo == "greedy":
        p = greedy(problema, graph_search=True, viewer=ConsoleViewer())

    if metodo == "depth_first":
        p = depth_first(problema, graph_search=True, viewer=ConsoleViewer())

    print(
        "=======================================================================\n"
    )
    print "Estado final :", p.state, "\n"
    print "Path :", p.path(), "\n"
    l = [x[0] for x in p.path()]
    print "Acciones tomadas", l, "\n"
    print "Costo :", p.cost, "\n"
Ejemplo 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]
Ejemplo n.º 8
0
def main():

    jugador = raw_input("Ingrese la posicion del jugador EJ: 0-2\n")
    enemigo = raw_input("Ingrese la posicion del enemigo EJ: 0-5\n")
    castillo = raw_input("Ingrese la posicion del castillo EJ: 3-2\n")

    global longitud
    longitud = int(raw_input("Ingrese la longitud de la grilla \n")) - 1

    metodo = raw_input(
        "Ingrese el metodo de busqueda-- (greedy,depth_first,breadth_first,astar)\n"
    )

    estado = generar_estados([jugador, enemigo, castillo])
    problema = prolemaDota(estado)

    if metodo == "breadth_first":
        p = breadth_first(problema, graph_search=True, viewer=ConsoleViewer())

    if metodo == "greedy":
        p = greedy(problema, graph_search=True, viewer=ConsoleViewer())

    if metodo == "depth_first":
        p = depth_first(problema, graph_search=True, viewer=ConsoleViewer())

    if metodo == "astar":
        p = astar(problema, graph_search=True, viewer=ConsoleViewer())

    print(
        "=======================================================================\n"
    )
    print "Estado final :", p.state, "\n"
    print "Path :", p.path(), "\n"
    l = [x[0] for x in p.path()]
    print "Acciones tomadas", l, "\n"
    print "Costo :", p.cost, "\n"
Ejemplo n.º 9
0
    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


#if __name__ == '__main__':

#viewer = WebViewer()
viewer = ConsoleViewer()
#viewer = None
#viewer = BaseViewer()

#metodo = "greedy"
metodo = "breadth_first"
#metodo = "astar"
#metodo = "uniform_cost"
#metodo = "depth_first"

franceses = [(0, 2), (0, 3), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 0),
             (3, 1), (3, 2), (4, 0), (4, 1), (5, 0)]
piratas = [(4, 4, 0), (4, 5, 0), (5, 4, 0)]

result = resolver(metodo, franceses, piratas)
# 4.3 - esto tiene que tener un ojetivo
class resolvedor(SearchProblem):
    def actions(self, estado):
        if len(estado) < len(objetivo):
            return list(caracteres)
        else:
            return []

    def heuristic(self, estado):
        erradas = sum(
            [1 if estado[i] != objetivo[i] else 0 for i in range(len(estado))])
        perdidas = len(objetivo) - len(estado)
        return erradas + perdidas

    def result(self, estado, accion):
        return estado + accion

    def is_goal(self, estado):
        return estado == objetivo


# 5 - se instancia
#     se parte desde vacio
#     se crea un visualizador de solucion
#     se le dice que lo resuelva
problema = resolvedor(initial_state="")
visualizadorSolucion = ConsoleViewer()
solucion = astar(problema, viewer=visualizadorSolucion)
# Se procede a mostar la solucion:
print(solucion.path())