def main(): number_of_variables = 3 leader_size = 50 gene_length = number_of_variables * leader_size prob = ZDT1(number_of_variables=number_of_variables) hv = HyperVolume(reference_point=[r_point] * prob.number_of_objectives) ranker = FastNonDominatedRanking() def objective(x, verbose=False): pareto_front = [] k = 10e3 c = 0 for ix in range(0, gene_length, number_of_variables): solution = prob.evaluate(x[ix:ix + number_of_variables]) pareto_front.append(solution) if not solution.objectives[ 0] <= r_point or not solution.objectives[1] <= r_point: c += 1 d = count_dominated_solutions(pareto_front) ind = -hv.compute(pareto_front) if verbose == True: print("{} {} {}".format(ind, d, c)) return ind + k * (c**2 + d**2) ga = GeneticAlgorithm(objective, 1000, gene_length, leader_size, prob.lower_bound[0], prob.upper_bound[0], 0.25, 0.01, 0.1, 100) ga.evolve() objective(ga.best_individual, True) plot(ga.best_individual, prob)
def __init__(self, numCars): self.numCars = numCars self.cars = [] self.walls = ((1256, 269), (1157, 267), (1050, 187), (862, 164), (744, 352), (614, 338), (495, 169), (318, 164), (223, 366), (12, 356), (10, 451), (291, 465), (404, 267), (566, 465), (817, 472), (942, 272), (1037, 294), (1124, 375), (1262, 380), (1256, 269)) #self.cookies are the lines in purple, the word cookies comes from giving cookies to dogs as rewards when they behavior good (we assume that cars can eat cookies in some way xD) self.cookies = (((1159, 268), (1149, 373)), ((1144, 256), (1103, 358)), ((1077, 330), (1120, 239)), ((1094, 218), (1047, 303)), ((1025, 292), (1058, 192)), ((1015, 181), (998, 285)), ((964, 278), (970, 178)), ((943, 272), (906, 170)), ((857, 171), (931, 288)), ((915, 316), (829, 216)), ((806, 250), (890, 353)), ((874, 381), (784, 286)), ((766, 318), (852, 411)), ((834, 443), (751, 340)), ((806, 472), (743, 352)), ((753, 469), (719, 351)), ((701, 467), (697, 348)), ((660, 343), (664, 466)), ((631, 340), (619, 465)), ((572, 465), (612, 335)), ((537, 429), (593, 311)), ((575, 281), (501, 386)), ((469, 350), (556, 253)), ((533, 223), (444, 316)), ((426, 298), (505, 186)), ((471, 169), (413, 278)), ((420, 168), (406, 270)), ((401, 271), (364, 167)), ((398, 277), (313, 175)), ((391, 290), (293, 216)), ((277, 254), (373, 321)), ((360, 343), (262, 283)), ((248, 314), (343, 372)), ((326, 402), (234, 339)), ((306, 439), (227, 359)), ((291, 465), (223, 365)), ((243, 462), (211, 365)), ((196, 461), (197, 364)), ((159, 459), (167, 365)), ((133, 360), (130, 457)), ((97, 456), (104, 359)), ((73, 359), (69, 453)), ((43, 449), (48, 359)), ((30, 356), (27, 452))) self.time = 0 self.maxTime = 800 self.deadCars = 0 self.carPos = (1180, 320) for i in range(0, numCars): self.cars.append(Car(self.carPos[0], self.carPos[1])) numWeights = self.cars[0].neuralNet.getNumberWeights() self.geneticAlgorithm = GeneticAlgorithm(numCars, numWeights) for i in range(0, numCars): self.cars[i].neuralNet.putWeights(self.geneticAlgorithm.population[i].genes) self.textSize = 32 self.textsToDraw = []
def main(): np.random.seed(7890) # recebendo instâncias r = ReadingDatas("dat/p01") r.readFile() # adicionando clientes Customers.addCustomers(r) # for cst in Customers.get_customersList().values(): # print(cst) # adicionando depósitos Depots.addDepots(r) # print("\n\n\n\") # for dpt in Depots.get_depotsList().values(): # print(dpt) # cálculo das distâncias Distances.euclidianDistanceAll(Customers.get_customersList(), Depots.get_depotsList()) # for cst in Customers.get_customersList(): # print(cst) # print(Customers.get_customersList()[cst].get_depotsDistances()) # print("\n\n\n") # for cst in Customers.get_customersList(): # print(cst) # print(Customers.get_customersList()[cst].get_neighborsDistances()) ga = GA() ga.GA()
def test_generateBasePopulation(self): area = Area('draw', numberOfBlocks) ga = GeneticAlgorithm(area, populationSize, mutationPercent, successionRate, diversityRate, time, solution, secondStage, progress) basePopulation = ga.createBasePopulation() self.assertEqual(basePopulation.shape, (ga.populationSize, ga.area.numberOfBlocks + 1)) self.assertEqual(sum(basePopulation[-1, :-1]), sum(basePopulation[0, :-1])) self.assertEqual(sum(basePopulation[0, :-1]), sum(range(0, ga.area.numberOfBlocks))) self.assertEqual( sum(np.sum(basePopulation[:, :-1], axis=1)), sum(range(0, ga.area.numberOfBlocks)) * ga.populationSize)
def main(SEED, POP, DESC, PROB_MUT, PROB_LS_POP, PROB_LS, PROB_LSB, PROB_LSBP, GEN_ILS, GEN_ILSA, DATFILE, INSTANCE): # redefinindo variáveis conforme Package Irace # config.FRAC_MAX_DISTRIBUTION = FRAC config.SIZE_POP = POP config.SIZE_DESC = DESC config.PROB_MUTATION = PROB_MUT config.PROB_LS_POP = PROB_LS_POP config.PROB_LS = PROB_LS config.PROB_LS_BEST = PROB_LSB config.PROB_LS_BEST_P = PROB_LSBP config.GEN_ILS = GEN_ILS config.GEN_ILSA = GEN_ILSA seed = SEED timeIni = time.time() # exit(0) # recebendo instâncias r = ReadingDatas(INSTANCE) r.readFile() # adicionando clientes Customers.addCustomers(r) # adicionando depósitos Depots.addDepots(r) # cálculo das distâncias Distances.euclidianDistanceAll(Customers.get_customersList(), Depots.get_depotsList()) ga = GA() best = ga.GA(seed) cost = best.get_cost() timeEnd = (time.time() - timeIni) / 60.0 logging.debug("Melhor indivíduo: %s" % best) logging.debug("tempo total: " + str(timeEnd) + " minutos.") logging.debug("------------fim algoritmo genético-----------") with open(DATFILE, 'w') as f: f.write(str(cost))
def runTournamentSizeTests(): size = 1000 selectors = [ TournamentSelector(150), TournamentSelector(350), TournamentSelector(500) ] crossoverThreshold = 0.2 mutationProbability = 0.1 # internal params crossoverProbability = 0.2 mutationStrength = 1 calculator = createDefaultLossCalculator() subDirectory = 'tournamentSize' os.makedirs(os.path.join(path, subDirectory), exist_ok=True) file = open(os.path.join(path, subDirectory, 'results.txt'), 'w+') board = loadFromFile('textTests/zad1.txt') file.write(f'Parametry testow:\n' f'Rozmiar populacji: {size}\n' f'Prawdopodobienstwo krzyzowania: {(1 - crossoverThreshold)}\n' f'Prawdopodobienstwo mutacji: {(1 - mutationProbability)}\n\n' f'Wyniki testow:\nParametr:\tBest:\tWorst:\tAvg:\tStdDev:\n') for selector in selectors: bestSolutionLosses = [] worstSolutionLosses = [] file.write(f'{selector}\t') pool = ProcessPoolExecutor(max_workers=10) futures = [] for i in range(10): futures.append( pool.submit( immediatelyCall, GeneticAlgorithm(board, size, calculator, selector, crossoverThreshold, crossoverProbability, mutationProbability, mutationStrength))) result = wait(futures, return_when=ALL_COMPLETED) for index, value in enumerate(result[0]): (best, worst, _, image) = value.result() bestSolutionLosses.append(best) worstSolutionLosses.append(worst) image.save( os.path.join(path, subDirectory, f'{selector}-test-{index}.png')) image.close() best = min(bestSolutionLosses) worst = max(worstSolutionLosses) avg = statistics.mean(bestSolutionLosses) stdDev = statistics.stdev(bestSolutionLosses) file.write(f'{best}\t{worst}\t{avg}\t{stdDev}\n') file.close()
def tryGA(): board = loadFromFile('textTests/zad1.5.txt') populationSize = 1000 selector = TournamentSelector(150) crossoverThreshold = 0.2 crossoverProbability = 0.2 mutationProbability = 0.1 mutationStrength = 1 maximumLoss = 25 lossWeights = LossWeights() lossWeights.intersectionCount = 20 lossWeights.outOfBoardPathCount = 30 lossWeights.outOfBoardLength = 40 lossWeights.totalPathLength = 0.5 lossWeights.segmentsCount = 0.5 calculator = LossCalculator(lossWeights) alg = GeneticAlgorithm(board, populationSize, calculator, selector, crossoverThreshold, crossoverProbability, mutationProbability, mutationStrength, maximumLoss) res = alg.algorithm() print(res)
percentError = abs(( numberWeAreLookingFor - chromosomeMathValue ) / numberWeAreLookingFor) except: return None return percentError #We should introduce a maximum fitness score. A score of zero indicates target number hit. numberWeAreLookingFor = int(raw_input('Enter a number to look for:')) tolerableError = 0.5 chromosomeSize = 400 populationSize = 1000 epochs = 250 simple_eval.POWER_MAX = 5000 geneticAlgorithm = GeneticAlgorithm(fitnessScore) geneticAlgorithm.setPopulationSize(populationSize) geneticAlgorithm.setNumberOfEpochs(epochs) geneticAlgorithm.setChromosomeSize(chromosomeSize) geneticAlgorithm.setChromsomeToHumanReadableFunction(chromosomeToMathExpression) geneticAlgorithm.setGeneSize(4) #mutationRate = 0.02 #geneticAlgorithm.setMutationRate(mutationRate) geneticAlgorithm.run() print('we were looking for ') print(numberWeAreLookingFor)
from geneticAlgorithm import GeneticAlgorithm n = 4 #Number of chromosomus steps = 100 #Needed number of steps p_crossing = .7 #Crossing posibility p_mutation = .1 #Mutation posibility search_val = 9996680000000 #Searching number gen_alg = GeneticAlgorithm(n, steps, p_crossing, p_mutation, search_val) gen_alg.run()
print(args) # Set arguments to variables filename = args.filename crossover_prob = args.crossover_prob mutation_prob = args.mutation_prob popSize = args.population_size generation = args.generation # Dataset read and parsing knapsack = Knapsack(filename) knapsack.reader() gene_size = len(knapsack.dataset) # Generate each GA instance roulette = GeneticAlgorithm(gene_size, popSize, crossover_prob, mutation_prob) tournament = GeneticAlgorithm(gene_size, popSize, crossover_prob, mutation_prob) # Roulette Wheel selection GA Initialization print('Roulette', end=' ') roulette.initialization() roulette.calculateFitness(knapsack) # Tournament selection GA Initialization print('Tournament', end=' ') tournament.initialization() tournament.calculateFitness(knapsack) # Training for i in range(generation): roulette.rouletteWheelSelection()
def geneticEvolution(self): self.genetic = GeneticAlgorithm(self.Birds) self.geneticCycles += 1 self.Birds = self.genetic.runGeneticAlgorithm()
def __init__(self): # Control Writing self.doIWrtie = 0 #Set Screen self.WIDTH = 288 * 2 self.HEIGHT = 512 self.SCORES = 288 #Dim Score Window self.interlineSCORES = 30 #Interline between Scores self.baseWidth = 336 #Width Ground self.baseHeight = 112 #Height Ground #Set Time self.clockSpeed = 250 #Set Pipes self.pipeWidth = 52 self.pipeHeight = 320 self.pipeSpeed = 5 self.spaceBetweenPipesMin = 150 self.spaceBetweenPipesMax = 200 self.distanceBetweenPipesMin = self.WIDTH / 2 self.distanceBetweenPipesMax = (3 / 4) * self.WIDTH self.distanceBetweenPipes = 0 self.DistanceBetweenPipesValue = self.WIDTH / 2 - self.pipeWidth / 2 '''self.spaceBetweenPipes0 = random.randint(self.spaceBetweenPipesMin, self.spaceBetweenPipesMax) self.spaceBetweenPipesHeight0 = random.randint(self.pipeHeight - self.spaceBetweenPipesMax / 2, self.pipeHeight + self.spaceBetweenPipesMin / 2)''' self.spaceBetweenPipes0 = 250 self.spaceBetweenPipesHeight0 = 300 self.spaceBetweenPipes1 = random.randint( int(self.spaceBetweenPipesMin), int(self.spaceBetweenPipesMax)) self.spaceBetweenPipesHeight1 = random.randint( int(self.pipeHeight - self.spaceBetweenPipesMax / 2), int(self.pipeHeight + self.spaceBetweenPipesMin / 2)) #Initialization Variables for Pipes self.pipeX0 = self.WIDTH / 2 - self.pipeWidth / 2 self.pipeX1 = self.WIDTH self.pipeClosest = self.pipeX0 self.nextSpaceBetweenPipes = self.spaceBetweenPipes0 #Initialization Variables for Scores self.flagPipePassed = 0 self.flagScoresIncremented = 0 self.maxScore = 0 self.maxFinalScore = 400 #Set GUI Screen self.screen = pygame.display.set_mode( (self.WIDTH + self.SCORES, self.HEIGHT + self.baseHeight)) self.background = pygame.image.load("img/backgroundDay.png").convert() self.base = pygame.image.load("img/base.png").convert() self.gameOver = pygame.image.load("img/gameover.png").convert() self.topPipe = pygame.image.load( "img/greenPipeTop.png").convert_alpha() self.downPipe = pygame.image.load( "img/greenPipeDown.png").convert_alpha() self.backgroundScores = pygame.image.load( "img/whiteRect.png").convert() #Create Flock self.numberOfBirds = 2 self.Birds = [] for i in range(1, self.numberOfBirds + 1): self.Birds.append(Bird()) #Indexing of birds _j = 1 for bird in self.Birds: bird.iD = _j _j += 1 #Vector of alive birds self.birdsAlive = [bird for bird in self.Birds if bird.dead == 0] self.genetic = GeneticAlgorithm(self.Birds) self.geneticCycles = 0 '''self.NeuralNetworks = []
class FlappyBird: def __init__(self): # Control Writing self.doIWrtie = 0 #Set Screen self.WIDTH = 288 * 2 self.HEIGHT = 512 self.SCORES = 288 #Dim Score Window self.interlineSCORES = 30 #Interline between Scores self.baseWidth = 336 #Width Ground self.baseHeight = 112 #Height Ground #Set Time self.clockSpeed = 250 #Set Pipes self.pipeWidth = 52 self.pipeHeight = 320 self.pipeSpeed = 5 self.spaceBetweenPipesMin = 150 self.spaceBetweenPipesMax = 200 self.distanceBetweenPipesMin = self.WIDTH / 2 self.distanceBetweenPipesMax = (3 / 4) * self.WIDTH self.distanceBetweenPipes = 0 self.DistanceBetweenPipesValue = self.WIDTH / 2 - self.pipeWidth / 2 '''self.spaceBetweenPipes0 = random.randint(self.spaceBetweenPipesMin, self.spaceBetweenPipesMax) self.spaceBetweenPipesHeight0 = random.randint(self.pipeHeight - self.spaceBetweenPipesMax / 2, self.pipeHeight + self.spaceBetweenPipesMin / 2)''' self.spaceBetweenPipes0 = 250 self.spaceBetweenPipesHeight0 = 300 self.spaceBetweenPipes1 = random.randint( int(self.spaceBetweenPipesMin), int(self.spaceBetweenPipesMax)) self.spaceBetweenPipesHeight1 = random.randint( int(self.pipeHeight - self.spaceBetweenPipesMax / 2), int(self.pipeHeight + self.spaceBetweenPipesMin / 2)) #Initialization Variables for Pipes self.pipeX0 = self.WIDTH / 2 - self.pipeWidth / 2 self.pipeX1 = self.WIDTH self.pipeClosest = self.pipeX0 self.nextSpaceBetweenPipes = self.spaceBetweenPipes0 #Initialization Variables for Scores self.flagPipePassed = 0 self.flagScoresIncremented = 0 self.maxScore = 0 self.maxFinalScore = 400 #Set GUI Screen self.screen = pygame.display.set_mode( (self.WIDTH + self.SCORES, self.HEIGHT + self.baseHeight)) self.background = pygame.image.load("img/backgroundDay.png").convert() self.base = pygame.image.load("img/base.png").convert() self.gameOver = pygame.image.load("img/gameover.png").convert() self.topPipe = pygame.image.load( "img/greenPipeTop.png").convert_alpha() self.downPipe = pygame.image.load( "img/greenPipeDown.png").convert_alpha() self.backgroundScores = pygame.image.load( "img/whiteRect.png").convert() #Create Flock self.numberOfBirds = 2 self.Birds = [] for i in range(1, self.numberOfBirds + 1): self.Birds.append(Bird()) #Indexing of birds _j = 1 for bird in self.Birds: bird.iD = _j _j += 1 #Vector of alive birds self.birdsAlive = [bird for bird in self.Birds if bird.dead == 0] self.genetic = GeneticAlgorithm(self.Birds) self.geneticCycles = 0 '''self.NeuralNetworks = [] for i in range(1, 11): self.NeuralNetworks.append(NeuralNetwork())''' # --- updatePipes --- def updatePipes(self): self.pipeX0 -= self.pipeSpeed self.pipeX1 -= self.pipeSpeed if self.pipeX0 < -self.pipeWidth: #self.distanceBetweenPipes=450 self.distanceBetweenPipes = random.randint( int(self.distanceBetweenPipesMin), int(self.distanceBetweenPipesMax)) self.spaceBetweenPipesHeight0 = random.randint( int(self.pipeHeight - self.spaceBetweenPipesMax / 2), int(self.pipeHeight + self.spaceBetweenPipesMin / 2)) self.spaceBetweenPipes0 = random.randint( int(self.spaceBetweenPipesMin), int(self.spaceBetweenPipesMax)) self.pipeX0 = self.pipeX1 + self.distanceBetweenPipes self.flagPipePassed = 0 for Bird in self.Birds: Bird.flagUpdateScore = 0 if self.pipeX1 < -self.pipeWidth: #self.distanceBetweenPipes=450 self.distanceBetweenPipes = random.randint( int(self.distanceBetweenPipesMin), int(self.distanceBetweenPipesMax)) self.spaceBetweenPipesHeight1 = random.randint( int(self.pipeHeight - self.spaceBetweenPipesMax / 2), int(self.pipeHeight + self.spaceBetweenPipesMin / 2)) self.spaceBetweenPipes1 = random.randint( int(self.spaceBetweenPipesMin), int(self.spaceBetweenPipesMax)) self.pipeX1 = self.pipeX0 + self.distanceBetweenPipes self.flagPipePassed = 0 for Bird in self.Birds: Bird.flagUpdateScore = 0 def nextPipeX(self): if ((self.pipeX0 >= 67 - (self.pipeWidth / 2)) and (self.pipeX0 < self.pipeX1 or self.pipeX1 <= 67 - (self.pipeWidth / 2))): #67=birdX+birdWidth/2 return self.pipeX0 else: return self.pipeX1 def nextPipeY(self): if ((self.pipeX0 >= 67 - (self.pipeWidth / 2)) and (self.pipeX0 < self.pipeX1 or self.pipeX1 <= 67 - (self.pipeWidth / 2))): return self.spaceBetweenPipesHeight0 else: return self.spaceBetweenPipesHeight1 def birdsPositions(self): #distance from the bird's center for Bird in self.Birds: if Bird.dead == 0: Bird.birdPositionX = (self.nextPipeX() + self.pipeWidth / 2) - (Bird.birdX + Bird.birdWidth / 2) Bird.birdPositionY = self.nextPipeY() - (Bird.birdY + Bird.birdHeight / 2) def getNextSpaceBetweenPipes(self): if ((self.pipeX0 >= 67 - (self.pipeWidth / 2)) and (self.pipeX0 < self.pipeX1 or self.pipeX1 <= 67 - (self.pipeWidth / 2))): return self.spaceBetweenPipes0 else: return self.spaceBetweenPipes1 def getDistanceBetweenPipes(self): if (self.pipeX0 <= 67 - self.pipeWidth / 2): self.DistanceBetweenPipesValue = self.pipeX1 - self.pipeX0 if (self.pipeX1 <= 67 - self.pipeWidth / 2): self.DistanceBetweenPipesValue = self.pipeX0 - self.pipeX1 return self.DistanceBetweenPipesValue # --- updateGame --- def updateLife(self): downPipeRect0 = pygame.Rect( self.pipeX0, self.spaceBetweenPipesHeight0 + self.spaceBetweenPipes0 / 2, self.pipeWidth, self.pipeHeight) topPipeRect0 = pygame.Rect( self.pipeX0, 0 - self.pipeHeight + self.spaceBetweenPipesHeight0 - self.spaceBetweenPipes0 / 2, self.pipeWidth, self.pipeHeight) downPipeRect1 = pygame.Rect( self.pipeX1, self.spaceBetweenPipesHeight1 + self.spaceBetweenPipes1 / 2, self.pipeWidth, self.pipeHeight) topPipeRect1 = pygame.Rect( self.pipeX1, 0 - self.pipeHeight + self.spaceBetweenPipesHeight1 - self.spaceBetweenPipes1 / 2, self.pipeWidth, self.pipeHeight) for Bird in self.Birds: if downPipeRect0.colliderect( Bird.bird ) or topPipeRect0.colliderect( Bird.bird ) or downPipeRect1.colliderect( Bird.bird ) or topPipeRect1.colliderect( Bird.bird ) or Bird.birdY > self.HEIGHT - Bird.birdHeight / 2 or Bird.birdY < Bird.birdHeight / 2: Bird.dead = 1 def updateScores(self): for Bird in self.Birds: if Bird.birdX > self.pipeClosest + self.pipeWidth and Bird.flagUpdateScore == 0 and self.flagPipePassed == 0 and Bird.dead == 0: Bird.score += 1 Bird.flagUpdateScore = 1 self.flagScoresIncremented += 1 if self.flagScoresIncremented != 0: self.flagPipePassed = 1 self.flagScoresIncremented = 0 def gui(self): #Font font = pygame.font.SysFont("Arial", 25) #GUI self.screen.fill((255, 255, 255)) self.screen.blit(self.background, (0, 0)) self.screen.blit(self.background, (self.WIDTH / 2, 0)) #Pipe0 Image self.screen.blit(self.downPipe, (self.pipeX0, self.spaceBetweenPipesHeight0 + self.spaceBetweenPipes0 / 2)) self.screen.blit( self.topPipe, (self.pipeX0, 0 - self.pipeHeight + self.spaceBetweenPipesHeight0 - self.spaceBetweenPipes0 / 2)) #Pipe1 Image self.screen.blit(self.downPipe, (self.pipeX1, self.spaceBetweenPipesHeight1 + self.spaceBetweenPipes1 / 2)) self.screen.blit( self.topPipe, (self.pipeX1, 0 - self.pipeHeight + self.spaceBetweenPipesHeight1 - self.spaceBetweenPipes1 / 2)) #Base Image self.screen.blit(self.base, (0, self.HEIGHT)) self.screen.blit(self.base, (self.WIDTH / 2, self.HEIGHT)) #Score scoreRect = pygame.Rect(self.WIDTH, 0, self.SCORES, self.HEIGHT + self.baseHeight) self.screen.blit( self.backgroundScores, (self.WIDTH, 0, self.SCORES, self.HEIGHT + self.baseHeight)) self.interlineSCORES = 30 #Score,Genetic Cycles and Birds Alive printing on screen self.screen.blit( font.render("Genetic Cycles" + " : " + str(self.geneticCycles), -1, (0, 0, 0)), (self.WIDTH + 30, self.interlineSCORES)) self.interlineSCORES += 50 for Bird in self.Birds: if (Bird.score > self.maxScore): self.maxScore = Bird.score self.screen.blit( font.render( "Birds alive" + " : " + str(len(self.birdsAlive)) + "/ " + str(len(self.Birds)), -1, (0, 0, 0)), (self.WIDTH + 30, self.interlineSCORES)) self.interlineSCORES += 50 self.screen.blit( font.render("Max Score" + " : " + str(self.maxScore), -1, (0, 0, 0)), (self.WIDTH + 30, self.interlineSCORES)) self.interlineSCORES += 50 def difficultyIncrease(self): #decreasing space between pipes if self.maxScore > 100 and ( self.maxScore % 50) == 0 and self.maxScore != 0 and ( self.pipeX0 == self.WIDTH / 2 - self.pipeWidth or self.pipeX1 == self.WIDTH / 2 - self.pipeWidth): if self.spaceBetweenPipesMax > self.spaceBetweenPipesMin + 10 and self.spaceBetweenPipesMin > 100: self.spaceBetweenPipesMax -= 10 self.spaceBetweenPipesMin -= 5 # --- run --- def restart(self): self.spaceBetweenPipesMin = 150 self.spaceBetweenPipesMax = 200 self.distanceBetweenPipesMin = self.WIDTH / 2 self.distanceBetweenPipesMax = (3 / 4) * self.WIDTH '''self.spaceBetweenPipes0 = random.randint(self.spaceBetweenPipesMin, self.spaceBetweenPipesMax) self.spaceBetweenPipesHeight0 = random.randint(self.pipeHeight - self.spaceBetweenPipesMax / 2, self.pipeHeight + self.spaceBetweenPipesMin / 2)''' self.spaceBetweenPipes0 = 250 self.spaceBetweenPipesHeight0 = 300 self.spaceBetweenPipes1 = random.randint( int(self.spaceBetweenPipesMin), int(self.spaceBetweenPipesMax)) self.spaceBetweenPipesHeight1 = random.randint( int(self.pipeHeight - self.spaceBetweenPipesMax / 2), int(self.pipeHeight + self.spaceBetweenPipesMin / 2)) #Initialization Variables for Pipes self.pipeX0 = self.WIDTH / 2 - self.pipeWidth / 2 self.pipeX1 = self.WIDTH #self.pipeClosest = self.pipeX0 #Initialization Variables for Scores self.flagPipePassed = 0 self.flagScoresIncremented = 0 self.maxScore = 0 #Create Flock (Standard Jump) '''for Bird in self.Birds: birdY = 200 Bird.gravityAcceleration = 0 #self.isJumping = 0 #Bird.jumpHeight = 0 #Initialization Variables for Life Bird.dead = 0 Bird.birdX = 50 Bird.birdY = 200 Bird.birdPositionX = 0 Bird.birdPositionY = 0 #Initialization Variables for Score Bird.score=0 Bird.flagUpdateScore = 0 #Initialization number of jump made Bird.jumpMade=0''' #Create Flock (Parabolic Jump) for Bird in self.Birds: birdY = 200 #Initialization Variables for Life Bird.dead = 0 Bird.birdX = 50 Bird.birdY = 200 Bird.birdPositionX = 0 Bird.birdPositionY = 0 #Initialization Variables for Score Bird.lastScore = Bird.score Bird.score = 0 Bird.flagUpdateScore = 0 #Initialization number of jump made Bird.jumpMade = 0 Bird.vy = 0 self.birdsAlive = [bird for bird in self.Birds if bird.dead == 0] def run(self): clock = pygame.time.Clock() #Imports clock of the game pygame.font.init() font = pygame.font.SysFont("Arial", 25) #Games Loop while len(self.birdsAlive) != 0 and self.maxScore < self.maxFinalScore: #Controls the speed of the game clock.tick_busy_loop(self.clockSpeed) self.birdsPositions() #Event Handler for Bird in self.Birds: Bird.isJumping = 0 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() #Update position of the closest pipe if (self.pipeX0 < self.pipeX1): self.pipeClosest = self.pipeX0 else: self.pipeClosest = self.pipeX1 #GUI self.gui() #Increase of the difficulty self.difficultyIncrease() #Updating Birds self.updateScores() self.birdsAlive = [bird for bird in self.Birds if bird.dead == 0] self.updatePipes() self.nextSpaceBetweenPipes = self.getNextSpaceBetweenPipes() for bird in self.birdsAlive: self.screen.blit(bird.birdImgs[0], (bird.birdX, bird.birdY)) bird.updateBird(self.nextSpaceBetweenPipes) bird.distanceTraveled += self.pipeSpeed self.updateLife() #Writing on file if self.maxScore >= 100: self.writeOnFile(self.geneticCycles) #Refresh Screen pygame.display.update() #Game over self.screen.fill((255, 255, 255)) self.screen.blit(self.gameOver, (40 + self.WIDTH / 4, 250)) self.index = 1 self.interlineSCORES = 30 for Bird in self.Birds: self.screen.blit( font.render( str(self.index) + " : " + str(Bird.distanceTraveled), -1, (0, 0, 0)), (self.WIDTH + 30, self.interlineSCORES)) self.index += 1 self.interlineSCORES += 50 def geneticEvolution(self): self.genetic = GeneticAlgorithm(self.Birds) self.geneticCycles += 1 self.Birds = self.genetic.runGeneticAlgorithm() def writeOnFile(self, nepochs): out_file = open( "data/trainingDataset_Parabolic3" + str(nEpochs) + ".txt", "a") if len(self.birdsAlive) > 0: out_file.write("%f," % self.birdsAlive[0].birdPositionX) out_file.write("%f," % self.birdsAlive[0].birdPositionY) out_file.write("%f," % self.nextSpaceBetweenPipes) out_file.write("%f\n" % self.birdsAlive[0].nn.takeDecision( self.birdsAlive[0].birdPositionX, self.birdsAlive[0].birdPositionY, self.nextSpaceBetweenPipes)) out_file.close() def loadLearnedNN(self): #learnedNN = LearningAlgorithm() #self.Birds = [] #self.Birds.append(Bird()) l1 = LearningAlgorithm() self.Birds[len(self.Birds) - 1].nn = l1.returnTrainedNN() self.Birds[len(self.Birds) - 1].birdImgs = [ pygame.image.load("img/redBirdFlap0.png").convert_alpha() ]
from geneticAlgorithm import GeneticAlgorithm from area import Area import numpy as np numberOfBlocks: int = 30 populationSize: int = 150 mutationPercent: float = 0.5 successionRate: int = 10 diversityRate: float = 0.5 time: int = 0 solution: int = 0 secondStage: bool = False progress: int = 100 if __name__ == '__main__': area = Area('file') area = Area('draw', 25) ga = GeneticAlgorithm(area, populationSize, mutationPercent, successionRate, diversityRate, time, solution, secondStage, progress) #ga.printParameters() ga.start()
print('Enter Neighbours: (ex. 0 1)') graph = {} for i in range(numberOfEdges): neighbours = input().split() if neighbours[0] in graph: graph[neighbours[0]].append(neighbours[1]) else: graph[neighbours[0]] = [neighbours[1]] algorithm = int( input( 'Which Algorithm You Want To Use:\n1.Genetics Algorithm\n2.Simulated Annealing:' )) if algorithm == 1: numberOfGenerations = int(input('Number Of Generations: ')) populationSize = int(input('Population Size: ')) tournumentSize = int(input('Tournument Size: ')) if tournumentSize > populationSize / 2: print('Tournument Size > Population Size / 2 !!!') print('No Parents can be produced!') exit(0) mutationRate = float(input('Mutation Rate: ')) GeneticAlgorithm(numberOfGenerations, populationSize, tournumentSize, mutationRate, numberOfProvinces, numberOfEdges, graph).run() elif algorithm == 2: # initialTemp = int(input('InitialTemp: ')) # probabiltyFunction = int(input('Probability Function: ')) SimulatedAnnealing(1.8, 1, numberOfProvinces, numberOfEdges, graph).run()
def constraint_satisfied(history): # extract Zt acceleration from the last N states Zt_dtdt = np.array(history)[:, 4] #standard deviation of Zt_dtdt devZt_dtdt = np.std(Zt_dtdt * Mt) #boundary condition F_stat_bound = (Mb + Mt) * 9.81 / 3.0 return devZt_dtdt <= F_stat_bound if __name__ == '__main__': print(f'Loading model "{MODEL_PATH.split("/")[-1]}"') model = GeneticAlgorithm.load_model(MODEL_PATH) print(f'Loading evaluation road profile "{ROAD_PROFILE_EVAL}"') with open(ROAD_PROFILE_EVAL, 'rb') as file: road_profile = pickle.load(file) history = [] env = Simulator(road_profile) x = env.states[-1] print('Simulating...') for step in range(len(road_profile) - 1): Zb, Zb_dt, Zb_dtdt, Zt, Tz_dt, Zt_dtdt, last_i, Zh, Zh_dt = x # add a moving average of the last states to the model's input moving_avg = env.moving_average() x = np.concatenate((x, moving_avg))
# Set arguments to variables problem = args.problem filename = args.filename crossover_prob = args.crossover_prob mutation_prob = args.mutation_prob popSize = args.population_size generation = args.generation # Traveling Salesman Problem Dataset dataset = Salesman(filename) dataset.read() gene_size = len(dataset.location) # Generate each GA instance tspga = GeneticAlgorithm(gene_size, popSize, crossover_prob, mutation_prob) best_fitness = [] mean_fitness = [] print('Ranking', end=' ') tspga.initialization() bf, mf = tspga.calculateFitness(dataset) best_fitness.append(bf) mean_fitness.append(mf) # Training for i in range(generation): # tspga.orderTwoCrossover() # tspga.cycleCrossover() tspga.partialMappedCrossover()
from hyperparameters import * MODEL_DIRECTORY = '../models/' MODEL_NAMES = ['grid_29.roadie', 'model_20.roadie', 'model_84.roadie'] ROAD_PROFILE_LIST = ['ts3_1_k_3.0.csv', 'ts3_2_k_3.0.csv', 'ts3_3_k_3.0.csv'] df = pd.DataFrame(data=history, columns=['t', 'Zh', 'Zt', 'Zb', 'Zt_dtdt', 'Zb_dtdt', 'i']) print(df) df.to_csv('result.csv') for index in range(len(MODEL_NAMES)): for roads in range(len(ROAD_PROFILE_LIST)): print(f'Loading model "{MODEL_NAMES[index].split(".")[0]}"') model = GeneticAlgorithm.load_model(MODEL_DIRECTORY + MODEL_NAMES[index]) print(f'Loading evaluation road profile "{ROAD_PROFILE_LIST[roads]}"') road_profile = ProfileManager.csv_to_profile(ROAD_PROFILE_LIST[roads], VELOCITY) history = [] env = Simulator(road_profile) x = env.states[-1] print('Simulating...') for step in range(len(road_profile) - 1): Zb, Zb_dt, Zb_dtdt, Zt, Tz_dt, Zt_dtdt, last_i, Zh, Zh_dt = x x_torch = torch.from_numpy(x.reshape((1, ) + x.shape)) i = model(x_torch)[0, 0].detach().numpy() * 2 #i = index t = DT * step
default='result.json', type=str, help='Set the output filename(json).') args = parser.parse_args() # Check argument by standard output print(args) # Set arguments to variables crossover_prob = args.crossover_prob mutation_prob = args.mutation_prob gene_size = args.gene_size popSize = args.population_size generation = args.generation # Generate each GA instance dsmga = GeneticAlgorithm(gene_size, popSize, crossover_prob, mutation_prob) best_fitness = [] mean_fitness = [] best_chromosomes = [] print('Dependency Structure Matrix Genetic Algorithm...', end=' ') dsmga.initialization() bf, mf, bc = dsmga.calculateFitness() best_fitness.append(bf) mean_fitness.append(mf) best_chromosomes.append(bc) # Training print("Start Iteration") bb_info = []
def main(): print("Parsing input data...") # Parse configuration files config = parser.parseConfiguration(CONFIG_INPUT) # Parse item files, pass the path to folder parser.parseItems(config.data) # Generate instance of the genetic algorithm configuration ga = GeneticAlgorithm(config) print("Starting algorithm") print("Press ctrl + c to stop at any moment") # Define output file and prepare output filename = OUTPUT_DIR + ('run_%s_%s.csv' % (config.clase, time.time())) prepareOutput(filename) # Generate the initial random population population = ga.generateInitialPopulation(config.n) generation = 0 # Plotting if config.show: plt.style.use('seaborn-whitegrid') fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 5)) try: # Iterate while terminal condition is not met while not ga.isTerminated(population): print('GENERATION #' + str(generation)) # Calculate data and keep in memory storeData(population, generation) # Plot the line if config.show: plotPoints(axes, fig, config.sampling) # Select parents for next generation parents = ga.select(population, config.k, config.a, generation) # Cross parents to generate children children = ga.crossAll(parents) # Mutate children for i in range(len(children)): children[i] = ga.mutate(children[i]) # Select next generation population = ga.nextGeneration(population, children, config.b, generation) generation += 1 storeData(population, generation) if config.show: plotPoints(axes, fig, config.sampling) print("Best configuration is:") print(getBestCharacter(population)) # Write output with open(filename, 'a') as csv_file: # Get instance of the writer csv_writer = csv.DictWriter(csv_file, fieldnames=OUTPUT_FIELDNAMES) writeAll(csv_writer) if config.show: print("Close the plot to stop program") plt.show() except KeyboardInterrupt: print("Finishing up...")
def immediatelyCall(algorithm: GeneticAlgorithm): return algorithm.algorithm()
class Game(object): def __init__(self, numCars): self.numCars = numCars self.cars = [] self.walls = ((1256, 269), (1157, 267), (1050, 187), (862, 164), (744, 352), (614, 338), (495, 169), (318, 164), (223, 366), (12, 356), (10, 451), (291, 465), (404, 267), (566, 465), (817, 472), (942, 272), (1037, 294), (1124, 375), (1262, 380), (1256, 269)) #self.cookies are the lines in purple, the word cookies comes from giving cookies to dogs as rewards when they behavior good (we assume that cars can eat cookies in some way xD) self.cookies = (((1159, 268), (1149, 373)), ((1144, 256), (1103, 358)), ((1077, 330), (1120, 239)), ((1094, 218), (1047, 303)), ((1025, 292), (1058, 192)), ((1015, 181), (998, 285)), ((964, 278), (970, 178)), ((943, 272), (906, 170)), ((857, 171), (931, 288)), ((915, 316), (829, 216)), ((806, 250), (890, 353)), ((874, 381), (784, 286)), ((766, 318), (852, 411)), ((834, 443), (751, 340)), ((806, 472), (743, 352)), ((753, 469), (719, 351)), ((701, 467), (697, 348)), ((660, 343), (664, 466)), ((631, 340), (619, 465)), ((572, 465), (612, 335)), ((537, 429), (593, 311)), ((575, 281), (501, 386)), ((469, 350), (556, 253)), ((533, 223), (444, 316)), ((426, 298), (505, 186)), ((471, 169), (413, 278)), ((420, 168), (406, 270)), ((401, 271), (364, 167)), ((398, 277), (313, 175)), ((391, 290), (293, 216)), ((277, 254), (373, 321)), ((360, 343), (262, 283)), ((248, 314), (343, 372)), ((326, 402), (234, 339)), ((306, 439), (227, 359)), ((291, 465), (223, 365)), ((243, 462), (211, 365)), ((196, 461), (197, 364)), ((159, 459), (167, 365)), ((133, 360), (130, 457)), ((97, 456), (104, 359)), ((73, 359), (69, 453)), ((43, 449), (48, 359)), ((30, 356), (27, 452))) self.time = 0 self.maxTime = 800 self.deadCars = 0 self.carPos = (1180, 320) for i in range(0, numCars): self.cars.append(Car(self.carPos[0], self.carPos[1])) numWeights = self.cars[0].neuralNet.getNumberWeights() self.geneticAlgorithm = GeneticAlgorithm(numCars, numWeights) for i in range(0, numCars): self.cars[i].neuralNet.putWeights(self.geneticAlgorithm.population[i].genes) self.textSize = 32 self.textsToDraw = [] def initialize(self): # Initialise screen pygame.init() self.myfont = pygame.font.SysFont("Comic Sans MS", self.textSize) self.screen = pygame.display.set_mode((1280, 720)) pygame.display.set_caption('Car Demo - Zibu') clock = pygame.time.Clock() # Fill background self.background = pygame.Surface(self.screen.get_size()) self.background = self.background.convert() self.background.fill((250, 250, 250)) # Event loop while 1: clock.tick(30) for event in pygame.event.get(): if event.type == QUIT: return if event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE: self.deadCars = self.numCars self.draw() self.update() def canBeUpdated(self, carNumber): if self.time % 2 == 0: if carNumber % 2 == 0: return True else: if carNumber % 2 != 0: return True return False def handleCollisions(self): carNumber = 0 for car in self.cars: if car.isAlive: car.update() if self.canBeUpdated(carNumber): rayPoints = [[], [], [], [], [], [], []] car.rayPoints = [[], [], [], [], [], [], []] for i in range(0, len(self.walls)-1): for j in range(0, len(car.edgesPointsAprox)-1): if utils.intersect(car.edgesPointsAprox[j], car.edgesPointsAprox[j+1], self.walls[i], self.walls[i+1]): if car.isAlive: car.isAlive = False self.deadCars += 1 break points = utils.lineRayIntersectionPoint(car.position, (car.leftPoint[0] - car.position[0], car.leftPoint[1] - car.position[1]), self.walls[i], self.walls[i+1]) if points: rayPoints[0] += points points = utils.lineRayIntersectionPoint(car.position, (car.frontLeft2Point[0] - car.position[0], car.frontLeft2Point[1] - car.position[1]), self.walls[i], self.walls[i+1]) if points: rayPoints[1] += points points = utils.lineRayIntersectionPoint(car.position, (car.frontLeftPoint[0] - car.position[0], car.frontLeftPoint[1] - car.position[1]), self.walls[i], self.walls[i+1]) if points: rayPoints[2] += points points = utils.lineRayIntersectionPoint(car.position, (car.frontPoint[0] - car.position[0], car.frontPoint[1] - car.position[1]), self.walls[i], self.walls[i+1]) if points: rayPoints[3] += points points = utils.lineRayIntersectionPoint(car.position, (car.frontRightPoint[0] - car.position[0], car.frontRightPoint[1] - car.position[1]), self.walls[i], self.walls[i+1]) if points: rayPoints[4] += points points = utils.lineRayIntersectionPoint(car.position, (car.frontRight2Point[0] - car.position[0], car.frontRight2Point[1] - car.position[1]), self.walls[i], self.walls[i+1]) if points: rayPoints[5] += points points = utils.lineRayIntersectionPoint(car.position, (car.rightPoint[0] - car.position[0], car.rightPoint[1] - car.position[1]), self.walls[i], self.walls[i+1]) if points: rayPoints[6] += points for i in range(0, len(rayPoints)): if rayPoints[i]: index = 0 minDist = utils.distance(rayPoints[i][0], car.position) for j in range(0, len(rayPoints[i])): dist = utils.distance(rayPoints[i][j], car.position) if dist < minDist: minDist = dist; index = j car.inputs[i] = minDist car.rayPoints[i] = int(round(rayPoints[i][index][0])), int(round(rayPoints[i][index][1])) else: car.rayPoints[i] = (0, 0) car.inputs = [float(i)/max(car.inputs) for i in car.inputs] for i in range(0, len(self.cookies)): for j in range(0, len(car.edgesPointsAprox)-1): if utils.intersect(car.edgesPointsAprox[j], car.edgesPointsAprox[j+1], self.cookies[i][0], self.cookies[i][1]): f = lambda a,b: a if (a > b) else b maxCookie = -1 if car.lastsCookies: maxCookie = functools.reduce(f, car.lastsCookies) if i not in car.lastsCookies and i > maxCookie: car.lastsCookies.append(i) car.incrementFitness() if len(car.lastsCookies) > 5: car.lastsCookies.pop(0) carNumber += 1 def draw(self): self.screen.blit(self.background, (0, 0)) pygame.draw.lines(self.screen, (0, 0, 0), False, self.walls, 3) for wall in self.cookies: pygame.draw.lines(self.screen, (150, 150, 255), False, wall, 1) for car in self.cars: if car.isAlive: pygame.draw.lines(self.screen, (0, 255, 0), False, car.edgesPointsAprox, 2) for point in car.rayPoints: if point: pygame.draw.circle(self.screen, (150, 150, 150), point, 3) pygame.draw.lines(self.screen, (150, 150, 150), False, [car.position, point], 1) else: pygame.draw.lines(self.screen, (255, 0, 0), False, car.edgesPointsAprox, 2) for i in range(0, len(self.textsToDraw)): label = self.myfont.render(self.textsToDraw[i], 1, (0,0,0)) self.screen.blit(label, (0, 50 + i*self.textSize)) pygame.display.flip() def update(self): self.handleCollisions() if(self.time >= self.maxTime or self.deadCars >= self.numCars): self.deadCars = 0 self.time = 0 self.geneticAlgorithm.update2() for i in range(0, self.numCars): self.cars[i].reset(self.carPos[0], self.carPos[1]) self.cars[i].neuralNet.putWeights(self.geneticAlgorithm.population[i].genes) for i in range(0, len(self.cars)): self.geneticAlgorithm.population[i].fitness = self.cars[i].fitness self.time += 1 self.geneticAlgorithm.calcFitness() self.textsToDraw = [] self.textsToDraw.append("Generation: " + str(self.geneticAlgorithm.generationNum)) self.textsToDraw.append("Avg Fitness: " + str(int(round(self.geneticAlgorithm.avgFitness)))) self.textsToDraw.append("Best Fitness: " + str(int(round(self.geneticAlgorithm.bestFitness)))) self.textsToDraw.append("Game Time: " + str(self.time) + "/" + str(self.maxTime))
def main(): gen = GeneticAlgorithm(10) gen.run()