def main(): mini=np.inf popsize=1100 prob=problem.Problem(fitness_func=problem.katsuura,dim=10,prangetup=(-100,100)) popu=population.Population(prob,size=popsize) popu.randominit() genlim=20000 print(popu.poparr) print("thing starts here") newsel=misc.Selection(3) newcros=misc.Crossover(rate=0.8) #newmuta=misc.Mutation(rate=0.1) mrate=0.2 newterm=misc.Termination(0) print(popu.avg_fitness()) for i in range(genlim): lis=[] if (i==200): print("here it is-----------------------------------------") if (i==5000): print("here it is 500 ------------------------------------") mrate=0.02 #newmuta=misc.Mutation(rate=0.01) popu.set_fitarr() minic=min(popu.fitarr) if mini>minic: mini=minic mininp=popu.poparr[list(popu.fitarr).index(minic)] for tup in newsel.select_parent(popu): child1,child2=newcros.do_crossover(tup) child1=smallstepchange(child1,fac=3,rate=mrate) child2=smallstepchange(child2,fac=3,rate=mrate) lis.append(child1) lis.append(child2) del(popu) arr=np.array(lis) popu=population.Population(prob,poparr=arr,size=popsize) popu.set_fitarr() if np.all(popu.poparr==popu.poparr[0] ): break #these two conditionals have pen-ultimate IMPORTANCE, as my normalization fails heavily if all are same if np.all(popu.fitarr==popu.fitarr[0]): break print(popu.avg_fitness(),i) print(mini,list(mininp)) if newterm.terminate(popul=popu,generationnum=i,generationlim=genlim): print("breaking bad") break print(popu.poparr) print(popu.avg_fitness())
def main(): popsize = 1100 prob = problem.Problem(fitness_func=problem.katsuura, dim=5, prangetup=(-100, 100)) popu = population.Population(prob, size=popsize) popu.randominit() genlim = 2000 print(popu.poparr) print("thing starts here") newsel = misc.Selection(1) newcros = misc.Crossover(rate=0.9) newmuta = misc.Mutation(rate=0.1) newterm = misc.Termination(1) print(popu.avg_fitness()) for i in range(genlim): lis = [] if (i == 200): print("here it is-----------------------------------------") if (i == 500): print("here it is 500 ------------------------------------") for tup in newsel.select_parent(popu): child1, child2 = newcros.do_crossover(tup) child1 = newmuta.mutate(child1, prob.rangetup, switch=1, iteri=i, switchiter=100, factup=(100, 1000)) child2 = newmuta.mutate(child2, prob.rangetup, switch=1, iteri=i, switchiter=100, factup=(100, 1000)) lis.append(child1) lis.append(child2) del (popu) arr = np.array(lis) popu = population.Population(prob, poparr=arr, size=popsize) popu.set_fitarr() if np.all(popu.poparr == popu.poparr[0]): break #these two conditionals have pen-ultimate IMPORTANCE, as my normalization fails heavily if all are same if np.all(popu.fitarr == popu.fitarr[0]): break print(popu.avg_fitness()) if newterm.terminate(popul=popu, iteri=i, lim=500): print("breaking bad") break print(popu.poparr) print(popu.avg_fitness())
def run(self): self.population = population.Population( self.args.population_size, self.args.crossover_rate, self.args.mutation_rate ) for generation in range(self.args.num_generations): print 'Generation {}'.format(generation) fronts = self.population.fast_non_dominated_sort() fronts_serialized = population.Population.serialize_fronts(fronts) self.log.append(fronts_serialized) for rank in fronts: front = fronts[rank] population.Population.calculate_all_crowding_distances(front) offspring_genotypes = self.population.create_offspring() offspring_individuals = [ individual.Individual(genotype_instance) for genotype_instance in offspring_genotypes ] combined_population_individuals = set(self.population.individuals).union(set(offspring_individuals)) combined_population = population.Population( population_size=len(combined_population_individuals), crossover_rate=self.args.crossover_rate, mutation_rate=self.args.mutation_rate, individuals=list(combined_population_individuals) ) new_individuals = set() fronts = combined_population.fast_non_dominated_sort() for rank in fronts: num_more_individuals_needed = self.args.population_size - len(new_individuals) if len(fronts[rank]) <= num_more_individuals_needed: new_individuals = new_individuals.union(fronts[rank]) else: front = fronts[rank] population.Population.calculate_all_crowding_distances(front) front = sorted(front, key=lambda x: x.crowding_distance, reverse=True)[:num_more_individuals_needed] new_individuals = new_individuals.union(front) break self.population = population.Population( population_size=self.args.population_size, crossover_rate=self.args.crossover_rate, mutation_rate=self.args.mutation_rate, individuals=list(new_individuals) )
def __init__(self, goal, w, h, num_poly, num_vertex, comparison_method, savepoints, outdirectory, iterations, pop_size, nmax, mmax): super().__init__(goal, w, h, num_poly, num_vertex, comparison_method, savepoints, outdirectory) self.iterations = iterations self.pop_size = pop_size self.nmax = nmax self.mmax = mmax self.evaluations = 0 self.pop = p.Population(self.pop_size) self.best = None self.worst = None # define data header for hillclimber self.data.append([ "Polygons", "Generation", "Evaluations", "bestMSE", "worstMSE", "medianMSE", "meanMSE" ]) # fill population with random polygon drawings for i in range(self.pop_size): alex = c.Constellation(0, i, None, self.w, self.h) alex.initialize_genome(self.num_poly, self.num_vertex) alex.img_to_array() alex.calculate_fitness_mse(self.goalpx) self.pop.add_organism(alex)
def main(): tf_env = get_tf_env() members = population.create_members(POPULATION_SIZE) hyperparams = FP.PPO_HYPERPARAMS pop = population.Population(members, hyperparams) pbt = pbt_runner.PBTRunner(population=pop, env=tf_env, num_to_evolve=NUM_TO_EVOLVE) pbt.run_pbt(root_dir=root_dir, num_epochs=NUM_EPOCHS, num_env_steps_per_epoch=NUM_ENV_STEPS_PER_EPOCH)
def crossoverPopulation(self, pop): # Create new population newpop = population.Population(pop.size()) # Loop over current population by fitness for popIndex in range(pop.size()): parent1 = pop.getFittest(popIndex) # Apply crossover to this individual? if self.crossoverRate > random.random( ): # and popIndex >= self.elitismCount: # Initialize offspring offspring = individual.Individual( parent1.getChromosomeLength()) # Find second parent parent2 = self.selectParent(pop) # Loop over genome for geneIndex in range(parent1.getChromosomeLength()): # Use half of parent1's genes and half of parent2's genes if 0.5 > random.random(): offspring.setGene(geneIndex, parent1.getGene(geneIndex)) else: offspring.setGene(geneIndex, parent2.getGene(geneIndex)) # Add offspring to new population newpop.setIndividual(popIndex, offspring) else: # Add individual to new population without applying crossover newpop.setIndividual(popIndex, parent1) return newpop
def mutatePopulation(self, pop): # Initialize new population newpop = population.Population(self.populationSize) # Loop over current population by fitness for popIndex in range(self.populationSize): indi = pop.getFittest(popIndex) # Loop over individual's genes for geneIndex in range(indi.getChromosomeLength()): # Skip mutation if this is an elite individual if popIndex > self.elitismCount: # Does this gene need mutation? if self.mutationRate > random.random(): # Get new gene newGene = 1 if indi.getGene(geneIndex) == 1: newgne = 0 # Mutate gene indi.setGene(geneIndex, newGene) # Add individual to population newpop.setIndividual(popIndex, indi) # Return mutated population return newpop
def go(): l = [] for i in range(40): x = random.randrange(70) y = random.randrange(70) l.append([x, y]) t = pop.Tour(l) now = pop.Population(t, 200) ret = now.getfittest() print("at first") ret.print_on_file() print((ret).getdistance()) print("start!!") ga = pop.GeneticAlgorithm(t, mutationrate=0.02, tournamentsize=8) for x in range(100): next = ga.evolve(now) ret = next.getfittest() ret.print() ret.print_on_file() print((next.getfittest()).getdistance()) now = next print("finish")
def run(self): #initialise the population pop1 = pop.Population(self.nb_nodes, self.p_edges, self.nb_graphs, self.pmut, self.coeff) #run the simulation results = [] for x in xrange(max_time): # OR in a second part "while True:" if (x+1)%text_time == 0 : print 'saving population' pop1.save_pop(self.savefile) liste_f = pop1.fitness_list() if max(liste_f) >= lim_fitness : pop1.save_pop() pop1.show_best() return "Found it!" else : for i in range(int(self.qreprod*self.nb_graphs)): nbnewborns = pop1.reproduction() pop1.mutation(nbnewborns) for i in range(int(self.qtty_immi*self.nb_graphs)): pop1.immigration() list_fit = pop1.fitness_list() print x , max(list_fit) , np.mean(list_fit) , list_fit.index(max(list_fit)), pop1.fitness(pop1.graphs[list_fit.index(max(list_fit))],1) results.append([max(list_fit), np.mean(list_fit)]) return results
def run(generations): ''' Runs DHN generations -- number of generations to evolve for ''' pop = population.Population(config) # Run the population under a simple evaluation scheme winner = pop.run(evaluate_xor, generations) cppn = FeedForwardNetwork.create(winner, config) substrate = decode(cppn, input_dimensions, num_outputs, sheet_dimensions) print("WINNER: Genome {0}\n".format(winner.key)) print("Winner Fitness is {0}".format(winner.fitness)) for node in winner.nodes: print("\t{0}: {1}".format(winner.nodes[node].key, winner.nodes[node].activation)) for connection in winner.connections: print("\t{0},{1},{2}".format(connection, winner.connections[connection].weight, winner.connections[connection].enabled)) sum_square_error = 0.0 for inputs, expected in zip(xor_inputs, expected_outputs): print("Expected Output: {0}".format(expected)) actual_output = substrate.activate(inputs)[0] print("Actual Output: {0}".format(actual_output)) sum_square_error += ((actual_output - expected)**2.0) / 4.0 print("Loss: {0}".format(sum_square_error)) draw_net(cppn, filename="dhn_cppn_winner") draw_net(substrate, filename="dhn_substrate_winner") for node in substrate.node_evals: print("Node: \t{0}:".format(node)) for connection in substrate.values: print("Value:\t{0}".format(connection))
def newtest(): indim = 8 outdim = 1 # np.random rng = np.random num_data = 10 # inputarr = np.random.random((num_data, indim)) neter = network.Neterr(indim, outdim, 10, np.random) # ka = np.random.randint(0, 2, (num_data,)) # print(neter.feedforward_ne(chromo)) """ targetarr = np.zeros((num_data,outdim)).astype(dtype = 'float32') for i in range(num_data): targetarr[i,ka[i]] = 1 print("target is ", targetarr) """ """ targetarr = ka.astype('int32') print(targetarr.dtype) inputarr = inputarr.astype('float32') tempchromo = copy.deepcopy(newchromo) arr = newchromo.node_arr newmatenc = tempchromo.convert_to_MatEnc(indim, outdim) newmatenc=copy.deepcopy(newmatenc) newchromo.modify_thru_backprop( indim, outdim, neter.rest_setx, neter.rest_sety) if not newchromo.node_arr == arr: print("failed 1") if not newchromo.dob == tempchromo.dob and not newchromo.node_ctr == tempchromo.node_ctr: print("failed 2") if not len(newchromo.conn_arr) == len(tempchromo.conn_arr): print("failed 3") newnewmatenc = newchromo.convert_to_MatEnc(indim,outdim) for key in newnewmatenc.WMatrix.keys(): if (newnewmatenc.WMatrix[key] == newmatenc.WMatrix[key]).all(): print("failed 5",key) """ popul = population.Population(indim, outdim, 10, 40) # popul.set_initial_population_as_list(indim,1,dob=0) # [item.pp() for item in popul.list_chromo] print(len(popul.list_chromo)) popul.list_chromo[0].do_mutation(1, 1, 1, 8, 1, np.random) # print(popul.list_chromo[0].pp()) print("-----------------------------------------------------------") time.sleep(5) # print(popul.list_chromo[2].pp()) popul.set_objective_arr(neter) print(popul.objective_arr)
def iterate(n_generations, n_agents, bottleneck, max_model_size, save_path=False, num_trial=None, num_epochs=1, shuffle_input=False, optimizer='adam'): # generate all the binary strings of the given length # possible_models is a 2d array, where each row is a model possible_models = util.generate_list_models(max_model_size) # create first generation parent_generation = pop.Population(n_agents, max_model_size) # data is a 3-d numpy array with shape (# gen, # possible models, # agents) data = np.empty(shape=(n_generations + 1, len(possible_models), n_agents)) parent_list = np.empty(shape=(n_generations + 1, n_agents)) parent_list[0, :] = [0] * n_agents for n in range(n_generations): # the new generation is created child_generation = pop.Population(n_agents, max_model_size) # the new generation learns from the old one parents = child_generation.learn_from_population( parent_generation, bottleneck, num_epochs, shuffle_input, optimizer) parent_list[n + 1] = parents # stores some data to be analyzed later! data[n] = util.create_languages_array(parent_generation.agents, possible_models) # the new generation becomes the old generation, ready to train the next generation parent_generation = child_generation print("Done generation {} out of {} \n\n".format(n, n_generations)) # stores the data from the last trained generation data[n_generations] = util.create_languages_array(parent_generation.agents, possible_models) if save_path: if not os.path.exists(save_path): os.makedirs(save_path) np.save(save_path + '/quantifiers', data) np.save(save_path + '/parents', parent_list) return data
def tournamentSelection(pop): tournament = population.Population(Algorithm._tournamentSize, False) for i in range(Algorithm._tournamentSize): randomIndex = int(random.random() * pop.size()) tournament.saveIndividual(i, pop.getIndividual(randomIndex)) fittest = tournament.getFittest() return fittest
def __init__( self, grid, score, grapher ): self.grid = grid self.score = score self.population = population.Population( ) self.currentGeneration = 0 self.currentGenome = 0 self.grapher = grapher self.backupGrid = np.zeros( [ 10, 20 ], dtype=np.uint8 ) self.backupTile = [ 0, 0, 0 ]
def test_scatter_plot(self): p = population.Population(population_size=30, crossover_rate=0.5, mutation_rate=0.5) fronts = p.fast_non_dominated_sort() fronts_serialized = population.Population.serialize_fronts(fronts) plot.Plotter.scatter_plot( fronts_serialized, title='Just a test plot. Nothing to see here.', output_filename='test.png')
def init_random_cities(self, n): self.cities = [] for i in range(0, n): p = self.random_map_point() random_population = population.Population(1311, 3) commodities = [100] * len(self.commodities) name = str(i) + "-city" new_city = city.City(name, p[0], p[1], random_population, commodities) self.cities.append(new_city)
def breed(self, debug=False): children = [] people = self.people synthpop = pop.Population() for i in xrange(0, len(self.people) / 2): if (debug): print("Making child " + str(i) + " out of person:" + str(2 * i) + " and person:" + str(2 * i + 1)) children.append( self.make_child(people[2 * i], people[2 * i + 1], synthpop)) self.children = children
def simulation(): # STILL TO BE DEFINED pop = population.Population(size, initial_rythm_type) data_accumulator = [] for i in range(generations + 1): if (i % report_every == 0): data_accumulator.append(pop.ca_monte_pop(mc_trials)) pop.produce(population, interactions) if method == 'chain': pop = population.Population(size, 'random') pop.learn(data, interactions) if method == 'replacement': population.update() pop.learn(data, interactions) if method == 'closed': pop.learn(data, interactions) # Plot the results return data_accumulator
def newPopulation(offspring, ori_data, m, shape, ori_full_table, obj, weight, size): candidates = [] for syn_data in offspring: candidates.append( individual.Individual(syn_data, ori_data, m, shape, ori_full_table, obj, weight)) new_population = population.Population(ori_data, size, candidates) new_population.populationFitness() return new_population
def run(gens): # Create population pop = population.Population(config) # Gather statistics from population and add that reporter stats = neat.statistics.StatisticsReporter() pop.add_reporter(stats) pop.add_reporter(neat.reporting.StdOutReporter(True)) # Run your population under some evaluation scheme for a number of generations winner = pop.run(eval_fitness, gens) print("dhn_xor done") return winner, stats
def openSimulation(self, event): game = self.createGame() size = int(self.tc_size.GetValue()) life_span = int(self.tc_lifeSpan.GetValue()) density = float(self.tc_density.GetValue()) self.population = population.Population(game, size, life_span=life_span, density=density) self.population.generate() PopulationVisualizerFrame(None, 'ESS', self.population, float(self.tc_speed.GetValue()))
def test_view(): # G = nx.random_graphs.watts_strogatz_graph(2000, 100, 0.3) G = nx.random_graphs.barabasi_albert_graph(10, 2, 1) print G.degree print G.degree[1] print G.degree[2] import population P = population.Population(G) print P.degree P.add_edge(13, 1) print P.degree[1] print P.degree[2]
def main(): # Initialize gen = 1 pop = popu.Population([]) while gen < MAX_GEN: children = [] # Print statistics of population print("Generation : {}".format(gen)) pop.statistics() # Get elites elites = pop.get_elites() # Get parents parents = pop.get_parents() # Make children children = pop.get_children(parents.copy()) # Make next population next_pop = children.copy() for elite in elites: next_pop.append(elite) # Make new population new_pop = popu.Population(next_pop.copy()) pop = new_pop gen += 1 # Termination code here print("\n\n\n\n") print("Done!") print("Generation : {}".format(gen)) pop.statistics() return gen
def test_non_dominated_individuals(self): p = population.Population(population_size=30, crossover_rate=0.5, mutation_rate=0.5) fronts = p.fast_non_dominated_sort() self.assertGreaterEqual(len(fronts[1]), 1) num_individuals = 0 for rank in fronts: num_individuals += len(fronts[rank]) self.assertEqual(num_individuals, len(p.individuals))
def initialize(self, n_in, n_out, pop_size=100, folder=None, delta_t=1., c1=1., c2=1., c3=0.5, desired_species=1, min_species=1, p_weight_mut=0.4, p_weight_random=0.02, weight_mut_sigma=0.3, node_mut_rate=0.05, edge_mut_rate=0.05, p_child_clone=0.02, p_mutate=0.8, p_inter_species=0.02, weight_amplitude=1.): self.generation = 1 self.n_in = n_in self.n_out = n_out prototype = genome_mod.Genome(self.n_in, self.n_out) self.population = population.Population( [deepcopy(prototype) for _ in range(pop_size)], delta_t=delta_t, c1=c1, c2=c2, c3=c3, desired_species=desired_species, min_species=min_species, p_weight_mut=p_weight_mut, p_weight_random=p_weight_random, weight_mut_sigma=weight_mut_sigma, node_mut_rate=node_mut_rate, edge_mut_rate=edge_mut_rate, p_child_clone=p_child_clone, p_mutate=p_mutate, p_inter_species=p_inter_species, weight_amplitude=weight_amplitude) self.population = self.population.generate_offspring() #self.population = population.Population([genome_mod.Genome(self.n_in, self.n_out) for _ in range(pop_size)]) if folder is not None: if not os.path.exists(folder): os.makedirs(folder) else: folder = "" self.folder = folder + "/" self.best_genome = None
def generateTrialPopulation(self, np): """ 生成重组后的种群,种群数量np Create a trial population (size np) from an existing population. Return a population object. """ trialMembers = [] for i in range(np): trialMember = self.generateTrialMember(i) # Bring the trial member back into the feasible region if necessary. if self.absoluteBounds: # absoluteBounds设置为True,则范围在限定范围外的个体将被“纠正” trialMember.constrain(self.minVector, self.maxVector) trialMembers.append(trialMember) return population.Population(members=trialMembers)
def solve(self, min_fitness, max_epochs): if min_fitness is None and max_epochs is None: return 0, 0, None initial_population = p.Population(self._population_size, chromosome_size=8) simulator = gs.GeneticSimulator(initial_population, self._cross_prob, self._mut_prob) while not simulator.is_end(max_epochs, min_fitness): simulator.step() #print(simulator.state) return simulator.best_result.fitness, simulator.epoch_num, simulator.best_result
def __init__(self, listTask, nInd, pMutation, set_of_city): self.set_of_city = set_of_city self.listTask = listTask self.nInd = nInd self.population = pp.Population(nInd, listTask) self.pMutation = pMutation self.iteration = 0 self.crossover = 0 self.mutation = 0 for i in listTask: maxdi = listTask[0].dimension if i.dimension > maxdi: maxdi = i.dimension self.pop_dimension = maxdi
def init_population_object(): """ Description --- initialize a population object to be used by subsequent tests """ sample_nondominated_population = population.Population() assert type(sample_nondominated_population) is population.Population #fill the population with randon individuals for individuals in range(np.random.randint(low=2, high=100)):#random population size from 2 to 100 ind = np.random.normal(loc=10, scale=2.0, size=3)#random individual #todo: verify sample_nondominated_population.append(ind) return sample_nondominated_population
def main(): Num_city = 50 corrd = [[random.uniform(0, 10), random.uniform(0, 10)] for idx in range(Num_city)] adj_matrix = [[ o_dis_func(corrd[idx1], corrd[idx2]) + 10 \ for idx1 in range(Num_city)] for idx2 in range(Num_city)] Num_unit = 10000 route_init = [idx for idx in range(Num_city)] popul = population.Population(Num_unit, route_init, 0.7, 0.001) popul.revolution(adj_matrix, 1000) print(popul.__population_gene__()) return