def doBasic(grid, size, iters, prob = 0): grid2, value, solution = solver.solve_puzzle(grid, size) best_val = value best_found = False best_grid = deepcopy(grid) grid_gen = deepcopy(grid) best_grid_s = deepcopy(grid2) best_sol = solution # Iterate for the number we specify for i in range(iters): rand_val = random.uniform(0, 1) prev_grid = deepcopy(grid_gen) grid_gen, grid_s, value_gen, solution_s = generate_grid(grid_gen, size) # print("BEST: " + str(best_val) + "\nGEN: " + str(value_gen) + "\nRAND: " + str(rand_val) + "\n------------") # If the value we generate is better than the best we make a new global best. Also if the value is the same we do not # consider a new max found, but still set the current puzzle as best. if value_gen >= best_val: if not value_gen == best_val: best_found = True best_val = value_gen best_grid = grid_gen best_grid_s = grid_s best_sol = solution_s # For random walk we determine if we should accept the new puzzle or not to go downhill elif best_found and rand_val > prob: grid_gen = prev_grid best_grid = np.array(best_grid).tolist() best_grid = [item for sublist in best_grid for item in sublist] best_grid_s = np.array(best_grid_s).tolist() best_grid_s = [item for sublist in best_grid_s for item in sublist] if best_val > 0: best_sol = "Puzzle Value: " + str(best_val) + "\n" + best_sol # best_sol = "Puzzle Value: " + str(best_val) + "\n" + best_sol + "\nIterations: " + str(i) + "\nCompute Time: " + "{0:.2f}".format(end - start) + "s" return best_grid, best_grid_s, best_val, best_sol, i + 1
def doRestart(grid, size, iters, iters_per): grid2, value, solution = solver.solve_puzzle(grid, size) best_val = value new_best = False best_grid = deepcopy(grid) grid_gen = deepcopy(grid) best_grid_s = deepcopy(grid2) best_sol = solution start = time.time() it = 0 for i in range(iters): grid_gen = generate_rand_grid(size) grid_g, grid_s, value_gen, solution_s, iters = doBasic(grid_gen, size, iters_per) it += iters if value_gen >= best_val: new_best = True best_val = value_gen best_grid = grid_gen best_grid_s = grid_s best_sol = solution_s end = time.time() best_grid = np.array(best_grid).tolist() best_grid = [item for sublist in best_grid for item in sublist] best_grid_s = np.array(best_grid_s).tolist() if len(best_grid_s) <= size: best_grid_s = [item for sublist in best_grid_s for item in sublist] if not new_best: best_sol = "Puzzle Value: " + str(best_val) + "\n" + best_sol return best_grid, best_grid_s, best_val, best_sol, it
def generate_rand_grid(n): while True: num_arr = [] for i in range(0, n): row = [] for j in range(0, n): row.append(random.randint(1, n - 1)) num_arr.append(row) num_arr[n - 1][n - 1] = 0 grid2, value, solution = solver.solve_puzzle(num_arr, n) if value > 0: return num_arr, value
def generate_grid(grid, size): orig_grid = deepcopy(grid) while True: rand_coord = [random.randint(0, size-1), random.randint(0, size-1)] rand_mag = random.randint(1, size-1) if not (rand_coord == [size-1,size-1]) and rand_mag != grid[rand_coord[0]][rand_coord[1]]: grid_gen = grid[:] grid_gen[rand_coord[0]][rand_coord[1]] = rand_mag grid_s, value_gen, solution_s = solver.solve_puzzle(grid_gen, size) if value_gen > 0: return grid_gen, grid_s, value_gen, solution_s else: grid = deepcopy(orig_grid)
def showhello(arr=None, size=5): try: size = int(request.form['size']) except Exception as e: pass if arr == None: grid = make_grid_nums(size) else: grid = arr grid2, value, solution = solver.solve_puzzle(grid, size) return render_template('/grid.html', nums=grid, size=size, grid2=grid2, sol=solution, value=value)
def doAnneal(grid, size, iters, temp_init, decay): grid2, value, solution = solver.solve_puzzle(grid, size) best_val = value prev_val = best_val best_found = False best_grid = deepcopy(grid) grid_gen = deepcopy(grid) best_grid_s = deepcopy(grid2) best_sol = solution accept_prob = 1 for i in range(iters): prev_grid = deepcopy(grid_gen) grid_gen, grid_s, value_gen, solution_s = generate_grid(grid_gen, size) try: # Calculate the acceptance probability accept_prob = math.exp((value_gen - prev_val) / (1.0 * temp_init)) except: accept_prob = 1 rand_val = random.uniform(0, 1) # print("Prev Val: " + str(prev_val) + "\nGen Val: " + str(value_gen) + "\nTemp: " + str(temp_init) + "\nAccept prob: " + str(accept_prob) + "\nRandom Value: " + str(rand_val) + "\n---------------") prev_val = value_gen if value_gen >= best_val: best_found = True best_val = value_gen best_grid = grid_gen best_grid_s = grid_s best_sol = solution_s elif rand_val > accept_prob: grid_gen = prev_grid temp_init *= decay temp_init = max(.01, temp_init) best_grid = np.array(best_grid).tolist() best_grid = [item for sublist in best_grid for item in sublist] best_grid_s = np.array(best_grid_s).tolist() best_grid_s = [item for sublist in best_grid_s for item in sublist] if best_val > 0: best_sol = "Puzzle Value: " + str(best_val) + "\n" + best_sol # best_sol = "Puzzle Value: " + str(best_val) + "\n" + best_sol + "\nIterations: " + str(i) + "\nCompute Time: " + "{0:.2f}".format(end - start) + "s" return best_grid, best_grid_s, best_val, best_sol, i + 1
def doGenetic(grid, size, iters): grid2, value, solution = solver.solve_puzzle(grid, size) best_val = value rand_array1 = [size-1] #bottom row replacement rand_array2 = [size-1] #right-most row replacement grid3 = deepcopy(grid) grid4 = deepcopy(grid) move_score1 = 0 move_score2 = 0 #score for each grid_score1 = 0 #bottom-most row score grid_score2 = 0 #right-most column score for x in range(0, size): rand_array1[x] = random.randint(1, size-x) rand_array2[x] = random.randint(1, size-x) for x in range(0, size): if rand_array1[x] <= size-x-1: move_score1 += 1 if rand_array2[x] <= size-x-1: move_score2 += 1 if grid3[size-1][x] <= size-x-1: grid_score1 += 1 if grid3[x][size-1] <= size-x-1: grid_score2 += 1 swapper(grid4, size, rand_array1, rand_array2, move_score1, move_score2, grid_score1, grid_score2)
def doGenetic(grid, size, iters, initial_pop, num_child, mutation_rate): current_pop = [] if initial_pop % 2 == 1: initial_pop += 1 # we create the initial population here for i in range(initial_pop): grid_gen, value_gen = generate_rand_grid(size) current_pop.append([grid_gen, value_gen]) current_pop.sort(key=itemgetter(1), reverse=True) for j in range(iters): children = [] for k in range(0, len(current_pop) - 1, 2): for ch in range(num_child): # Create a copy of each parent to use for each pair of children curr_parent1 = deepcopy(current_pop[k][0]) curr_parent2 = deepcopy(current_pop[k + 1][0]) # choose random segment in parent to swap and make the new children while True: rand_x = random.sample(range(0, (size)), 2) rand_y = random.sample(range(0, (size)), 2) rand_x_start = rand_x[0] rand_x_end = rand_x[1] rand_y_start = rand_y[0] rand_y_end = rand_y[1] if rand_x_start >= rand_x_end: temp = rand_x_start rand_x_start = rand_x_end rand_x_end = temp if rand_y_start >= rand_y_end: temp = rand_y_start rand_y_start = rand_y_end rand_y_end = temp if [rand_x_end, rand_y_end] != [size - 1, size - 1]: break tmp_chromo1 = [] tmp_chromo2 = [] # create the chromosome strings here for num in range(rand_x_start, rand_x_end): for num2 in range(rand_y_start, rand_y_end): tmp_chromo1.append(curr_parent1[num][num2]) tmp_chromo2.append(curr_parent2[num][num2]) count = 0 rand_val1 = random.uniform(0, 1) rand_val2 = random.uniform(0, 1) # swap the chromosomes here for num in range(rand_x_start, rand_x_end): for num2 in range(rand_y_start, rand_y_end): # a random chance of mutation can occur when switching genes if rand_val1 < mutation_rate: tmp_chromo1[count] = random.randint(1, (size) - 1) if rand_val2 < mutation_rate: tmp_chromo2[count] = random.randint(1, (size) - 1) curr_parent1[num][num2] = tmp_chromo2[count] curr_parent2[num][num2] = tmp_chromo1[count] count += 1 children.append(curr_parent1) children.append(curr_parent2) if len(children) % 2 == 1: children = children[:len(children) - 2] current_pop = [] for l in children: grid2, value, solution = solver.solve_puzzle(l, size) current_pop.append([l, value]) current_pop.sort(key=itemgetter(1), reverse=True) # for i in current_pop: # print(i[1]) # print("--------------------") current_pop = current_pop[:initial_pop] best_grid = np.array(current_pop[-1][0]).tolist() best_grid_s, best_val, best_sol = solver.solve_puzzle(best_grid, size) best_grid = [item for sublist in best_grid for item in sublist] best_grid_s = np.array(best_grid_s).tolist() best_grid_s = [item for sublist in best_grid_s for item in sublist] if best_val > 0: best_sol = "Puzzle Value: " + str(best_val) + "\n" + best_sol # best_sol = "Puzzle Value: " + str(best_val) + "\n" + best_sol + "\nIterations: " + str(i) + "\nCompute Time: " + "{0:.2f}".format(end - start) + "s" return best_grid, best_grid_s, best_val, best_sol