Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.30 KB | None | 0 0
  1. import random
  2. import math
  3.  
  4. class Board():
  5.  
  6.     def __init__(self, numRowsCols):
  7.         self.cells = [[0] * numRowsCols for i in range(numRowsCols)]
  8.         self.numRows = numRowsCols
  9.         self.numCols = numRowsCols
  10.  
  11.         # negative value for initial h...easy to check if it's been set or not
  12.         self.h = -1
  13.  
  14.     # Print board
  15.     def printBoard(self):
  16.         for row in self.cells:
  17.             print(row)
  18.  
  19.     # Randomize the board
  20.     def rand(self):
  21.         for row in self.cells:
  22.             i = random.randint(0, self.numCols - 1)
  23.             row[i] = 1
  24.  
  25.     # Swap two locations on the board
  26.     def swapLocs(self, a, b):
  27.         temp = self.cells[a[0]][a[1]]
  28.         self.cells[a[0]][a[1]] = self.cells[b[0]][b[1]]
  29.         self.cells[b[0]][b[1]] = temp
  30.  
  31.  
  32. # Cost function for a board
  33. def numAttackingQueens(board):
  34.     # Collect locations of all queens
  35.     locs = []
  36.     for r in range(len(board.cells)):
  37.         for c in range(len(board.cells[r])):
  38.             if board.cells[r][c] == 1:
  39.                 locs.append([r, c])
  40.     # print 'Queen locations: %s' % locs
  41.  
  42.     result = 0
  43.  
  44.     # For each queen (use the location for ease)
  45.     for q in locs:
  46.  
  47.         # Get the list of the other queen locations
  48.         others = [x for x in locs if x != q]
  49.         # print 'q: %s others: %s' % (q, others)
  50.  
  51.         count = 0
  52.         # For each other queen
  53.         for o in others:
  54.             # print 'o: %s' % o
  55.             diff = [o[0] - q[0], o[1] - q[1]]
  56.  
  57.             # Check if queens are attacking
  58.             if o[0] == q[0] or o[1] == q[1] or abs(diff[0]) == abs(diff[1]):
  59.                 count = count + 1
  60.  
  61.         # Add the amount for this queen
  62.         result = result + count
  63.  
  64.     return result
  65.  
  66.  
  67. # Move any queen to another square in the same column
  68. # successors all the same                                                                                                                
  69. def getSuccessorStates(board):
  70.     result = []
  71.  
  72.     for i_row, row in enumerate(board.cells):
  73.         # Get the column the queen is on in this row
  74.         i_queen = [i for i, x in enumerate(row) if x == 1][0]
  75.  
  76.         # For each column in the row
  77.         for i_col in range(board.numCols):
  78.  
  79.             # If the queen is not there
  80.             if row[i_col] != 1:
  81.                 # Make a copy of the board
  82.                 bTemp = Board(board.numRows)
  83.                 bTemp.cells[:] = [r[:] for r in board.cells]
  84.  
  85.                 # Now swap queen to i_col from i_queen
  86.                 bTemp.swapLocs([i_row, i_col], [i_row, i_queen])
  87.                 # bTemp.printBoard()
  88.                 result.append(bTemp)
  89.  
  90.     return result
  91.  
  92.  
  93. def schedule(t_value, decay_rate):
  94.     return t_value * decay_rate
  95.  
  96.  
  97. def simulated_annealing (problem, schedule):
  98.     # current_node = problem
  99.  
  100. # def localSearch(board, decay_rate, threashold):
  101. #     Tempurature = 100
  102.    
  103. #     board.rand()
  104. #     current = board
  105. #     h = numAttackingQueens(current)
  106.    
  107. #     print('Initial state: ')
  108. #     current.printBoard()
  109. #     print('h-value: ' + str(h) + '\n')
  110.        
  111. #     while Tempurature > threashold :
  112. #         if h == 0 :
  113. #             break
  114. #         successor_list = getSuccessorStates(board)
  115. #         successor_state = successor_list[random.randint(0, len(successor_list) - 1)]
  116.            
  117. #         if numAttackingQueens(current) > numAttackingQueens(successor_state) :
  118. #             current = successor_state
  119. #         else :
  120. #             if (probability(current, successor_state, Tempurature) > random.random()):
  121. #                 current = successor_state
  122.            
  123. #         h = numAttackingQueens(current)            
  124. #         Tempurature = schedule(Tempurature, decay_rate)
  125.        
  126. #     print('Final state: ')
  127. #     current.printBoard()
  128. #     print('h-value = ' + str(h))
  129.    
  130. #     return current
  131.  
  132. def simulated_annealing_2 (board, t_start_val, threshhold, decay_rate):
  133.   best_board = board
  134.   best_val = numAttackingQueens(board)
  135.   tval = t_start_val
  136.  
  137.  
  138.   while (tval > threshold):
  139.     nextStates = getSuccessorStates()
  140.     next_possible = random.choice(nextStates)
  141.     next_possible_val = numAttackingQueens(next_possible)
  142.  
  143.     if  next_possible_val > best_val:
  144.       best_board = next_possible
  145.       best_val = numAttackingQueens(next_possible)
  146.     elif next_possible_val < bestVal:
  147.       probability = math.e**((best_val - next_possible_val) / tval)
  148.  
  149.       # continue from here, do something with the probability var
  150.  
  151.     tval = tval * decay_rate
  152.  
  153.  
  154.  
  155. def main():
  156.     print('Starting main function for Simulated Annealing program')
  157.  
  158.     board_size = 4
  159.     T = 100
  160.     decay_rates = [0.9, 0.75, 0.5]
  161.     thresholds = [0.000001, 0.0000001, 0.00000001]
  162.     pair_1 = schedule(thresholds[0], decay_rates[0])
  163.     pair_2 = schedule(thresholds[1], decay_rates[1])
  164.     pair_3 = schedule(thresholds[2], decay_rates[2])
  165.  
  166.     for i in range(3):
  167.         board = Board(board_size)
  168.         board_size *= 2
  169.         for j in range(10):
  170.             board.rand()
  171.             board.printBoard()
  172.             print(" ")
  173.             simulated_annealing(board, pair_1)
  174.             simulated_annealing(board, pair_2)
  175.             simulated_annealing(board, pair_3)
  176.  
  177.     print('Printing Board:')
  178.  
  179. if __name__ == '__main__':
  180.     main()
  181.     print('\nExiting normally')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement