def annealing(self, original_call): complete = False self.current.h = nqueens.numAttackingQueens(self.current) if (self.T <= self.min_T): complete = True else: next_boards = nqueens.getSuccessorStates( self.current ) #I might not be calling this right, but hopefully you get the idea next_board = next_boards[random.randint(0, len(next_boards) - 1)] next_board.h = nqueens.numAttackingQueens(next_board) delta_E = self.findDeltaE( next_board) #The method that armond's writing. if delta_E > 0: self.current = next_board else: if random.random > self.threshold( delta_E): #The method that Allen's writing. self.current = next_board self.decrement_T( ) #The method that Nolan's already written. Nolan, please correct the syntax of this line if incorrect. self.annealing(False) if original_call: self.current.printBoard() print self.current.h
def annealing(self): #sam's method that does algoritom counter = 0 complete = False while complete == False: self.current.h = nqueens.numAttackingQueens(self.current) if self.current.h == 0: complete = True print ">Solution found no attacking queens!<" break elif (self.T <= self.min_T): complete = True print ">Timeout termination final state as above<" break else: next_boards = nqueens.getSuccessorStates(self.current) index = random.randint(0, len(next_boards) - 1) next_board = next_boards[index] next_board.h = nqueens.numAttackingQueens(next_board) delta_E = self.findDeltaE( next_board) #The method that armond's writing. if delta_E < 0 and self.current.h > next_board.h: self.current = next_board self.current.h = nqueens.numAttackingQueens(self.current) else: if random.random > self.threshold( delta_E): #The method that Allen's writing. self.current = next_board self.current.h = nqueens.numAttackingQueens( self.current) self.decrement_T() print "run: " + str(counter) self.current.printBoard() print "h value: " + str(self.current.h) print " " counter += 1
def annealing(b, T, decay_rate, threshold): current = b current.h = nqueens.numAttackingQueens(current) #Annealing algorithm while (T > threshold or current.h != 0): current.h = nqueens.numAttackingQueens(current) rand2 = random.randint(0, (len(nqueens.getSuccessorStates(current)) - 1)) neigh = nqueens.getSuccessorStates(current)[rand2] neigh.h = nqueens.numAttackingQueens(neigh) T = scheduling(T, decay_rate) E = current.h - neigh.h randNum = random.random() if E > 0: current = neigh else: if math.exp(E / T) > randNum: current = neigh if T < threshold: return current return current
def simulatedAnnealing(startBoard, decayRate, threshHold): current = startBoard T = 100 numLoops = 0 while (T > threshHold): T = schedule(T, decayRate) if (T == 0): return current nextList = nqueens.getSuccessorStates(current) nextNum = random.randint(0, len(nextList)) nextState = nextList[nextNum - 1] h = nqueens.numAttackingQueens(current) - nqueens.numAttackingQueens( nextState) if (h > 0): current = nextState elif (h <= 0 and random.randrange(0, 1) < abs((h / T))): numLoops = numLoops + 1 current = nextState current.printBoard() return h
def simulatedAnnealing(current, thresh, decay): print('') T = 100 loops = 0 #main loop while (T >= thresh): current.h = nq.numAttackingQueens(current) if (current.h == 0): break children = nq.getSuccessorStates(current) child = choice(children) child.h = nq.numAttackingQueens(child) delta_h = current.h - child.h if (delta_h >= 0): current = child else: chance = math.e**(delta_h / T) if random() < chance: current = child ++loops T = schedule(T, decay) print("Result: Final board h-value =", current.h) current.printBoard() return current.h
def Main(): for i in range(2, 5): print("********************\n", "Board Size: ", 2**i, "\n********************\n", "######################################\n", "Decay Rate: 0.9 T Threshold: 0.000001\n", "######################################") b = nqueens.Board(2**i) bhAvg = 0 for j in range(1, 11): print("Run ", j) b.rand() print("Initial Board:") b.printBoard() b.h = nqueens.numAttackingQueens(b) print("Initial h-value: ", b.h) b = simulatedAnnealing(b, 0.9, 0.000001) print("Final Board:") b.printBoard() print("Final h-value: ", b.h, "\n") bhAvg = bhAvg + b.h bhAvg = bhAvg/10 print("********************\n", "Average H-Value: ", bhAvg, "\n********************\n") print("######################################\n", "Decay Rate: 0.75 T Threshold: 0.0000001\n", "######################################") bhAvg = 0 for j in range(1, 11): print("Run ", j) b.rand() print("Initial Board:") b.printBoard() b.h = nqueens.numAttackingQueens(b) print("Initial h-value: ", b.h) b = simulatedAnnealing(b, 0.75, 0.0000001) print("Final Board:") b.printBoard() print("Final h-value: ", b.h, "\n") bhAvg = bhAvg + b.h bhAvg = bhAvg/10 print("********************\n", "Average H-Value: ", bhAvg, "\n********************\n") print("######################################\n", "Decay Rate: 0.5 T Threshold: 0.00000001\n", "######################################") bhAvg = 0 for j in range(1, 11): print("Run ", j) b.rand() print("Initial Board:") b.printBoard() b.h = nqueens.numAttackingQueens(b) print("Initial h-value: ", b.h) b = simulatedAnnealing(b, 0.5, 0.00000001) print("Final Board:") b.printBoard() print("Final h-value: ", b.h, "\n") bhAvg = bhAvg + b.h bhAvg = bhAvg/10 print("********************\n", "Average H-Value: ", bhAvg, "\n********************\n")
def run_sim_annealing(size, rate, threshold): NUM_RUNS = 10 T_INIT = 100 sum_h = 0 for run in range(0, NUM_RUNS): # create a new board, randomize it and calculate its h cost current = Board(size) current.rand() current.h = numAttackingQueens(current) # output the run count and the initial board print(f"Run {run}\nInitial board:") current.printBoard() print(f"h-value: {current.h}") # initialize temperature T = T_INIT # Loop until temperature T reaches or falls beneath the threshold. # Once this occurs the final board, represented by current, has # been found. while T > threshold: # calculate temperature T using linear schedule: T * rate T = f(T, rate) # we've found the solution if current board's h cost is 0 if current.h == 0: break; # set next_b to one of current's successors, chosen at random next_b = get_random_successor(current) next_b.h = numAttackingQueens(next_b) # calculate the h cost difference between current and next_b delta_E = current.h - next_b.h # if h cost difference greater than 0 or probability of move passes # then set current to next_b and continue loop if delta_E > 0: current = next_b elif random.random() < math.exp(delta_E / T): current = next_b # output final board's h cost and the final board print(f"Final board h value: {current.h}") current.printBoard() # add this run's final board h cost to the running sum sum_h += current.h # return the total average h cost: sum of h costs over number of runs return sum_h / NUM_RUNS
def simulatedAnnealing(initBoard, decayRate, T_Threshold): current = initBoard T = 100 while T > T_Threshold: current.h = nqueens.numAttackingQueens(current) T = schFunction(T, decayRate) suState = nqueens.getSuccessorStates(current) for x in suState: if(current.h > nqueens.numAttackingQueens(x)): current = x return current
def main(): board_sizes = [4, 8, 16] thresh_values = [.000001, .0000001, .00000001] decay_rate = [0.9, 0.75, 0.5] for x in board_sizes: print("**********************************") print("Board Size: ", x) print("**********************************") for j in range(len(decay_rate)): print("decayRate: %s ThresHold: %e" % (decay_rate[j], thresh_values[j])) print("######################################") count_h_value = 0 for i in range(10): print('Run', i) print('Initial: ') board = nqueens.Board(x) board.rand() board.printBoard() print("h-value: ", nqueens.numAttackingQueens(board)) answer = simulated_annealing(decay_rate[j], board, thresh_values[j]) print("Final h_value: ", answer.h) answer.printBoard() count_h_value += answer.h print("--------------------------------------") print("Average h value: ", count_h_value / 10) print("--------------------------------------")
def findDeltaE( next_board ): #Armond's method that returns next_board.h - self.current.h currentH = self.current.h nextH = nqueens.numAttackingQueens(next_board) deltaE = nextH - currentH return deltaE
def simulated_annealing(decay_rate, Board, min_threshold_value): T = 100 current = Board current.h = nqueens.numAttackingQueens(current) while True: T = scheduling(T, decay_rate) if (T < min_threshold_value or current.h == 0): return current neighbor_states = nqueens.getSuccessorStates(current) next_state = random.choice(neighbor_states) next_state.h = nqueens.numAttackingQueens(next_state) delta_e = current.h - next_state.h if (delta_e > 0): current = next_state else: rand_number = random.random() if (rand_number < math.e**(delta_e / T)): current = next_state
def simulatedAnnealing(start, decay_rate, threshold): current = start T = 100 while (T > threshold): cost = current.h = nqueens.numAttackingQueens( current) # have to use function to print intial successors = nqueens.getSuccessorStates(current) next_board = successors[random.randint( 0, len(successors) - 1)] # return a random neighbor by selecting a random one cost_next = next_board.h = nqueens.numAttackingQueens( next_board) # get the cost of the random neighbor diff = cost - cost_next if diff > 0: current = next_board elif random.randrange(0, 1) > math.exp((diff / T)): current = next_board # maybe move based on probabilty T = decayRate(decay_rate, T) return current # T < threshold exits and returns the current state
def main(): T = INITIAL_T # temperature variable is set to it's initial value decay_rate = [ .9, .75, .5 ] #test values for decay rate. values #provided by Sterling McLeod threshold = [ 0.000001, 0.0000001, 0.00000001 ] #test values for threshold T must reach to terminate the loop. values #provided by Sterling McLeod board_size = [4, 8, 16] # testor board sizes #provided by instructor time = 0 #todo: do we actualy need this variable? board = None waittime = 0 sum_fin_h_vals = 0 #will hold the sum of all final h values num_iterations = 10 #the number of times each threshold-decay-rate pairing is tested suc_states = None h_vals = [] #temp testor variable holder fin_board = None for x in range(len(board_size)): print("_" * 51, "\n\nFor board size ", board_size[x], "\n_", "_" * 50, "\n") for y in range(len(threshold)): testVals = [threshold[y], decay_rate[y]] #stores this iteration's testing values print("_" * 21, "\n\nThreshold: ", testVals[0], "\nDecay Rate: ", testVals[1], "\n_", "_" * 20, "\n") sum_fin_h_vals = 0 #resets the sum of final h values variable for z in range(num_iterations): if z == 2: print( "Please keep in mind this may take a momment to execute" ) #print("i looped. ", x, ", ", y, ", " , z)#temp: testor #note: this loop has been proven to work the correct number of times print("run #: ", z) T = INITIAL_T # temperature variable is set to it's initial value time = 0 #resets time board = nqueens.Board(board_size[x]) board.rand() board.h = nqueens.numAttackingQueens(board) print("intitial state: ", "\t\t\t\t\t\t\t\tintial h-value: ", board.h) print(board.printBoard()) #print("h-val after printboard ", board.h)#temp testor while (T >= testVals[0] and board.h != 0): suc_states = nqueens.getSuccessorStates(board) #print("suc states", suc_states)#temp testor for i in suc_states: temp_h = nqueens.numAttackingQueens(i) if (temp_h < board.h): board.h = temp_h fin_board = i # h_vals.append(board.h)#temp testing mechanism # print("h-val during suc_states loop ", h_vals)#temp testor # print("h after the sucstates loop", board.h) T = get_ft(T, testVals[1]) #decrements T time += 1 #increments time # print("\t\t T = ", T, "at time ", time, "h val is ", board.h)#temp testor # while(input("************************************please Press enter to continue***************************************************") != "" ): # waittime += 1 sum_fin_h_vals += board.h print("final state: ", "\t\t\t\t\t\t\t\tfinal h-value: ", board.h) print(fin_board.printBoard()) while (input( "**************************please Press enter to continue****************************" ) != ""): waittime += 1 #just a placeholder so the syntax will work avg_time = (sum_fin_h_vals / num_iterations) print( "_" * 21, "\n\nAverage h-value for decay rate", testVals[1], " and threshold ", testVals[0], " is : ", avg_time, "\n_", "_" * 20, "\n\n", "*" * 20 ) #todo: make this display the threshold and decay rate info too while (input( "**********************please Press enter to continue*****************************" ) != ""): waittime += 1 #just a placeholder so the syntax will work print("done") #temp testor
def main(): print('**********************************') print('BOARD SIZE: 4 DECAY RATE 0.9 TRHESHOLD: 0.000001') print('**********************************') hAvg = 0 for x in range(10): print('RUN', x) startingBoard = nqueens.Board(4) startingBoard.rand() startingBoard.printBoard() print('INITIAL h VALUE', nqueens.numAttackingQueens(startingBoard)) print('') hAvg = simulatedAnnealing(startingBoard, 0.9, 0.000001) print('AVERAGE h VALUE: ', hAvg / 10) print('**********************************') print('BOARD SIZE: 8 DECAY RATE 0.9 TRHESHOLD: 0.000001') print('**********************************') hAvg = 0 for x in range(10): print('RUN', x) startingBoard = nqueens.Board(8) startingBoard.rand() startingBoard.printBoard() print('INITIAL h VALUE', nqueens.numAttackingQueens(startingBoard)) print('') hAvg = hAvg + simulatedAnnealing(startingBoard, 0.9, 0.000001) print('AVERAGE h VALUE: ', hAvg / 10) print('**********************************') print('BOARD SIZE: 16 DECAY RATE 0.9 TRHESHOLD: 0.000001') print('**********************************') hAvg = 0 for x in range(10): print('RUN', x) startingBoard = nqueens.Board(16) startingBoard.rand() startingBoard.printBoard() print('INITIAL h VALUE', nqueens.numAttackingQueens(startingBoard)) print('') hAvg = hAvg + simulatedAnnealing(startingBoard, 0.9, 0.000001) print('') print('AVERAGE h VALUE: ', hAvg / 10) print('**********************************') print('BOARD SIZE: 4 DECAY RATE 0.75 TRHESHOLD: 0.0000001') print('**********************************') hAvg = 0 for x in range(10): print('RUN', x) startingBoard = nqueens.Board(4) startingBoard.rand() startingBoard.printBoard() print('INITIAL h VALUE', nqueens.numAttackingQueens(startingBoard)) print('') hAvg = hAvg + simulatedAnnealing(startingBoard, 0.75, 0.0000001) print('AVERAGE h VALUE: ', hAvg / 10) #FINISH THE h VAL PRINTING print('**********************************') print('BOARD SIZE: 8 DECAY RATE 0.75 TRHESHOLD: 0.0000001') print('**********************************') hAvg = 0 for x in range(10): print('RUN', x) startingBoard = nqueens.Board(8) startingBoard.rand() startingBoard.printBoard() print('INITIAL h VALUE', nqueens.numAttackingQueens(startingBoard)) print('') hAvg = hAvg + simulatedAnnealing(startingBoard, 0.75, 0.0000001) print('AVERAGE h VALUE: ', hAvg / 10) print('**********************************') print('BOARD SIZE: 16 DECAY RATE 0.75 TRHESHOLD: 0.0000001') print('**********************************') hAvg = 0 for x in range(10): print('RUN', x) startingBoard = nqueens.Board(16) startingBoard.rand() startingBoard.printBoard() print('INITIAL h VALUE', nqueens.numAttackingQueens(startingBoard)) print('') hAvg = hAvg + simulatedAnnealing(startingBoard, 0.75, 0.0000001) print('AVERAGE h VALUE: ', hAvg / 10) print('**********************************') print('BOARD SIZE: 4 DECAY RATE 0.5 TRHESHOLD: 0.00000001') print('**********************************') hAvg = 0 for x in range(10): print('RUN', x) startingBoard = nqueens.Board(4) startingBoard.rand() startingBoard.printBoard() print('INITIAL h VALUE', nqueens.numAttackingQueens(startingBoard)) print('') hAvg = hAvg + simulatedAnnealing(startingBoard, 0.5, 0.00000001) print('AVERAGE h VALUE: ', hAvg / 10) print('**********************************') print('BOARD SIZE: 8 DECAY RATE 0.75 TRHESHOLD: 0.0000001') print('**********************************') hAvg = 0 for x in range(10): print('RUN', x) startingBoard = nqueens.Board(8) startingBoard.rand() startingBoard.printBoard() print('INITIAL h VALUE', nqueens.numAttackingQueens(startingBoard)) print('') hAvg = hAvg + simulatedAnnealing(startingBoard, 0.5, 0.00000001) print('AVERAGE h VALUE: ', hAvg / 10) print('**********************************') print('BOARD SIZE: 16 DECAY RATE 0.75 TRHESHOLD: 0.0000001') print('**********************************') hAvg = 0 for x in range(10): print('RUN', x) startingBoard = nqueens.Board(16) startingBoard.rand() startingBoard.printBoard() print('INITIAL h VALUE', nqueens.numAttackingQueens(startingBoard)) print('') hAvg = hAvg + simulatedAnnealing(startingBoard, 0.5, 0.00000001) print('AVERAGE h VALUE: ', hAvg / 10)
def print_initial_h(current): current.h = nq.numAttackingQueens(current) print("h-value =", current.h)