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
def resolver(metodo_busqueda): vwr = BaseViewer() if metodo_busqueda == "hill_climbing": result = hill_climbing(DotaArmamento(INITIAL), viewer=vwr, iterations_limit=1000) elif metodo_busqueda == "beam": result = beam(DotaArmamento(), beam_size=100, viewer=vwr, iterations_limit=1000) elif metodo_busqueda == "hill_climbing_random_restarts": result = hill_climbing_random_restarts(DotaArmamento(), restarts_limit=100, viewer=vwr, iterations_limit=1000) return result
def pixelize_image(self, method, points=None): best_state = None triangle_mask = None if points is None: best_state = cacher.best_state(self.image_name, self.max_points) if best_state is not None: triangle_mask = best_state if triangle_mask is None: triangle_mask = TriangleMask(self.width, self.height) my_problem = SplitProblem( triangle_mask, split_image=self ) if method == "astar": result = astar(my_problem, graph_search = True) elif method == "beam": result = beam(my_problem) elif method == "hill_random": result = hill_climbing_random_restarts(my_problem, 1) elif method == "hill": result = hill_climbing(my_problem) else: print("Invalid method: {}".format(method)) return print("FINAL RESULT REACHED") print("RESULT: {}".format( result.state.triangles)) # TODO: Make caching work with triangle masks cacher.persist_log( self.image_name ) triangle_mask = result.state triangles = triangle_mask.triangles self.display(triangles) if self.wait: a = input("Would you like to improve on this?\n") a = a.upper().strip() if a not in {"Y","YES","YUP","YEAH"}: return method_temp = input("Which method? [{}]\n".format(method)).strip().lower() if method_temp: method = method_temp max_points = input("How many points? [{}]\n".format(self.max_points)).strip() if max_points: self.max_points = int(max_points) return self.pixelize_image(method, points) return triangles
def resolver(metodo_busqueda, iteraciones, haz, reinicios): #problema = Hnefatafl(INICIAL) if metodo_busqueda == "hill_climbing": resultado = hill_climbing(Hnefatafl(INICIAL), iteraciones) if metodo_busqueda == "hill_climbing_stochastic": resultado = hill_climbing_stochastic(Hnefatafl(INICIAL), iteraciones) if metodo_busqueda == "hill_climbing_random_restarts": resultado = hill_climbing_random_restarts(Hnefatafl(None), reinicios, iteraciones) if metodo_busqueda == "beam": resultado = beam(Hnefatafl(INICIAL), beam_size = haz, iterations_limit = iteraciones) if metodo_busqueda == "simulated_annealing": resultado = simulated_annealing(Hnefatafl(INICIAL), iterations_limit = iteraciones) return resultado
def resolver(metodo_busqueda, iteraciones, haz, reinicios): problema = HnefataflProblem(inicial()) if metodo_busqueda == "hill_climbing": resultado = hill_climbing(problema, iteraciones) return resultado if metodo_busqueda == "hill_climbing_stochastic": return hill_climbing_stochastic(problema, iteraciones) if metodo_busqueda == "beam": return beam(problema, haz, iteraciones) if metodo_busqueda == "hill_climbing_random_restarts": return hill_climbing_random_restarts(problema, reinicios, iteraciones) if metodo_busqueda == "simulated_annealing": return simulated_annealing(problema, iterations_limit=iteraciones)
def resolver(metodo_busqueda, iteraciones, haz, reinicios): problema_inicial = Hnefatafl2(INICIAL) if metodo_busqueda == "hill_climbing": return hill_climbing(problema_inicial, iteraciones) if metodo_busqueda == "hill_climbing_stochastic": return hill_climbing_stochastic(problema_inicial, iteraciones) if metodo_busqueda == "beam": return beam(problema_inicial, haz, iteraciones) if metodo_busqueda == "hill_climbing_random_restarts": return hill_climbing_random_restarts(problema_inicial, reinicios, iteraciones) if metodo_busqueda == "simulated_annealing": return simulated_annealing(problema_inicial, iterations_limit=iteraciones)
# 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
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
'''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 for number in '12345678e': row_n, col_n = find_location(rows, number) row_n_goal, col_n_goal = goal_positions[number] distance += abs(row_n - row_n_goal) + abs(col_n - col_n_goal) return distance result = astar(EigthPuzzleProblem(INITIAL)) result = hill_climbing(EigthPuzzleProblem(INITIAL)) # if you want to use the visual debugger, use this instead: # result = astar(EigthPuzzleProblem(INITIAL), viewer=WebViewer()) for action, state in result.path(): print('Move number', action) print(state)
state[reina] = fila return tuple(state) def value(self, state): maldad = 0 for reina, fila in enumerate(state): for reina2, fila2 in enumerate(state): if reina != reina2: diferencia_c = abs(reina - reina2) diferencia_f = abs(fila - fila2) if fila == fila2 or diferencia_c == diferencia_f: maldad += 1 return -maldad def generate_random_state(self): return tuple(random.randint(0, 7) for x in range(8)) result = hill_climbing(OchoReinas(INITIAL)) #result = hill_climbing_stochastic(OchoReinas(INITIAL)) #result = hill_climbing_random_restarts(OchoReinas(), restarts_limit=100) #result = beam(OchoReinas(), beam_size=5) #result = simulated_annealing(OchoReinas(INITIAL), iterations_limit=20) print result
return tuple(state) def print_state(self, state): elements = { str(element): [(row_i, column_i)] for row_i, row in enumerate(state) for column_i, element in enumerate(row) } print_grid(SQUARE_SIZE, SQUARE_SIZE, elements) if __name__ == "__main__": expected_value = SQUARE_SIZE * 2 iterations = 0 while True: iterations += 1 random_state = MagicSquareProblem().generate_random_state() problem = MagicSquareProblem(random_state) result = hill_climbing(problem, 1000) if result.value == expected_value: print("solution found! Iterations:", iterations) break if iterations % 10 == 0: print( f"{iterations} iterations and the solution hasn't been found yet :(" ) problem.print_state(result.state) print("value:", problem.value(result.state))
if fila == fila2: ataques += 1 elif abs(fila - fila2) == abs(columna - columna2): ataques += 1 return -ataques def generate_random_state(self): state = [] for _ in range(8): state.append(random.randint(0, 7)) return tuple(state) result = hill_climbing(QueensProblem(INITIAL)) print 'Hill climbing:' print result.state print QueensProblem().value(result.state) result = hill_climbing_stochastic(QueensProblem(INITIAL)) print 'Hill climbing stochastic:' print result.state print QueensProblem().value(result.state) result = beam(QueensProblem(), beam_size=10) print 'Beam:' print result.state print QueensProblem().value(result.state) result = hill_climbing_random_restarts(QueensProblem(), restarts_limit=100)
from Mapa.crearMapa import crearMapa from simpleai.search import breadth_first, depth_first, greedy, uniform_cost, astar, hill_climbing from Draw.Drawings import getResults from SituacionProblema.TercerAvance.SituacionProblema import Rover if __name__ == '__main__': print_map = True mapa = crearMapa(20, 30, 20, 1, True) problema = Rover(mapa, 5) output = hill_climbing(problema) print(mapa) print('\nPath to the solution:') print(output.path()) for item, state in output.path(): print("nivel", problema.nivel) print("state", state) print("item", item) print(mapa[:state] + "$" + mapa[state+1:]) print(f"Valor = {problema.value(state)}") """ while True: try: print_map = True mapa = crearMapa(20, 30, 20, 1, True) problema = Rover(mapa) if print_map: print("------------------------------------------- Mapa Inicial -------------------------------------------") print(mapa) getResults(mapa, problema, breadth_first, 'breadth_first', print_map) getResults(mapa, problema, depth_first, 'depth_first', print_map) getResults(mapa, problema, greedy, 'greedy', print_map)