def Start(self, maxIter = 50): self.Population = Population() for i in range(self.PopulationSize): indi = self.Chromosome.Clone() indi.Randomize() self.Population.append(indi) self.ResEval.Evaluate(self.Population) self.PenEval.Evaluate(self.Population) self.FitnessEval.Evaluate(self.Population) self.Population.SortByFitness() for gen in range(maxIter): newPop = Population() newPop.extend(self.Population[:self.Elitism]) for i in range(self.Elitism, len(self.Population)): selected = self.SelectionOp.Select(self.Population) offspring = self.RecombinationOp.Combine(selected) # FIXME: mutation? #self.MutationOp.Mutate(offspring) offspring.ClipWithinBounds() newPop.append(offspring) self.Population = newPop self.ResEval.Evaluate(self.Population) self.PenEval.Evaluate(self.Population) self.FitnessEval.Evaluate(self.Population) self.Population.SortByFitness() print "Generation %d" % (gen + 1) print self.Population[0] if self.PostIterationCallback != None: self.PostIterationCallback(gen, self.Population)
def initialize(self): if self.type == 'normal': for popNumber in range(8): pop = Population(popNumber, 0, self.cities, 100, 'normal', 5, 0.05, 10, self.migrationSize, None) pop.createInitialPopulation() pop.evaluate() self.populations.append(pop) elif self.type in ['static', 'dynamic']: pop0 = Population(0, 0, self.cities, 100, 'absolute', 5, None, 10, self.migrationSize, None) pop1 = Population(1, 0, self.cities, 100, 'empirical', 5, None, 10, self.migrationSize, None) pop2 = Population(2, 0, self.cities, 100, 'normal', 5, 0.05, 10, self.migrationSize, None) pop3 = Population(3, 0, self.cities, 100, 'absolute', 5, None, 10, self.migrationSize, None) pop4 = Population(4, 0, self.cities, 100, 'empirical', 5, None, 10, self.migrationSize, None) pop5 = Population(5, 0, self.cities, 100, 'normal', 5, 0.05, 10, self.migrationSize, None) pop6 = Population(6, 0, self.cities, 100, 'absolute', 5, None, 10, self.migrationSize, None) pop7 = Population(7, 0, self.cities, 100, 'empirical', 5, None, 10, self.migrationSize, None) self.populations = [pop0, pop1, pop2, pop3, pop4, pop5, pop6, pop7] for pop in self.populations: pop.createInitialPopulation() pop.evaluate() pass
def test_set_get_pop(self): coils = GAutils.get_coils_from_excel() population1 = Population.Population(coils) population1.createInitial(GAutils.CONST_POPULATION_SIZE) pop1 = population1.getPop() population2 = Population.Population(coils) population2.createInitial(GAutils.CONST_POPULATION_SIZE) pop2 = population2.getPop() self.assertNotEqual(pop1, pop2) population2.setPop(pop1) pop2 = population2.getPop() self.assertEqual(pop1, pop2)
def statistics(self): bestfitnesses = [] for i in range(TEST_RUNS): self.population = Population(no=TEST_POP) for j in range(TEST_ITER): self.iteration() bestfitnesses.append(self.population.v[0].fittness(self.problem)) bf = np.array(bestfitnesses) mu = bf.mean() sigma = bf.std() textstr = '\n'.join( (r'$\mu=%.2f$' % (mu, ), r'$\sigma=%.2f$' % (sigma, ))) f, axarr = plt.subplots(1, 2, figsize=(10, 5)) axarr[0].set_title("Results of " + str(TEST_RUNS) + " runs with a population of " + str(TEST_POP)) axarr[0].plot(np.array(range(len(bestfitnesses))), bf, c='r', label="Fitness") axarr[0].set_xlabel("Run") axarr[0].set_ylabel("Fitness") axarr[0].legend(loc='upper right') props = dict(boxstyle='round', facecolor='w', alpha=0.5) axarr[0].text(0.05, 0.95, textstr, transform=axarr[0].transAxes, fontsize=14, verticalalignment='top', bbox=props) self.population = Population() fitnesses = [] for i in range(NO_ITER): self.iteration() fitnesses.append(self.population.v[0].fittness(self.problem)) axarr[1].set_title("Variation of fitness in one run") axarr[1].plot(np.array(range(len(fitnesses))), np.array(fitnesses), c='r', label="Fitness") axarr[1].set_xlabel("Iteration") axarr[1].set_ylabel("Fitness") axarr[1].legend(loc='upper right')
def create_initial_population(self): population = Population() for _ in range(self.num_of_individuals): individual = self.problem.generateIndividual() self.problem.calculate_objectives(individual) population.population.append(individual) return population
def oneRun(constants, evaluation, sheet=None): """ Performs one run of the experiment Parameters: -``constants``: Config settings for the EA from the config files specified at run time -``evaluation``: Fitness function. From ``Fitness`` Module """ created = [] if "popType" in constants: pop = Util.moduleClasses(Population)[constants["popType"]](constants) else: pop = Population.Population(constants) best, evals, lastImproved = Population.Individual(), 0, 0 rowCounter = 0 while evals < constants["evals"] and best.fitness < constants["maxFitness"]: try: child = pop.next() except StopIteration: break evaluation(child) evals += 1 if best < child: lastImproved = evals created.append((evals, child.fitness, child)) best = child print best.fitness return created
def main_2(): iter_max = 30 Pop = Population( "AAAGGATCTTCTTGAGATCCTTTTTTTCTGCGCGTAATCTGCTGCCAGTAAACGAAAAAACCGCCTGGGGAGGCGGTTTAGTCGAAGGTTAAGTCAG" ) Pop.evolve(iter_max, "Tournoi")
def main(): while True: prob = Problem() #create problem size = prob.loadData( "data01.in") #load data of problem, return board size x = Individ([0] * size) pop = Population(x) alg = Algorithm(pop) alg.readParameters("param.in") printMainMenu() x = input() if x == "1": bestX, sample = alg.run() print(bestX) print(bestX.fitness()) plt.plot(sample) # function to show the plot plt.show() if x == "2": alg.run() sd, m = alg.statistics() print("Standard deviation " + str(sd)) print("Mean " + str(m)) if x == "0": return
def evolve_Population(self,myPop): newPopulation = Population(myPop.get_size(),False,"2") #Saving the most fittest from old population newPopulation.save_individual(0,myPop.get_Fittest()) print(newPopulation.individuals) #selecting two random individual crossover_List = list(combinations(Population.individuals, 2)) #checking crossover probability and generating cross over population for pair in crossover_List: i=1 test = random.randint(0,100) if(test<=75): print("CrossOVer positive") (indiv1, indiv2) = pair self.crossover(indiv1,indiv2,newPopulation) i +=1 print("Generation 1 :") print(newPopulation.individuals,len(newPopulation.individuals)) #removing Duplicates using dictionary print(newPopulation.dict_pop,len(newPopulation.dict_pop)) print(newPopulation.dict_fitness,len(newPopulation.dict_fitness)) print(newPopulation.get_Fittest())
def evolve(self): self.population = self.utils.create_initial_population() print 'initial population generate' self.utils.fast_nondominated_sort(self.population) for front in self.population.fronts: self.utils.calculate_crowding_distance(front) returned_population = None for j in range(self.num_of_generations): print 'generation: ' + str(j) children = self.utils.create_children(self.population) self.population.extend(children) self.utils.fast_nondominated_sort(self.population) new_population = Population() front_num = 0 while len(new_population) + len(self.population.fronts[front_num] ) <= self.num_of_individuals: self.utils.calculate_crowding_distance( self.population.fronts[front_num]) new_population.extend(self.population.fronts[front_num]) front_num += 1 sorted(self.population.fronts[front_num], cmp=self.utils.crowding_operator) # random.shuffle(self.population.fronts[front_num]) print[[self.problem.f1(i), self.problem.f2(i)] for i in self.population.fronts[0]] new_population.extend( self.population.fronts[front_num][0:self.num_of_individuals - len(new_population)]) returned_population = self.population self.population = new_population return returned_population.fronts[0]
def generateTable(): global logGens logGens = "" generationNumber = 1 logGens += "\n> Generation # " + str(generationNumber) + "\n" population = Population.Population(POPULATION_SIZE) population.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True) logGens += str(displayMgr.print_generation(population)) logGens += str( displayMgr.print_schedule_as_table(population.get_schedules()[0])) geneticAlgorithm = GeneticAlgorithm.GeneticAlgorithm() while (population.get_schedules()[0].get_fitness() != 1.0): generationNumber += 1 logGens += "\n> Generation # " + str(generationNumber) + "\n" population = geneticAlgorithm.evolve(population) population.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True) logGens += str(displayMgr.print_generation(population)) logGens += str( displayMgr.print_schedule_as_table(population.get_schedules()[0])) print("\n\n") root.destroy() last_gen = displayMgr.get_generated(population.get_schedules()[0]) Generated_Table(last_gen)
def testing_the_algorithm_total_and_best_improvement(coils): """ This method used for research and debug purposes :param coils: the coils from the excel file :return: NONE """ population = Population.Population(coils) population.createInitial(CONST_POPULATION_SIZE) best_improve = [] total_improve = [] for i in range(CONST_GENERATIONS): population.updateGenesRange() selected = rouletteSelection(population) offspring = crossover(selected[0], selected[1]) c1 = offspring[0] c2 = offspring[1] c1 = mutate(c1) c2 = mutate(c2) c1.evaluate(c1.getSequence(), Steel.calculate_max_penalty(), population.coils) c2.evaluate(c2.getSequence(), Steel.calculate_max_penalty(), population.coils) population = replacement_elitism(population, offspring[0], offspring[1]) population.update_fitness() best = population.get_best_solution() best_improve.append(best[1]) total_improve.append(population.getFitness()) save_data_to_excel_self_and_total_improve(best_improve, total_improve)
def selection(popul, nb_best): """ \Description : Select the best individuals of a population as well as random individuals from the rest of the population \Args : popul : the population of individual to evolve nb_best : number of best individuals to select \Outputs : pop_next : The population of next generation """ # Select the nb_best best individuals selected_indiv = popul.pop[0:nb_best] # Select 2/3 of the population so that the the last 1/3 is from the crossover nb_rand_indiv = (popul.size - len(selected_indiv)) - (popul.size // 3) # Select random individuals from the rest of the population selected_indiv.extend(sample(popul.pop[nb_best:], nb_rand_indiv)) # Create the corresponding population pop_next = Pop.Population(dataset=popul.dataset, size=len(selected_indiv), NL_set=popul.NL_set, NF_set=popul.NF_set, lr_set=popul.lr_set, mom_set=popul.mom_set, indiv_list=selected_indiv, train_loader=popul.train_loader, test_loader=popul.test_loader, train_batch_size=popul.train_batch_size, test_batch_size=popul.test_batch_size) return pop_next
def encontrarSolucion(self): self.poblacion=Population.Population(POB_INICIAL) while((self.poblacion.getMejorIndividuo().getFitness() < sum(MAX_FITNESS)-ERROR_ACEPTABLE) and (self.poblacion.getNumeroGeneraciones()<MAX_GENERACIONES)): for x in self.poblacion.getGeneracionActual(): print( x.getCromosomas(),x.getFitness()) print('Fin GEN ',self.poblacion.getNumeroGeneraciones()) #PARENT SELECION parents=self.poblacion.seleccionarParents() #CROSSOVER cruzar=random.random() offSprings=[] if(cruzar<PROB_CROSSOVER): offSprings=parents[0].crearOffSprings_UniformCrossOver(parents[1]) #dos nuevos miembros #offSprings=parents[0].crearOffSprings_OnePointCrossOver(parents[1]) #dos nuevos miembros #MUTATION #Se puede decidir si mutar todos los descendientes o toda la poblacion entera poblacionBase=self.poblacion.getGeneracionActual() for x in poblacionBase: x.mutar() #SURVIVOR SELECTION nuevaGen=self.seleccionarSobrevivientes(poblacionBase,offSprings) self.poblacion.actualizarGeneracion(nuevaGen) print('Fin en generacion numero: ', self.poblacion.getNumeroGeneraciones()) print('primer mejor individuo: ', self.poblacion.getPrimerMejorIndividuo().getCromosomas(),self.poblacion.getPrimerMejorIndividuo().getFitness()) print(' mejor individuo: ', self.poblacion.getMejorIndividuo().getCromosomas(),self.poblacion.getMejorIndividuo().getFitness())
def get_baseline_maxmean(self, run_minutes, num_to_avg): print('Recording baseline intensity...\n') self.reset_time() args0 = copy.copy(self.args) args0.zernike_coeffs = [0] args0.num_masks = 1 uniform_pop = Population.Population(args0,base_mask=self.base_mask,uniform=True) frame = 0 times = [] end_time = datetime.datetime.now() + datetime.timedelta(0,int(run_minutes*60)) while datetime.datetime.now() < end_time: self.interface.get_output_fields(uniform_pop,repeat=num_to_avg) self.update_metrics(uniform_pop, 'initial',save_mask=False) times.append(datetime.datetime.now()) frame += num_to_avg print('Time left:', end_time-datetime.datetime.now()) self.save_path += '/baseline' os.makedirs(self.save_path, exist_ok=True) self.save_checkpoint() np.savetxt(self.save_path+'/baseline_times.txt', np.asarray(times,dtype='datetime64[s]'), fmt='%s') self.save_plots() self.save_path = args0.save_path print('.....Done\n\n')
def run(self): # get user input before running program print(self.summary) self.num_cities = 10 print(self.select_population_size) self.pop_size = int(input()) print(self.select_mutation_rate) self.mutation_rate = float(input()) print(self.generate_new_distances) self.generate = str(input()) self.cities = Cities.Cities(self.num_cities) # use user input to create population object # and use them in the algorithm p = Population.Population(self.num_cities, self.pop_size, self.mutation_rate, self.cities) if self.generate == 'y': p.get_cities().generate_distances() else: p.get_cities().create_distances() for x in range(0, 1000): p.run_algorithm() # top = p.get_population()[0] # print("First place is: ", top, " with ", top.get_fitness()) for x in range(0, self.pop_size - 1): print(p.get_population()[x], " with ", p.get_population()[x].get_fitness())
def selection(aPopulation, distanceArr): newPopulation = Population() aPopulation.calAllScores() mean = aPopulation.getAverage() print("average = ", mean) selected = 0 sum = 0 for x in aPopulation.getPopulation(): if x[1] <= mean: print("rate = ", mean / x[1]) sum += mean / x[1] print("sum = ", sum) for x in aPopulation.getPopulation(): if x[1] <= mean: rate = mean / x[1] print("weight = ", rate / sum) weight_int = int(round(rate * 100 / sum)) print("acutal weight = ", weight_int) selected += 1 for y in range(weight_int): copy = list(x[0].getSeq()) cities = CitySeq(copy) cities.calDistance(distanceArr) print("adding: ", cities, "\nsequence: ", cities.getSeq(), "\ndistance: ", cities.getDistance()) newPopulation.addIndividuals(cities) newPopulation.setSelected(selected) print("\ndone with selection\n") newPopulation.printPopulation() print("\ntotal individuals = ", len(newPopulation.individuals)) newPopulation.calAllScores() return newPopulation
def evolve_population(self, pop): new_population = Population.Population(pop.get_population_size(), False, self.tm) # Keep our best individual if elitism is enabled elitism_offset = 0 if self.__elitism: new_population.save_tour(0, pop.get_fittest()) elitism_offset = 1 # Crossover population # Loop over new population's size and creates individuals from current population for i in range(elitism_offset, new_population.get_population_size()): # Select parents parent_1 = self.tournament_selection(pop) parent_2 = self.tournament_selection(pop) # Crossover parents child = self.crossover(parent_1, parent_2) # Add child to new population new_population.save_tour(i, child) # Mutate the new population a bit to add some new genetic material for i in range(elitism_offset, new_population.get_population_size()): self.mutate(new_population.get_tour(i)) return new_population
def __init__(self, numOfPointsVal, populationSizeVal, rootWindow, controller): """Takes number of generations and Population() object""" self.pause = True self.stop = False # get random list listOfCities = rmg.genRandomListOfPoints(numOfPointsVal, 800, 400) # not use self.mutateRate = 0 # how often will mutation occur self.mutateChance = 0.01 self.populationSizeVal = populationSizeVal # population size must be even self.checkPopulationSize() self.population = population = Population.Population( self.populationSizeVal, listOfCities, self.mutateChance, self.mutateRate) self.event = mp.Event() controller.setEvent(self.event) controller.setForClossingEvent(self) pro = t.Thread(target=controller.genethicAlgorithmPart) pro.start() rootWindow.after(300, controller.addChangerListiner()) controller.show_frame(CanvasFrame) controller.getCurrentTopFrame().updateFrame( self.population.bestSalesman.dna.getAsListOfTuple()) print("After init EvolutionManager")
def processPopulations(self): manager = mp.Manager() retDict = manager.dict() jobs = [] for pop in self.populations: j = mp.Process(target=pop.processPopulation, args=(retDict, )) jobs.append(j) j.start() for j in jobs: j.join() self.newPopulations = [] self.generationNumber += 1 for pop in retDict.values(): newPop = Population(pop.populationID, self.generationNumber, cities_, pop.numberOfSpecimen, pop.type, pop.tournamentSize, pop.p_m, pop.eliteSize, pop.migrationSize, pop.specimen, pop.pmx, pop.cx, pop.ox, pop.pmxEff, pop.cxEff, pop.oxEff, pop.swap, pop.insert, pop.scramble, pop.inversion, pop.swapEff, pop.insertEff, pop.scrambleEff, pop.inversionEff) self.newPopulations.append(newPop) self.populations = self.newPopulations self.populations.sort(key=lambda x: x.populationID) pass
def __init__(self, screen): self.goal = [400, 10] self.boxSize = [800, 800] self.dotSize = 4 self.screen = screen self.test = Population(100, self.dotSize, self.boxSize, self.screen, self.goal)
def Main(): f = TestCases.Rosenbrock() ch = f.Chromosome() resEval = ResponseEvaluator(f) penEval = PenaltyEvaluator() penEval.ObjectivePenalties = f.Objectives() penEval.ConstraintPenalties = f.Constraints() fitnessEval = FitnessEvaluator() if False: opti = MonoObjectiveGA(ch, resEval, penEval, fitnessEval, 400, 2) else: pop = Population() for i in range(4): pop.append(ch.Clone()) pop.Randomize() resEval.Evaluate(pop) penEval.Evaluate(pop) fitnessEval.Evaluate(pop) pop.SortByFitness() opti = MonoObjectiveSurrogateGA(ch, resEval, penEval, fitnessEval, pop) opti.Start(50)
def testing_the_algorithm_1000_runs(coils): """ This method created for research only and not being used during normal runs :param coils: the coils from the excel file :return: NONE """ sum_first_generation_fit = 0 sum_last_generation_fit = 0 sum_fit_improvement = 0 sum_penalty_improvement = 0 temp_first = 0 temp_last = 0 for run in range(CONST_GENERATIONS_TO_TEST): population = Population.Population(coils) population.createInitial(CONST_POPULATION_SIZE) for i in range(CONST_GENERATIONS): population.updateGenesRange() best = population.get_best_solution() if i == 0: sum_first_generation_fit += best[1] temp_first = best[1] selected = rouletteSelection(population) offspring = crossover(selected[0], selected[1]) c1 = offspring[0] c2 = offspring[1] c1 = mutate(c1) c2 = mutate(c2) c1.evaluate(c1.getSequence(), Steel.calculate_max_penalty(), population.coils) c2.evaluate(c2.getSequence(), Steel.calculate_max_penalty(), population.coils) population = replacement_elitism(population, offspring[0], offspring[1]) population.update_fitness() best = population.get_best_solution() if i == (CONST_GENERATIONS - 1): sum_last_generation_fit += best[1] temp_last = best[1] sum_fit_improvement += (temp_last / temp_first) * 100 sum_penalty_improvement += ((1 - temp_last) / (1 - temp_first)) * 100 print(run) sum_first_generation_fit /= CONST_GENERATIONS_TO_TEST sum_last_generation_fit /= CONST_GENERATIONS_TO_TEST sum_fit_improvement /= CONST_GENERATIONS_TO_TEST sum_penalty_improvement /= CONST_GENERATIONS_TO_TEST wb = Workbook() ws = wb.active ws["A1"] = "first generation avg:" ws["B1"] = "last generation avg:" ws["C1"] = "fitness improvement avg:" ws["D1"] = "penalty improvement avg:" ws["E1"] = "population size:" ws["A2"] = sum_first_generation_fit ws["B2"] = sum_last_generation_fit ws["C2"] = sum_fit_improvement ws["D2"] = sum_penalty_improvement ws["E2"] = CONST_POPULATION_SIZE file_name = str(CONST_GENERATIONS_TO_TEST) + " runs avg.xlsx" wb.save(file_name)
def ButOptimizeClick(self): self.GetOptions() # self.PrintOptions() # Интерпретация пользовательского ввода. if self.nOfFunction == 1: self.OptFunction = QuadraticFunction self.toleranceRange = [[self.a1, self.b1]] elif self.nOfFunction == 2: self.OptFunction = RosenbrokFunction self.toleranceRange = [[self.a1, self.b1], [self.a2, self.b2]] elif self.nOfFunction == 3: self.OptFunction = MatyasFunction self.toleranceRange = [[self.a1, self.b1], [self.a2, self.b2]] self.FitnessFunction = FitnessFunction1 if self.nOfCodingProcedure == 0: self.Encode = Dec2Gray self.Decode = Gray2Dec elif self.nOfCodingProcedure == 1: self.Encode = Dec2Bin self.Decode = Bin2Dec # Настраиваем класс Organism методом его метакласса Configure. Organism.Configure(self.OptFunction, # Оптимизируемая функция; self.toleranceRange, # Ее ОДЗ; self.nOfGenes, # Число генов организма; self.FitnessFunction, # Его фитнес-функция; self.Encode, # Функция кодирования признака; self.Decode, # Функция декодирования признака; self.areCrossoverPointsDiffer, # Различны ли точки кроссовера?; self.areMutationPointsDiffer) # Различны ли точки мутации? # Создаем популяцию организмов. pop = Population(Organism, # Класс организмов, населяющих популяцию; self.nOfOrganisms, # Число организмов, , населяющих популяцию; self.crossoverProbability, # Вероятность кроссовера; self.nOfCrossoverPoints, # Число точек кроссовера; self.mutationProbability, # Вероятность мутации; self.nOfMutatingPoints) # Число точек мутации. # self.progressGeneration.setModal(True) # self.progressGeneration.show() self.progressGeneration.setMaximum(self.nOfGenerations-1) for i in range(self.nOfGenerations): pop.Generate() self.progressGeneration.setValue(i) self.lblx.setText('x* = ' + str(pop[0].argopt())) self.lblfx.setText('f(x*) = ' + str(pop[0].opt())) pop.listInfo.append(['x* =' , pop[0].argopt()]) pop.listInfo.append(['f(x*) = ', pop[0].opt()]) self.SaveIntegralInfoToFile('SystemInfo.txt', pop.listInfo)
def main_4(): lineList = [line.rstrip('\n') for line in open("./Data/plasmid_8k.fasta")] seq = ''.join(lineList[1:]) pop_size = 20 nb_gen = 4 pop = Population(seq, pop_size) pop.evolve(nb_gen, selection_method="Tournoi", alpha=0.593879313130056)
class Master: """ This class controls the Population / Individuals, kind like a master uses his whip to control his slaves. """ time.sleep(5) population = Population.Population(2) print(population) uinsane_bolt = population.population[1] uinsane_bolt.run()
def test_draw_traited_2(file_name, methode_sele, nbiter, nbindiv): lineList = [line.rstrip('\n') for line in open(file_name)] seq = ''.join(lineList[1:]) Pop = Population(seq, n=nbindiv) Pop.evolve(nbiter, selection_method=methode_sele) traj = Traj3D() traj.compute(seq, Pop._Get_Current_Best()[0]) return traj
def __init__(self): super().__init__() self.layout = 0 self.setGeometry(20, 30, 1500, 800) self.population = Population.Population() self.GenerCanvas = [0, 0] self.initUI() self.setAnotherLay() self.countGeneration = 0
def driver(num_sorting_genomes, num_test_genomes, num_generations, list_length): max_fitness_per_generation = [] sorting_genomes = [ sg.SortingGenome(list_length=list_length) for x in range(num_sorting_genomes) ] sort_test_genomes = [ stg.SortTestGenome(list_length=list_length) for x in range(num_test_genomes) ] population = p.Population(sorting_genomes, sort_test_genomes, sg.SortingGenome, stg.SortTestGenome) for gen_num in range(num_generations): population.next_generation() max_fit = -1.0 max_fit_index = 0 print 'entity fitness length is ' print len(population.entities) for i in range(len(population.entity_fitness)): if (population.entity_fitness[i] > max_fit): max_fit = population.entity_fitness[i] max_fit_index = i max_fitness_per_generation.append( [max_fit, population.entities[max_fit_index].genome]) print 'Max fit genome is ' print population.entities[max_fit_index].genome print 'Fitness is ' + str(max_fit) print 'Max fit genome length is ' print str(len(population.entities[max_fit_index].genome)) print 'max fit genome delete mutation rate is ' print str(population.entities[max_fit_index].delete_mutation_rate) print 'max fit genome mutation rate is ' print str(population.entities[max_fit_index].mutation_rate) print 'max fit genome add mutation rate is ' print str(population.entities[max_fit_index].copy_mutation_rate) print gen_num print 'Test cases are: ' for i in range(len(population.tests)): print population.tests[i].genome #for sorting_genome in population.entities: #print sorting_genome.genome max_fit = -1.0 max_fit_index = 0.0 for i in range(len(population.entity_fitness)): if (population.entity_fitness[i] > max_fit): max_fit = population.entity_fitness[i] max_fit_index = i print 'Max fit genome is ' print population.entities[i].genome print 'Max fit genome length is ' print len(population.entities[i].genome) return max_fitness_per_generation
def test_calculate_transition_penalty(self): # we calculated the transition penalty between the 2 first coils outside the program: 0.1885 coils = GAutils.get_coils_from_excel() population = Population.Population(coils) population.createInitial(GAutils.CONST_POPULATION_SIZE) # coils[0] is pf type Steel and holds the attributes for the coils temp = coils[0].calculate_penalty(coils[1]) temp = float("%.4f" % temp) self.assertAlmostEqual(temp, 0.1984)