def init_population(filename, year=2017): filepath = basepath + filename df = pandas.read_csv(filepath) num_places = len(df) df = df.drop(df.columns[0], axis=1) # print(df) population = Population(num_places) # age_ranges = Parser.get_age_ranges() population_ages = Parser.get_population_data()[year] total_pop = sum(population_ages.values()) for pop in population_ages: percentage = population_ages[pop] / total_pop population_ages[pop] = percentage for _, row in df.iterrows(): lug_pop = row['POPULATION'] home_loc = row['PLACE_ID'] for (a, b) in population_ages: percentage = population_ages[(a, b)] pop_in_range = int(round(percentage * lug_pop, 0)) population.add_batch_age_range(pop_in_range, home_loc, a, b) return population
def calculate(self): outWorkbook = xlsxwriter.Workbook('D:\Program Files\Sztuczna inteligencja\Lista 1\wyniki\\' + self.fileName) outSheet = outWorkbook.add_worksheet() outSheet.write("A1", "najlepszy") outSheet.write("B1", "średni") outSheet.write("C1", "najgorszy") population = Population(self.pop_size, self.loader) m = Mutation(self.Pm) cross = OrderedCrossover(self.Px, self.loader) ts = Selection(self.Tour) generationNumber = 0 i = 2 while(generationNumber < self.gen): newPopSize = 0 newPopulation = Population(0, self.loader) while(newPopSize < self.pop_size): val1 = ts.selection_result(population) val2 = ts.selection_result(population) ox = cross.crossover(val1, val2) mut = m.mutate(ox) newPopulation.population_array.append(mut) newPopSize+=1 population = newPopulation outSheet.write("A"+str(i), str(selectBest(population.population_array))) outSheet.write("B" + str(i), str(avarage(population.population_array))) outSheet.write("C" + str(i), str(selectWorst(population.population_array))) generationNumber+=1 i+=1 outWorkbook.close()
def iteration(self, i): parents = range(self.__nrIndividuals) #two parent => one child nrChildren = len(parents) // 2 #generate the population of offsprings offspringPopulation = Population(nrChildren) #create the offsprings for i in range(nrChildren): #random indexes for the parents crossover = False while not crossover: i1 = random.randint(0, self.__nrIndividuals - 1) i2 = random.randint(0, self.__nrIndividuals - 1) #select parents if (i1 != i2): crossover = True #combine parents parent1 = self.population.individuals[i1] parent2 = self.population.individuals[i2] offspringPopulation.individuals[i] = Chromosome.crossover( parent1, parent2, self.probability_crossover) #mutate offspring offspringPopulation.individuals[i].mutate( self.probability_mutate) #evaluating the offspring population offspringPopulation.evaluate(self.inputTrain, self.outputTrain) #we add the population of children to the population of parents self.population.reunion(offspringPopulation) #select tot nrIndividuals from the new population, i.e. only the best individuals survive to the next generation self.population.selection(self.__nrIndividuals)
def start(self): filename = "in.txt" probability = 0.01 populationSize = 50 noOfIterations = 1000 problem = Problem(filename) A = problem.getA() subsets = problem.getSubsets() # print(A, subsets) individSize = len(A) individ = Individ(individSize, A, A, subsets) population = Population(populationSize) population.computePopulation(A, individSize, subsets) algorithm = Algorithm(problem, population) graded, fitnessOptim, individualOptim, avgfitness = algorithm.run( noOfIterations, probability, individ) print('Result:\n After %d iterations \n Fitness Optim: %d' % (noOfIterations, fitnessOptim)) print(" Individual Optim:" + str(individualOptim)) meanValue, standardDeviation = algorithm.statistics() print("Mean Value: " + str(meanValue)) print("Standard Deviation: " + str(standardDeviation)) algorithm.getPlot(avgfitness)
def loadCoords(self,f=None): """loads Coords, creates the corresponding UI elements and the circles for plotting """ default_cluster = self.d.default_cluster self.reset_sample_list() if f is None: f = tkFileDialog.askopenfile(mode='r',initialfile="coords.txt") print f else: f = open( f ) for i,line in enumerate(f): p = Population() p.load_line(line) self.d.add_pop(p) sUI = SampleUIWPop(pop=p, master=self.sample_frame, config = self.c, data=self.d, cluster=default_cluster) sUI.grid(column=0,row=i, sticky="ew") #create plotting circles and register events self.canvas['H'].panel.add_artist( sUI.circH ) self.canvas['Psi'].panel.add_artist( sUI.circP ) sUI.circH.connect() sUI.circP.connect() self.add_sample( sUI ) self.nCoords = len( self.d.sList ) self.activeCanvas.redraw()
def evolve(pop): new_pop = Population(0) #'''Keep The Fittests Chromosomes''' #for i in range(NUMBER_OF_ELITE_CHROMOSOMES): # new_pop.get_chromosomes().append(pop.get_chromosomes()[i]) print("\nCrossover and Mutation Trace:") while new_pop.get_chromosomes().__len__() < POPULATION_SIZE: parent1 = select_tournament(pop) parent2 = select_tournament(pop) child1, child2 = crossover_chromosomes(parent1, parent2) mutate_chromosome(child1) mutate_chromosome(child2) new_pop.get_chromosomes().append(child1) # make sure to not depass the population size if we keep the elite if len(new_pop.get_chromosomes()) < POPULATION_SIZE: new_pop.get_chromosomes().append(child2) new_pop.get_chromosomes().sort(key=lambda x: x.get_fitness(), reverse=True) return new_pop
def make(self, population, newPopulationSize): """ Process population. Winner of a single tournament is excluded from next ones. :param population: :param newPopulationSize: :return: list of selected Units """ units = population.units[:] newUnits = [] for i in range(self.elitismFactor): elite = population.bestUnit(i) newUnits.append(elite) #TODO: verify if this works units.remove(elite) while len(newUnits) < newPopulationSize and len(units): tournamentPopulation = Population() while tournamentPopulation.size < self.tournamentSize and len(units): unit = random.choice(units) tournamentPopulation.addUnitAndExpand(unit) selectedUnit = tournamentPopulation.bestUnit() units.remove(selectedUnit) newUnits.append(selectedUnit) return newUnits
def createInitialPopulation (self): individuals=[]; if self.seedDir == "": #random initialization for i in range(int(self.populationSize)): individuals.append(self.__randomlyCreateIndividual__()); self.population=Population(individuals); else: #initial population based on existing individuals.. Useful for continuing runs that where stopped newerPop=0; ##find which is the newest population for root, dirs, filenames in os.walk(self.seedDir): for f in filenames: if((".pkl" in f) and ("rand" not in f)): tokens=re.split('[_.]',f); popNum=int(tokens[0]); if (popNum>newerPop): newerPop=popNum; input = open(self.seedDir+str(newerPop)+'.pkl',mode="rb"); self.population=Population.unpickle(input); input.close(); maxId=0;##track the maxId for indiv in self.population.individuals: if(indiv.myId>maxId): maxId=indiv.myId; Individual.id=maxId; #the new indiv will start from maxId self.bestIndividualUntilNow=self.population.getFittest(); #set the best individual seen until now self.loopSize=self.bestIndividualUntilNow.getInstructions().__len__(); #ensure that loop Size is correct self.populationsExamined=newerPop+1;#population will start from the newer population self.loadRandstate(); #load the previous rand state before evolving pop self.evolvePopulation(); #immediately evolve population return;
def load_pop(file, wrapped_dict): if file == '/dev/null': pop = None else: pop = Population() pop.from_wrapped_dict(wrapped_dict) return pop
class Game: def __init__(self, width, height): self.delay = 0.0000005 self.screen = [width, height] self.wn = turtle.Screen() self.wn.title("Jump Man Game") self.wn.bgcolor("black") self.wn.setup(width=width, height=height) self.wn.tracer(0) self.roof = Roof(width, height) self.floor = Floor(width, height, self.roof.point) gen = Gen(0, 30, 20) # self.jump_man = JumpMan(screen=self.screen, dna=gen, point=self.floor.point) self.population = Population(screen=self.screen, point=self.floor.point) def move_game(self): self.wn.update() self.population.move_population() def start_game(self): while True: stop = False while not stop: self.move_game() if self.population.all_alive(): self.population.generate_children() stop = True
def __init__(self, pop_size=10, mutation_rate=0.05, mutation_scale = 0.3, generations=10): self.pop_size = pop_size self.generations = generations self.mutation_rate = mutation_rate self.mutation_scale = mutation_scale self.pop = Population(pop_size, mutation_rate, mutation_scale) self.emulator = emulator.Emulator()
def __init__(self, simNum): self.simNum = simNum self.numTimePeriods = 100 self.logInteractions = True self.popSize = 100 #Size of the population self.minFam = 2 self.maxFam = 6 self.igConnectLow = 2 self.igConnectHigh = 5 self.xConnects = round(.2 * self.popSize) self.intsPerTime = .2 # interactions as a proportion of the population per time period self.meanPosVal = 5 #Mean value of an interaction self.meanAvoidVal = 0 #Mean value of avoiding an interaction self.disRisk = .05 #Probability of being a disease carrier at the start of the simulation) self.immuneProb = .05 #Probability of being immune to disease at the start of the simulation self.newDisease = Disease() self.newPop = Population(self.popSize, self.disRisk, self.immuneProb, self.newDisease, self.xConnects, self.minFam, self.maxFam, self.igConnectLow, self.igConnectHigh) self.intLog = [] self.totalInts = 0 self.timeLog = [] self.startTime = None self.endTime = None self.timePerInt = None self.runTime = None self.runVals = None
def main(self): herd = Population(30) selection = SelectionStrategies() recombination = RecombinationStrategies() reinsertion = ReinsertionStrategies() herd.main() generations = 100 # Display the first generation print "Generation 1" # for individual in range(1, len(herd.population)): # print '--> ' .join(herd.population[individual]), # print ' = ',herd.objective_values[individual], 'km' x = herd.objective_values population = herd.population for count in range(generations): population,x = selection.sort_by_fitness(population,x) parent1, parent2 = selection.tournament(population, x) child1,child2 = recombination.crossover(parent1, parent2) fitness_of_child1 = herd.get_total_distance(child1, herd.city_names, herd.routes) fitness_of_child2 = herd.get_total_distance(child2, herd.city_names, herd.routes) population,x = reinsertion.tournament(child1, child2, population, x, fitness_of_child1, fitness_of_child2) print "Generation ",count +2 for individual in range(len(herd.population)): # print '--> ' .join(population[individual]), # print ' = ',x[individual], 'km' print ' ',x[individual], print
def genetic_algorithm(tournament_size=TOURNAMENT_SIZE, crossover_rate=CROSSOVER_RATE, mutation_rate=MUTATION_RATE, population_size=POPULATION_SIZE): task = read(input_file=OUTPUT_FILE) population = init_population(NUMBER_OF_ITEMS, population_size) best_ind = [] i = 0 new_pop_val = [] while i < ITERATIONS: # print(i) j = 0 new_pop_arr = [] while j < population_size: parent1 = population.tournament(tournament_size, task) parent2 = population.tournament(tournament_size, task) child = crossover(parent1, parent2, crossover_rate) mutated_child = mutate(child, mutation_rate) new_pop_arr.append(mutated_child) j += 1 population = Population(new_pop_arr) i += 1 best_from_pop = population.tournament(population_size, task) best_evaluated = best_from_pop.best_individual(task) new_pop_val.append(best_evaluated) return new_pop_val
def __init__(self, pSettings): self.settings = pSettings self.population = Population(self.settings.mu, self.settings.sigma, self.settings.size_x, self.settings.size_y, self.settings.maxIndividuals) self.population.initialize_population()
def statistics(self, noRuns): # Initialize population self.population = Population(self.popSize, self.problem) # Chose the best fitness from population l = [max([i.fitness() for i in self.population.individs])] # Makes a list with best fitness for each generation after each iteration for _ in range(0, self.noGen): self.iteration() l.append(max([i.fitness() for i in self.population.individs])) plt.plot(l) plt.show() l.clear() # It runs the AI 'noRuns' times for i in range(0, noRuns): print(str((i / noRuns) * 100) + "%") # Refresh the population self.population = Population(self.popSize, self.problem) # Pick the best l.append(self.run()) print("100% done") print("Best solution:", max(l)) print("Average solution:", mean(l)) print("Standard deviation:", stdev(l))
def __init__(self): pygame.init() self.Backgrounds = [ 'Sky.png' ] #'WinterMountain.png', 'Mountain.png', 'Basic.png' self.gameWidth = 350 self.indexBackground = random.randint(0, len(self.Backgrounds) - 1) self.gameHeight = 500 self.gameDisplay = pygame.display.set_mode( (self.gameWidth, self.gameHeight)) pygame.display.set_caption('FlappyBird') self.background = pygame.image.load( 'Resources\\Backgrounds\\background' + self.Backgrounds[self.indexBackground]) self.fps = pygame.time.Clock() self.score = 0 self.bestScore = 0 self.frameRate = 40 self.population = Population(self.gameWidth, self.gameHeight, layers=[5, 8, 2], mutation=0.05, populationSize=50) # self.bird = Bird(self.gameWidth, self.gameHeight) self.pipes = [ pipes(self.gameWidth, self.gameHeight, 50), pipes(self.gameWidth, self.gameHeight, self.gameWidth + 50) ]
def routineTo(sf, cf): gen = Genetic(sf, cf) fen = fenetre() food = Food(fen) #newFen = newFenTop() #texts = addScoreOnTopWindows(newFen, int(Params.p['sizePop'])) pop = Population(fen, food) pop.setInitialPositions() for i in range(int(Params.p['nbEvol'])): popName = "pop_" + str(i) if i > 0: gen.createNewPopulation(pop) food = Food(fen) pop.setFood(food) pop.setInitialPositions() #newFen[1].itemconfig(newFen[2], text=popName) t = time.time() #while time.time() - t < Params.p['lifeTime']: j = 0 while j < Params.p['lifeTime']: #refreshScores(newFen, texts, pop) pop.routineForPopulation() fen.refreshScreen() j += 1 timeGen = time.time() - t print("Execution time: ", timeGen) savePop(pop, popName = popName) fen.fen.destroy()
def resolver(self): pop = Population(self.popSize, self.dict) gennr = 0 fitnesses = [] while pop.best().fitness() != 0: if gennr < 250: newpop = [pop.best()] for i in range(1, self.popSize): M = pop.selection() F = pop.selection() off = M.xover(F) off.mutate() newpop.append(off) pop.setPop(newpop) print("fitness:", pop.best().fitness(), "generetion: ", gennr) gennr += 1 fitnesses.append(pop.averageFitness()) if gennr > 1000: plt.clf() plt.plot(fitnesses) plt.ylabel("fitness variation") plt.show() break #print(pop.best()) return pop.best()
def evolve_population(population_passed): print("Evolving population...") new_population = Population(population_passed.size(), False) # If Elitism is enabled then copy the best scoring individual to the next generation if Algorithm.Elitism: new_population.individuals.append(population_passed.get_fittest()) elitism_off_set = 1 else: elitism_off_set = 0 #Do crossover over the entire population for i in range(elitism_off_set, population_passed.size()): individual1 = Algorithm.tournament_selection(population_passed) individual2 = Algorithm.tournament_selection(population_passed) new_individual = Algorithm.crossover(individual1, individual2) new_population.individuals.append(new_individual) #Do mutation randomly for i in range(elitism_off_set, population_passed.size()): Algorithm.mutate(new_population.get_individual(i)) #Repair any individuals broken by crossover or mutation for individual in new_population.individuals: individual.genes = fpl.repairteam(individual.genes) for i in range(population_passed.size()): new_population.get_individual(i).reset_score() return new_population
def __tournamentSelection__(self): tournamentIndiv = [] for j in range(0, int(self.tournamentSize)): tournamentIndiv.append( self.population.pickRandomlyAnIndividual(self.rand)) tournamentPop = Population(tournamentIndiv) return tournamentPop.getFittest()
def main(): #Get the sequence to be searched using FitnessCalculator.set_solution(str(raw_input("SEQUENCE: "))) #Define the population pop_size = int(raw_input("Enter population size: ")) elite_option = str(raw_input("Elitism enabled?(y/n): ")) #Elite switch if elite_option == 'y': elitism_enabled = True else: elitism_enabled = False #Create a starting popultation population = Population(pop_size, True) #Generation count generation = 0 evolution = Evolution(elitism_enabled) #Loop until we dont have a solution while population.get_fittest().get_fitness() < FitnessCalculator.get_max_fitness(): generation += 1 print "GENERATION : " + str(generation) + " FITTEST: " + str(population.get_fittest().get_fitness()) #Evolve the population population = evolution.evolve(population) print "SOLUTION FOUND..." print "GENERATION: " + str(generation) print "GENES: " + population.get_fittest().get_string() return
def __init__(self): self.__problem = Problem() self.__dimPopulation = 0 self.__noOfIterations = 0 self.readFromFile() self.__population = Population(self.__dimPopulation) self.__best = []
class Algorithm: def __init__(self, problem, data): self.problem = problem self.data = data self.mutProb = None self.noGen = None self.popSize = None self.readParameters("param.in") self.population = Population(self.popSize, problem) def readParameters(self, fileName): f = open(fileName, "r") self.mutProb, self.noGen, self.popSize = f.readline().split(" ", 3) self.mutProb, self.noGen, self.popSize = float(self.mutProb), int( self.noGen), int(self.popSize) f.close() def iteration(self): # take the 2 best individs. Makes a crossOver, select the best 2 of 3 individ1, individ2 = self.population.select() child = Individ.crossOver(individ1, individ2) child.mutate(self.mutProb) self.population.add( sorted([individ1, individ2, child], key=lambda x: x.fitness(), reverse=True)[:2][:]) def run(self): # Run iterations. Get fitness of best individ for _ in range(0, self.noGen): self.iteration() return max([i.fitness() for i in self.population.individs]) def statistics(self, noRuns): # Initialize population self.population = Population(self.popSize, self.problem) # Chose the best fitness from population l = [max([i.fitness() for i in self.population.individs])] # Makes a list with best fitness for each generation after each iteration for _ in range(0, self.noGen): self.iteration() l.append(max([i.fitness() for i in self.population.individs])) plt.plot(l) plt.show() l.clear() # It runs the AI 'noRuns' times for i in range(0, noRuns): print(str((i / noRuns) * 100) + "%") # Refresh the population self.population = Population(self.popSize, self.problem) # Pick the best l.append(self.run()) print("100% done") print("Best solution:", max(l)) print("Average solution:", mean(l)) print("Standard deviation:", stdev(l))
def __init__(self, problem, data): self.problem = problem self.data = data self.mutProb = None self.noGen = None self.popSize = None self.readParameters("param.in") self.population = Population(self.popSize, problem)
def load_and_check_pop(file, total_pop, name): p = Population() p.from_population_file(file) if not total_pop.is_superset(p): gd_util.die( 'There is an individual in the {0} that is not in the SNP table'. format(name)) return p
def main(): file_path = "dataset.csv" population = Population() population.read_population_from_file(file_path) graph = PopulationGraph(population) graph.plot_graph()
def population(): data = json.loads(request.data) population = Population() for new_cat in data: population.add_cat_from_data(new_cat) next_population = population.breed_population() answer = json.dumps(next_population.to_json()) return answer
def best_score(nbindiv, nbgen, step, methode="Tournoi", alpha=0.59): """ Permet de calculer le score du meilleur individu de la population pour une méthode donnée à partir d'un nombre d'individu et d'un nombre de génération """ pop = Population(seq, nbindiv) return pop.evolve_with_step(nbgen, step, selection_method=methode, alpha=alpha)
def selection(self, pop): #Torneio fitpop = Population(self.size_pop) quantity = random.randint(1, self.size_pop) for i in range(quantity): add = random.randint(0, self.size_pop - 1) fitpop.chromosomes.append(pop.chromosomes[add]) fit = fitpop.Fittest(quantity) return (fit)
def tournamentSelection(self, pop): tournament = Population(self.tourManager, self.tournamentSize, False) for i in range(self.tournamentSize): rand = int(random.random() * self.tournamentSize) tournament.saveTour(i, pop.getTour(rand)) tourFittest = tournament.getFittest() return tourFittest
def do_int_run(pop_size=100, chrom_len=10, co_rate=0.6, mut_rate=0.01, num_gens=5000, fit_thresh=1000000, fit_fun=None): population = Population(0) for i in range(pop_size): population.add_chromosome(make_random_int_chromosome(fit_fun, chrom_len)) myga = GA(population, num_gens, co_rate, mut_rate, fit_thresh, make_random_int_chromosome) return myga.evolve()
def Start(): population = Population(target_string, alphabet, mutation_rate) population.initialize(max_population) fittest_individual = population.max_ind max_fitness = population.max_fitness print("Fittest individual:", fittest_individual.dna) print("With a fitness score of: ", max_fitness) new_population = population.reproduce() return new_population
def __init__(self, label='Confirmed', **kwargs): '''Initialize a population of Known planets, from the NASA Exoplanet archive.''' # set up the population Population.__init__(self, label=label, **kwargs) correct(self) self.saveStandard() # defing some plotting parameters self.color = 'black' self.zorder = -1
def __init__(self, label='KOI', **kwargs): '''Initialize a population of KOI's, from Exoplanet archive.''' # set up the population Population.__init__(self, label=label, **kwargs) correct(self) self.saveStandard() # defing some plotting parameters self.color = 'gray' self.zorder = -1
def tournament_selection(self, population): # Create a new tournament population tournament_population = Population(self.tournament_size, False) for i in range(0, self.tournament_size): # Select a random individual from the pool for breeding qualification index = random.randint(0, population.get_size() - 1) tournament_population.save_individual(i, population.get_individual(index)) # Return the fittest individual from the tournament for breeding return tournament_population.get_fittest()
def routine2(): for i in range(int(Params.p['nbEvol'])): popName = "pop_" + str(i) fen = fenetre() food = Food(fen) pop = Population(fen, food) t = time.time() while time.time() - t < Params.p['lifeTime']: pop.routineForPopulation() fen.refreshScreen() fen.fen.destroy() savePop(pop, popName = popName)
def tournament_selection(population_passed): #Tournament pool tournament = Population(Algorithm.Tournament_size, False) """ Tournament selection technique. How it works: The algorithm choose randomly five individuals from the population and returns the fittest one """ for i in range(Algorithm.Tournament_size): random_id = int(random() * population_passed.size()) tournament.individuals.append(population_passed.get_individual(random_id)) fittest = tournament.get_fittest() return fittest
def routine(): #create the windows fen = fenetre() #create the food food = Food(fen) #create the population pop = Population(fen, food) t = time.time() while time.time() - t < Params.p['lifeTime']: #time.sleep(0.01) pop.routineForPopulation() fen.refreshScreen() fen.fen.destroy() savePop(pop)
def pos_dict(gd_indivs_file, input_type): rv = {} p = Population() p.from_population_file(gd_indivs_file) for tag in p.tag_list(): column, name = tag.split(':') column = int(column) - 1 if input_type == 'gd_genotype': column -= 2 rv[name] = column return rv
def run_GA(P, fitnessOp, mutationOp,VEL_POP, MAX_ITER, ERR_THRESHOLD): fitnessOp.evaluate(P) gen = 0 print "%5d. gen,\t error: %s" %(gen, fitnessOp.minError) while gen < MAX_ITER and fitnessOp.minError > ERR_THRESHOLD: gen += 1 new_P = Population(P.n,0) new_P.addIndividual(fitnessOp.bestIndividual) while new_P.populationSize <VEL_POP: parent1, parent2 = chooseParents(P, fitnessOp) child = crossover(parent1, parent2) mutationOp.mutate(child) new_P.addIndividual(child) P = new_P fitnessOp.evaluate(P) print "%5d. gen,\t error: %s" %(gen, fitnessOp.minError) return fitnessOp.bestIndividual
def main(): args = argsParser() args.parse('args.xml') if args.fitnessFunction == "euclidean" : fitOp = EuclideanDistFit(args.input1, args.input2) elif args.fitnessFunction == "manhattan" : fitOp = ManhattanDistFit(args.input1, args.input2) elif args.fitnessFunction == "minkowski" : fitOp = MinkowskiDistFit(args.input1, args.input2, args.p) elif args.fitnessFunction == "linear" : fitOp = LinearInterpolation(args.input1, args.input2, args.euclF, args.manhF) else : raise "Something went wrong while assigning the fitness function" # if args.selection == "tournament" : selOp = Selection.tournament elif args.selection == "elimination": selOp = Selection.elimination else : raise "Something went wrong while assigning the selection operator" if args.elitism == 0: Selection.setElitism(0) elif args.elitism == 1: Selection.setElitism(1) else : raise "Something went wrong while assigning elitism" crossOp = Crossover.crossover mutationOp = Mutation.mutation if args.batch == 1: p = Population(args.populationSize, fitOp, selOp, crossOp, mutationOp) p.evaluateAll() run (p, args) writeOut(args.outputFile, p) else: for i in range(0, args.batch): print "\nBatch: %d/%d" %(i+1, args.batch) p = Population(args.populationSize, fitOp, selOp, crossOp, mutationOp) p.evaluateAll() run (p, args) writeOutBatch(i+1, p)
def evolve_population(population_passed): print("Evolving population...") new_population = Population(population_passed.size(), False) if Algorithm.Elitism: new_population.individuals.append(population_passed.get_fittest()) elitism_off_set = 1 else: elitism_off_set = 0 #Do crossover over the entire population for i in range(elitism_off_set, population_passed.size()): individual1 = Algorithm.tournament_selection(population_passed) individual2 = Algorithm.tournament_selection(population_passed) new_individual = Algorithm.crossover(individual1, individual2) new_population.individuals.append(new_individual) #Do mutation randomly for i in range(elitism_off_set, population_passed.size()): Algorithm.mutate(new_population.get_individual(i)) return new_population
def __init__(self): self.running = True self.clock = pygame.time.Clock() self.initializeScreen() self.viewPositionX = 0 self.viewPositionY = 0 self.terrain = Terrain(40,40) self.population = Population(self.terrain) self.buildingPopulation = BuildingPopulation(self.terrain) self.powers = PowerPopulation() self.explosionTimer = 0;
def routine4(sf, cf): gen = Genetic(sf, cf) fen = fenetre() food = Food(fen) newFen = newFenTop() texts = addScoreOnTopWindows(newFen, int(Params.p['sizePop'])) pop = Population(fen, food) numPop = startWithChoosenPop(pop) pop.setInitialPositions() for i in range(numPop, numPop+int(Params.p['nbEvol']), 1): popName = "pop_" + str(i) if i > numPop: gen.createNewPopulation(pop) food = Food(fen) pop.setFood(food) pop.setInitialPositions() newFen[1].itemconfig(newFen[2], text=popName) t = time.time() while time.time() - t < Params.p['lifeTime']: refreshScores(newFen, texts, pop) pop.routineForPopulation() fen.refreshScreen() savePop(pop, popName = popName) fen.fen.destroy()
def evolve(p: Population, c: int, s: int, r: int) ->List(float): """ Computes the list of average payoffs over the evolution of population p for c cycles of match_ups with r rounds per match and at birth/death rate of s :param p: Population :param c: Natural :param s: Natural :param r: Natural :return: [float] """ payoffs = [] for i in range(c): p2 = p.match_up(r) pp = p2.payoffs() p3 = p2.regenerate(s) payoffs = payoffs + [relative_average(pp, r)] p = p3 return payoffs
def evolve(self, population): new_population = Population(population.get_size(), False) # Save the best individual for the next generation if elitism is activated if self.elitism: new_population.save_individual(0, population.get_fittest()) # Create Crossovers for i in range(self.elitism_offset, population.get_size()): parent_1 = self.tournament_selection(population) parent_2 = self.tournament_selection(population) child = self.crossover(parent_1, parent_2) new_population.save_individual(i, child) # Create mutants for i in range(self.elitism_offset, new_population.get_size()): self.mutate(new_population.get_individual(i)) return new_population
def __init__(self, simNum): self.simNum = simNum self.numTimePeriods = 50 # number of time periods that a simulation should run self.logInteractions = True # boolean indicating whether to log each interaction during the simulation (set to 'false' for large populations) self.popSize = 1000 #Size of the population self.minFam = 2 # minimum number of agents in each family self.maxFam = 6 # maximum number of agents in each family self.igConnectMin = 2 # minimum number of ingroup (non-family) connections for each agent self.igConnectMax = 5 # maximum number of ingroup (non-family) connections for each agent self.xConnects = round(.1 * self.popSize) # set the number of outgroup connections as a proportion of the total population size self.meanPosVal = 1 # set the average health value change resulting from an interaction self.meanAvoidVal = -1 # set the average health value change resulting from avoiding an interaction self.immuneProb = 0 # set the probability that an agent has natural immunity from disease self.newDisease = Disease() # initialize a disease that can be spread in the poppulation self.newPop = Population(self.popSize, self.immuneProb, self.newDisease, self.xConnects, self.minFam, self.maxFam, self.igConnectMin, self.igConnectMax) # initialize a new population graph using the parameters set above self.intLog = [] # initialize a new interaction log as a list self.totalInts = 0 # initialize the total number of interactions to zero self.timeLog = [] # initialize a new log for summary statistics at each time period self.startTime = None # initialize the variable to hold the system time associated with the start of the simulation self.endTime = None # initialize the variable to hold the system time associated with the end of the simulation self.timePerInt = None # initialize the variable to hold the average time per interaction during the simulation self.runTime = None # initialize the variable to hold the total run time of the simultion self.runVals = None # initialize the variable to hold the log of parameters governing the simulation run
from fpl import fpl # Import the player data from a file fpl.getplayerdata() # Time the algorithm start = time() # Set solution value higher than highest possible score. # Look for the best possible answer FitnessCalc.set_solution(1000) # Create the initial random population my_pop = Population(10000, True) # Loop until number of generations is complete generation_count = 0 while my_pop.fitness_of_the_fittest() < FitnessCalc.get_max_fitness(): generation_count += 1 # Output the best solution every 100 generations if generation_count % 100 == 0: print("Outputting Current Status") my_pop.OutputFittest() # Quit after a set number of generations if generation_count == 500: break
#!/usr/bin/env python import gd_util import sys from Population import Population ################################################################################ if len(sys.argv) != 13: gd_util.die('Usage') input, p1_input, p2_input, input_type, data_source, min_reads, min_qual, retain, discard_fixed, biased, output, ind_arg = sys.argv[1:] p_total = Population() p_total.from_wrapped_dict(ind_arg) p1 = Population() p1.from_population_file(p1_input) if not p_total.is_superset(p1): gd_util.die('There is an individual in population 1 that is not in the SNP table') p2 = Population() p2.from_population_file(p2_input) if not p_total.is_superset(p2): gd_util.die('There is an individual in population 2 that is not in the SNP table') ################################################################################ prog = 'Fst_column' args = [ prog ]
from Population import Population import os pop = Population(200, "To be or not to be, that is the question", 0.2) while (pop.newGen() == False): os.system('cls') pop.display()
column, name = tag.split(':') if p_type == 'gd_genotype': column = int(column) - 2 the_list.append('{0}:{1}:{2}'.format(val, column, name)) ################################################################################ if len(sys.argv) != 11: gd_util.die('Usage') snp_input, snp_ext, snp_arg, cov_input, cov_ext, cov_arg, indiv_input, min_coverage, req_thresh, output = sys.argv[1:] p_snp = load_pop(snp_input, snp_arg) p_cov = load_pop(cov_input, cov_arg) p_ind = Population() p_ind.from_population_file(indiv_input) if not p_snp.is_superset(p_ind): gd_util.die('There is an individual in the population individuals that is not in the SNP/Genotype table') if p_cov is not None and (not p_cov.is_superset(p_ind)): gd_util.die('There is an individual in the population individuals that is not in the Coverage table') ################################################################################ prog = 'mito_pi' args = [ prog ] args.append(snp_input) args.append(cov_input)
input, data_source, output, extra_files_path, ind_arg = sys.argv[1:6] population_info = [] p1_input = None all_individuals = False for arg in sys.argv[6:]: if arg == 'all_individuals': all_individuals = True elif len(arg) > 12 and arg[:12] == 'individuals:': p1_input = arg[12:] elif len(arg) > 11 and arg[:11] == 'population:': file, name = arg[11:].split(':', 1) population_info.append((file, name)) p_total = Population() p_total.from_wrapped_dict(ind_arg) ################################################################################ gd_util.mkdir_p(extra_files_path) ################################################################################ prog = 'coverage' args = [ prog ] args.append(input) args.append(data_source) user_coverage_file = os.path.join(extra_files_path, 'coverage.txt')
def load_and_check_pop(name, file, total_pop): p = Population(name=name) p.from_population_file(file) if not total_pop.is_superset(p): gd_util.die('There is an individual in {0} that is not in the SNP table'.format(name)) return p
chrom = 'all' if het_arg == 'use_installed': loc_path = os.path.join(galaxy_data_index_dir, heterochromatin_loc_file) location_file = LocationFile(loc_path) heterochrom_path = location_file.get_values_if_exists(dbkey) if heterochrom_path is None: heterochrom_path = '/dev/null' elif het_arg == 'use_none': heterochrom_path = '/dev/null' else: heterochrom_path = het_arg population_list = [] p_total = Population() p_total.from_wrapped_dict(ind_arg) if not use_reference: ap1 = load_and_check_pop('Ancestral population 1', ap1_input, p_total) population_list.append(ap1) ap2 = load_and_check_pop('Ancestral population 2', ap2_input, p_total) population_list.append(ap2) if populations == 3: ap3 = load_and_check_pop('Ancestral population 3', ap3_input, p_total) population_list.append(ap3) p = load_and_check_pop('Potentially admixed', p_input, p_total) population_list.append(p)