def simulatedAnnealing(maxTry, chessBoard): # Initialization mTry = iterator = maxTry # Copy initiate board and count the value bestResult = copy.deepcopy(chessBoard) ts0, td0, qs0, qd0, rs0, rd0, bs0, bd0, ks0, kd0 = Checker.conflictChecker(bestResult) Value = ts0 - td0 # Improved and accepted states counter improved = accepted = 0 # Outer loop, which randomizes state until a number of steps while iterator > 0 : # Function that set the temperature T = math.log(mTry - iterator + 1, math.exp(1)) # Generate a random state tempBoard = copy.deepcopy(bestResult) tempList = BoardHandler.createPiecesListWithPos(tempBoard) randPiece = tempList[randint(0, len(tempList)-1)] # Randomizes a piece's position randRow = randint(0, 7) randCol = randint(0, 7) while tempBoard[randRow][randCol] != ('.', "."): randRow = randint(0, 7) randCol = randint(0, 7) tempBoard[randPiece[3]][randPiece[2]] = ('.', ".") tempBoard[randRow][randCol] = (randPiece[0], randPiece[1]) # Count the randomized board value ts1, td1, qs1, qd1, rs1, rd1, bs1, bd1, ks1, kd1 = Checker.conflictChecker(tempBoard) tempValue = ts1 - td1 # If the next state value is better, accept it if tempValue <= Value : bestResult = copy.deepcopy(tempBoard) Value = tempValue improved += 1 # If the next state value is worse, accept with probability of it is higher than a random number elif tempValue > Value : sigmoidFunc = math.floor(math.exp(-T)) * 100 randomNum = randint(0, 100) if sigmoidFunc > randomNum: bestResult = copy.deepcopy(tempBoard) Value = tempValue accepted += 1 # Iterator value decreased iterator -= 1 # Result of improved states print(improved) # Result of accepted states print(accepted) Printer.printSolutionToFile(bestResult, "SimulatedAnnealing") return bestResult
def GeneticAlgorithm(chessList): #the process of genetic algorithm population = initialize_population(chessList) # for chromosome in population : # print(chromosome.fitness) i = 1 while (population[0].fitness != 0): print("Generation :", i) populationSort(population) deleteLeastFit(population) # for chromosome in population : # print(chromosome.fitness) # print("===============") # print("PieceList") # print(chromosome.piecesLocation) # print("Crossover") # print("===============") index = 0 while index < maxPopulation / 2: parent1, parent2 = getParents(population, index) if not (samePosition(parent1, parent2)): crossOver(population, parent1, parent2) index = index + 2 # index = 0 # parent1 , parent2 = getParents(population, index) # crossOver(population, parent1, parent2) populationSort(population) print("Fittest : ", population[0].fitness) # for chromosome in population : # print(chromosome.fitness) # for chromosome in population : # Printer.printChessBoard(chromosome.board) # # populationSort(population) i = i + 1 print(population[0].piecesLocation) # BoardHandler.updateBoard(population[0].board, population[0].piecesLocation) Printer.printChessBoard(population[0].board)
def initialize_population(chessList): #initialize the population population = [] for i in range(100): chromosome = Chromosome() chromosome.board = [] chromosome.piecesLocation = BoardHandler.random_genetic( chromosome.board, chessList) chromosome.fitness = Checker.conflictChecker(chromosome.board)[0] population.append(chromosome) Printer.printChessBoard(population[0].board) print(population[0].piecesLocation) print(population[0].fitness) return population
def hillC(maxTry, chessboard): # Generate initial state currentState = copy.deepcopy(chessboard) # Iterate Try times for i in range(maxTry): print(i) bestNeighbour = copy.deepcopy(getBestNeighbour(currentState)) # Compare current state with best neighbour, if current state is better return current state, if evaluate(bestNeighbour, currentState) > 0: Printer.printChessBoard(currentState) Printer.printSolutionToFile(currentState, "HillClimbing") return currentState Printer.printChessBoard(currentState) # else assign current state with best neighbour currentState = copy.deepcopy(bestNeighbour) # Return current state if function HC cannot find maximum until try times Printer.printChessBoard(currentState) Printer.printSolutionToFile(currentState, "HillClimbing") return currentState
def GeneticAlgorithm(chessList): # the process of genetic algorithm population = initialize_population(chessList) generationCount = 1 count = 1 maxFitness = 0 while generationCount <= maxGeneration: newGeneration = [] index = 0 while index < (maxPopulation / 2 - 1): parent1, parent2 = getParents(population, index) crossOver(newGeneration, parent1, parent2) index = index + 1 population = newGeneration + population # add new generation to current population populationSort(population) deleteLeastFit(population) print("Generation :" + str(generationCount) + ", Fittest : ", abs(population[0].fitness)) if population[0].fitness != maxFitness: maxFitness = population[0].fitness count = 1 else: count += 1 if count == 100: # if in 100 gen there is no change in fittest score print("Same fitness for " + str(count) + " gen") print("Terminate") time.sleep(1) break else: generationCount = generationCount + 1 # print (population[0].piecesLocation) if generationCount == maxGeneration: print("Max iteration reach") time.sleep(1) Printer.printChessBoard(population[0].board) Printer.printSolutionToFile(population[0].board, "Genetic")
def mainMenu(): chessBoard = [] while True: if os.name == 'nt': # Windows os.system('cls') elif os.name == 'posix': # Linux os.system('clear') print(colorize(header, 'pink')) i = 1 for item in menuItems: print("[" + str(i) + "] " + colorize(item, 'blue')) i += 1 choice = int(input(">> ")) try: if choice < 1: raise ValueError # Call the matching function if choice == 1: Printer.printDir("Inputs/") chessBoard = BoardHandler.createChessboard() elif choice == 2: Printer.printDir("Inputs/") chessBoard = BoardHandler.readChessboard() elif choice == 3: Printer.printChessBoard(chessBoard) elif choice == 7: credit() elif choice == 8: exit(0) else: print(">> That is not a valid input.") except (ValueError, IndexError): pass while True: text = input("\n>> Press enter to continue.") if text == "": break else: print("\n>> You did not press enter.") print("\n\n")
def mainMenu(): chessBoard = [] # Clear screen while True: if os.name == 'nt': # Windows os.system('cls') elif os.name == 'posix': # Linux os.system('clear') # Print header & menu options print(colorize(header, 'pink')) i = 1 for item in menuItems: print("[" + str(i) + "] " + colorize(item, 'blue')) i += 1 choice = int(input(">> ")) try: if choice < 1: raise ValueError # Call the matching function if choice == 1: Printer.printDir("Inputs/") chessBoard = BoardHandler.createChessboard() elif choice == 2: Printer.printDir("Inputs/") chessBoard = BoardHandler.readChessboard() elif choice == 3: Printer.printChessBoard(chessBoard) elif choice == 4: maxTry = int(input(">> Enter maximum try : ")) Printer.printChessBoard(hc.hillC(maxTry, chessBoard)) elif choice == 5: maxTry = int(input(">> Enter maximum try : ")) Printer.printChessBoard( SimulatedAnnealing.simulatedAnnealing(maxTry, chessBoard)) elif choice == 6: Genetic.GeneticAlgorithm( BoardHandler.createPiecesList(chessBoard)) elif choice == 7: helpMe() elif choice == 8: credit() elif choice == 9: exit(0) else: print(">> That is not a valid input.") except (ValueError, IndexError): pass # Users need to press enter to continue using program (refresh the display) while True: text = input("\n>> Press enter to continue.") if text == "": break else: print("\n>> You did not press enter.") print("\n\n")