def test_rr_searches(restarts, initial_max): hill_restart_solution = 0 hill_avg = [] annealing_restart_solution = 0 annealing_avg = [] for i in range(restarts): # Get new starting point internal_p = SineVariant(randrange(0, initial_max), initial_max, delta=1) # Solve using hill-climbing + random restarts current_hill_solution = hill_climbing(internal_p) hill_avg.append(current_hill_solution) if current_hill_solution > hill_restart_solution: hill_restart_solution = current_hill_solution # Solve the problem using simulated annealing + random restarts current_annealing_solution = simulated_annealing( internal_p, exp_schedule(k=30, lam=0.005, limit=1000)) annealing_avg.append(current_annealing_solution) if current_annealing_solution > annealing_restart_solution: annealing_restart_solution = current_annealing_solution # Print results of each test print('Hill-climbing (RR) solution x: ' + str(hill_restart_solution) + '\t\tvalue: ' + str(internal_p.value(hill_restart_solution)) + '\taverage of runs: ' + str(sum(hill_avg) / len(hill_avg))) print('Simulated annealing (RR) solution x: ' + str(annealing_restart_solution) + '\t\tvalue: ' + str(internal_p.value(annealing_restart_solution)) + '\taverage of runs: ' + str(sum(annealing_avg) / len(annealing_avg)))
def compare_algorithms_for_this_world(world, dist_dict, attempts=30, print_solution=False): # using the initial as our baseline best_hill_climber = world best_annealing = world # initializing averages avg_hill_climber = 0 avg_annealing = 0 # our small world problem representation tsp = TSP(world, dist_dict) # try both algorithms over and over for i in range(0, attempts): hill_climber = hill_climbing(tsp) annealing = simulated_annealing( tsp, exp_schedule(k=20, lam=0.005, limit=1000)) # keep track of the best solutions if tsp.value(hill_climber) > tsp.value(best_hill_climber): best_hill_climber = hill_climber if tsp.value(annealing) > tsp.value(best_annealing): best_annealing = annealing # maintain average values avg_hill_climber += tsp.value(hill_climber) avg_annealing += tsp.value(annealing) # Calculate the average avg_hill_climber /= attempts avg_annealing /= attempts # Ouptut: world statistics print("World of size " + str(len(world)) + " with " + str(attempts) + " per algorithm") hill_path = str(best_hill_climber) annealing_path = str(best_annealing) if not print_solution: hill_path = "" annealing_path = "" # Output: hill climbing results print("Hill Climbing:\t" + hill_path + "\tbest: " + str(tsp.value(best_hill_climber)) + "\tavg: " + str(round(avg_hill_climber, 2))) # Output: simulated annealing results print("Annealing:\t" + annealing_path + "\tbest: " + str(tsp.value(best_annealing)) + "\tavg: " + str(round(avg_annealing, 2)))
def test_knapsack_simulated_annealing_large_scale_1(): params = open_file("../dataset/large_scale/knapPI_1_100_1000_1") problem = KnapsackProblem(params[0], params[1]) ins_problem = InstrumentedProblem(problem) result = simulated_annealing(ins_problem, exp_schedule(1000, 0.0005, 4000)) optimum = int(( open("../dataset/large_scale-optimum/knapPI_1_100_1000_1").readline())) assert optimum == 9147 assert result.value <= optimum assert result.value >= 8000
def test_knapsack_simulated_annealing_low_dimensional_2(): params = open_file("../dataset/low-dimensional/f2_l-d_kp_20_878") problem = KnapsackProblem(params[0], params[1]) ins_problem = InstrumentedProblem(problem) result = simulated_annealing(ins_problem, exp_schedule(2000, 0.00005, 200000)) optimum = int((open( "../dataset/low-dimensional-optimum/f2_l-d_kp_20_878").readline())) assert optimum == 1024 assert result.value == optimum
def test_searches(searchspace): # Solve the problem using hill-climbing. hill_solution = hill_climbing(searchspace) print('Hill-climbing solution x: ' + str(hill_solution) + '\t\tvalue: ' + str(p.value(hill_solution))) # Solve the problem using simulated annealing. annealing_solution = simulated_annealing( searchspace, exp_schedule(k=30, lam=0.005, limit=1000)) print('Simulated annealing solution x: ' + str(annealing_solution) + '\t\tvalue: ' + str(p.value(annealing_solution)))
def main(): r = csv.reader(file('../step2.csv')) titles = r.next() data = [array(map(float, csValues)) for csValues in r] valueFunc = value(data) final = simulated_annealing( zeros((len(titles) - 1,)), successor2, valueFunc, schedule=search.exp_schedule(k=0.1, lam=0.0015)) print valueFunc(final) print final
def simulated_annealing(initial, successor, value, schedule=search.exp_schedule()): current = initial val_cur = value(current) try: for t in xrange(sys.maxint): T = schedule(t) print '%5d %0.4f %0.6f' % (t, T, val_cur) if T == 0: return current next = successor(current) val_next = value(next) delta_e = val_next - val_cur if delta_e < 0 or utils.probability(math.exp(-delta_e/T)): current = next val_cur = val_next except BaseException, e: traceback.print_exc() return current
return math.fabs(x * math.sin(x)) if __name__ == '__main__': # Formulate a problem with a 2D hill function and a single maximum value. maximum = 30 initial = randrange(0, maximum) p = SineVariant(initial, maximum, delta=1.1) print('Initial x: ' + str(p.initial) + '\t\tvalue: ' + str(p.value(initial))) # Solve the problem using hill-climbing. hill_solution = hill_climbing(p) annealing_solution = simulated_annealing( p, exp_schedule(k=20, lam=0.005, limit=1000)) hill_restarts = hill_solution hill_value_accumulator = 0 hill_x_accumulator = 0 annealing_restarts = annealing_solution annealing_value_accumulator = 0 annealing_x_accumulator = 0 restarts = 100 for i in range(restarts): initial = randrange(0, maximum) p = SineVariant(initial, maximum, delta=1.1) hill_solution = hill_climbing(p)
(10, 3): 9, (10, 4): 2, (10, 5): 1, (10, 6): 6, (10, 7): 4, (10, 8): 6, (10, 9): 8, (10, 10): 3 } # print(cities) # Initialize a path using numerical order path = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0] # Initialize the TSP problem p = TSP(cities, distances, path) print("Initial Path:", path) # Solve the problem using hill climbing. hill_solution = hill_climbing(p) print('\nHill-climbing:') print('\tSolution:\t' + str(hill_solution)) print('\tValue:\t\t' + str(p.value(hill_solution))) # Solve the problem using simulated annealing. annealing_solution = \ simulated_annealing(p, exp_schedule(k=20, lam=0.005, limit=10000)) print('\nSimulated annealing:') print('\tSolution:\t' + str(annealing_solution)) print('\tValue:\t\t' + str(p.value(annealing_solution)))
class TSP2(Problem): def __init__(self, n, initial): self.n = n self.initial = initial def actions(self, state): actions = [] for column in range(self.n): for row in [x for x in range(self.n) if x != state[column]]: actions.append([column, row]) for i in range(1,10): return actions def result(self, state, move): """Makes the given move on a copy of the given state.""" new_state = state[:] new_state[move[0]] = move[1] return new_state def goal_test(self, state): """Check to see if there are no conflicts.""" return not any(self.conflicted(state, state[col], col) for col in range(len(state))) def conflicted(self, state, row, col): """Check to see if placing a queen at (row, col) would conflict with anything. """ return any(self.conflict(row, col, state[c], c) for c in range(col)) def conflict(self, row1, col1, row2, col2): """Check to see if two queens placed in (row1, col1) and (row2, col2) respectively would conflict with each other. """ return (row1 == row2 # # same row or col1 == col2 # # same column or row1 - col1 == row2 - col2 # # same \ diagonal or row1 + col1 == row2 + col2) # # same / diagonal def value(self, state): """This method computes a value of given state based on the number of conflicting pairs of queens. It doesn't follow AIMA-Python's NQueens gradient-descent formulation; instead, it counts the number of non-conflicting pairs (e.g., top score: 28 for a 8-queen problem; worst score: 0). """ # Start with the highest possible score (n combined 2). value = math.factorial(self.n) / (2 * math.factorial(self.n - 2)) # Loop through all pairs, subtracting one for every conflicted pair. for pair in itertools.combinations(range(self.n), 2): if self.conflict(state[pair[0]], pair[0], state[pair[1]], pair[1]): value -= 1 return value if __name__ == '__main__': # Set the board size. n = 8 # Initialize the board with all queens in the first row. board = [0] * n print('Start: ' + str(board)) # Initialize the NQueens problem p = TSP2(n, board) print('Value: ' + str(p.value(board))) # Solve the problem using hill climbing. hill_solution = hill_climbing(p) print('Hill-climbing:') print('\tSolution: ' + str(hill_solution)) print('\tValue: ' + str(p.value(hill_solution))) print('\tGoal? ' + str(p.goal_test(hill_solution))) # Solve the problem using simulated annealing. annealing_solution = simulated_annealing( p, exp_schedule(k=20, lam=0.005, limit=10000) ) print('Simulated annealing:') print('\tSolution: ' + str(annealing_solution)) print('\tValue: ' + str(p.value(annealing_solution))) print('\tGoal? ' + str(p.goal_test(annealing_solution)))
for k in vertexstring[i + 1:]: vertex_dict[k] = rnd.randint(1, maxdist) graph_dict[vertexstring[i]] = vertex_dict return graph_dict if __name__ == '__main__': # invalid_it = ['C','D','B','A'] # valid_it = ['C','A','B','D'] # simpleTSP = TSP(invalid_it, simple_map) # print(hill_climbing(simpleTSP)) graph_dict = gen_graph(vertexstring='ABCDEFGHIJKLMNOPQRSTUVWXYZ') print(graph_dict) myGraph = UndirectedGraph(graph_dict) myTSP = TSP(get_city_list(myGraph), myGraph) values = [] for _ in range(1000): hill_climbing_solution = hill_climbing(myTSP) values.append(myTSP.value(hill_climbing_solution)) # print(hill_climbing_solution) # print(myTSP.value(hill_climbing_solution)) print(max(values)) annealing_solution = simulated_annealing(myTSP, exp_schedule(k=20, lam=0.005, limit=100000)) print(annealing_solution) print(myTSP.value(annealing_solution))
eforie=(562, 293), fagaras=(305, 449), giurgiu=(375, 270), hirsova=(534, 350), iasi=(473, 506), lugoj=(165, 379), mehadia=(168, 339), neamt=(406, 537), oradea=(131, 571), pitesti=(320, 368), rimnicuvilcea=(233, 410), sibiu=(207, 457), timisoara=(94, 410), urziceni=(456, 350), vaslui=(509, 444), zerind=(108, 531)) initial1 = random.choice(list(locations.keys())) problem1 = TSP(locations, initial1) initial2 = random.choice(list(locations.keys())) problem2 = TSP(locations, initial2) hill_solution = hill_climbing(problem1) print('\nHill-climbing solution x: ' + '\tvalue: ' + str(math.fabs(problem1.value(hill_solution))) + "\n\n") annealing_solution = simulated_annealing( problem2, exp_schedule(k=20, lam=0.005, limit=15000)) print('\nAnnealing solution x: ' + '\tvalue: ' + str(math.fabs(problem2.value(annealing_solution))) + "\n\n")