def evolve_model(evolve_population_size=10, evolve_recombinate_count=5, evolve_generation_count=10): evolution = Evolution.Evolution() evolution.init_population(evolve_population_size) evolution.evaluate_population() print(f"Original population: {evolution.population}") print(f"Original evaluation: {evolution.evaluation}") for generation in range(evolve_generation_count): offsprings = [] for recombinate_index in range(evolve_recombinate_count): parent1, parent2 = evolution.get_parents() offspring1, offspring2 = evolution.recombinate(parent1, parent2) size1 = Evolution.get_model_encoding(offspring1) if size1 < 32 * 32: print( f"New individual obtained by recombination with size {size1} - {offspring1}." ) offsprings.append(offspring1) size2 = Evolution.get_model_encoding(offspring2) if size2 < 32 * 32: print( f"New individual obtained by recombination with size {size2} - {offspring2}." ) offsprings.append(offspring2) mutated = Evolution.mutate(offsprings) evolution.combine_generations(mutated) evolution.set_new_population() evolved_autoencoder = evolution.get_best_individual() return evolved_autoencoder
def get_output(probability): feature_name = probability_selector(probability) input_init = inputs.Input(probability, feature_name=feature_name) duration = input_init.get_duration() input_init.delete_duration() input_init.normalize() tra_feature, tra_label, vaildation_feature, vaildation_label, test_feature, test_label = input_init.data_generator( ) vaild_list = input_init.vaild_list vaild_dur = [] for vaild_num in vaild_list: vaild_dur.append(duration[vaild_num]) optimal_net = ep.evolve(30, 1, tra_feature, tra_label, vaildation_feature, vaildation_label, test_feature, test_label, type='random') w, b, e, r, predict, test = ep.Evolution().network_optimizer(tra_feature, tra_label, test_feature, test_label, optimal_net, 18600, final=True) print(vaild_dur) return e, predict, test, vaild_dur
def runModel(): allCP = int(AllCEntry.get()) allDP = int(AllDEntry.get()) TFTP = int(TFTEntry.get()) numOfTournaments = int(numofTEntry.get()) allC = Agent(1, 1, 1, "All-C") allD = Agent(0, 0, 0, "All-D") TFT = Agent(1, 1, 0, "T-F-T") testPopulation = [{ "agent": allC, "count": allCP }, { "agent": TFT, "count": TFTP }, { "agent": allD, "count": allDP }] evolution = Evolution(allCP, allDP, TFTP) tempAgentCounts = evolution.run(testPopulation, numOfTournaments) for n in range(0, numOfTournaments + 1): lineDataC.set_xdata(evolution.round_history[0:n + 1]) lineDataC.set_ydata(evolution.C_history[0:n + 1]) lineDataD.set_xdata(evolution.round_history[0:n + 1]) lineDataD.set_ydata(evolution.D_history[0:n + 1]) lineDataTFT.set_xdata(evolution.round_history[0:n + 1]) lineDataTFT.set_ydata(evolution.TFT_history[0:n + 1]) # also points! axes.plot(evolution.round_history[n - 1], evolution.C_history[n - 1], color="red", marker="o") axes.plot(evolution.round_history[n - 1], evolution.D_history[n - 1], color="blue", marker="o") axes.plot(evolution.round_history[n - 1], evolution.TFT_history[n - 1], color="green", marker="o") canvas.draw()
def __init__(self): self.game = None; self.MAX_ITERATIONS = 80 self.POP_SIZE = 20 self.INITIAL = 1 self.hidden_layer1 = 5 self.hidden_layer2 = 2 self.inputs = 11 self.gene_number = self.hidden_layer1*self.hidden_layer2+self.hidden_layer1*self.inputs + self.hidden_layer2 + self.hidden_layer1 + self.hidden_layer2 + 1 self.pop,self.labels = Evolution.create_initial_population(self.POP_SIZE*self.INITIAL,self.gene_number) # self.pop[:] = [[-3.57186],[0.34468494],[-0.44975404],[0.37229567],[-0.63908 ], # [-1.88027692],[-0.74647466],[ 1.25289468],[-1.1205533],[-0.00261427],[0]] print(self.pop.shape) # self.pop[0,:] = -8 # self.pop[3,:] = 8 self.nnets = NNets(self.inputs,self.hidden_layer1,self.hidden_layer2) self.scores = [] print('Bot Created') self.gen_scores = [] self.gen_scores_save = [] self.all_scores=[] self.pop_index = 0 self.iteration_index = 0 self.weight = self.pop[:,self.pop_index] [first,second,out,bias1,bias2,bias3] = self.seperate_weights(self.weight) self.nnets.set_weights_bias(first,second,out,bias1,bias2,bias3) # print(self.weight) self.new_gen = False
def __init__(self): self.game = None self.MAX_ITERATIONS = 80 self.POP_SIZE = 10 self.INITIAL = 1 self.gene_number = 11 self.pop, self.labels = Evolution.create_initial_population( self.POP_SIZE * self.INITIAL, self.gene_number) # self.pop[:] = [[-3.57186],[0.34468494],[-0.44975404],[0.37229567],[-0.63908 ], # [-1.88027692],[-0.74647466],[ 1.25289468],[-1.1205533],[-0.00261427],[0]] # self.pop[:] = [[-0.53854854], [-1.60903557], [1.56770598], [-2.28885673], [0.83760923], [0.53685226], # [-1.75321933], [1.45448524], [ 0.14393141],[ -0.44144691], [ 0.82662996]] self.pop[:] = [[-0.7729166], [-1.66007687], [1.43303584], [-3.48686149], [0.63306077], [0.09769052], [-2.11997579], [0.80672387], [-0.06324216], [-0.64053525], [0.22088197]] self.pop[:] = [[-0.84876553], [-0.95773762], [1.4080699], [-2.32832832], [1.30429547], [-1.43197305], [-0.63502829], [1.50546105], [-0.12530199], [-1.70731413], [-1.01129018]] print(self.pop.shape) # self.pop[0,:] = -8 # self.pop[3,:] = 8 self.scores = [] print('Bot Created') self.gen_scores = [] self.gen_scores_save = [] self.all_scores = [] self.pop_index = 0 self.iteration_index = 0 self.weight = self.pop[:, self.pop_index] # print(self.weight) self.new_gen = False
def next_gen(self): name_score = 'scores_of_gen' + str(self.iteration_index) np.save(name_score, self.gen_scores_save) self.new_gen = True if self.iteration_index == 0: print('New generation : ', self.iteration_index, ' . Best of previous gen : ', np.max(self.gen_scores), ' .Average of generation : ', np.mean(self.gen_scores)) self.iteration_index += 1 self.pop, self.labels = Evolution.create_next_gen_hard( self.gen_scores, self.pop, 1 / self.INITIAL, self.labels) # self.pop,self.labels = Evolution.create_next_gen(self.gen_scores,self.pop,self.labels) self.pop_index = -1 #self.all_scores = np.append(self.all_scores,self.gen_scores,0) self.gen_scores = [] self.gen_scores_save = [] self.next_agent() elif self.iteration_index < self.MAX_ITERATIONS: print('New generation : ', self.iteration_index, ' . Best of previous gen : ', np.max(self.gen_scores), ' .Average of generation : ', np.mean(self.gen_scores)) self.iteration_index += 1 self.pop, self.labels = Evolution.create_next_gen( self.gen_scores, self.pop, self.labels) self.pop_index = -1 self.all_scores = np.append(self.all_scores, self.gen_scores, 0) self.gen_scores = [] self.gen_scores_save = [] if self.iteration_index % 5 == 0: name = 'scores' + str(self.iteration_index) np.save(name, self.all_scores) name_genes = 'genes' + str(self.iteration_index) np.save(name_genes, self.pop) name_score = 'scores_for_gen' + str(self.iteration_index) np.save(name_score, self.gen_scores) self.next_agent() else: np.save('scores', self.all_scores) while True: i = 1
def simulateEvolution(numclones, humanGenome, binsize, mutations): # clonalwgd, clonalwcl, clonalcam, clonalfocal, subclonalwgd, subclonalwcl, subclonalcam, subclonalfocal = mutations evolution = Evolution.RandomTree(n=numclones, humanGenome=humanGenome, binsize=binsize) sublocations = locateSubclonal(clones=evolution.clones, mutations=mutations) mutate(clone=evolution.root, mutations=mutations, sublocations=sublocations) return evolution
def evolve(population, generation, screen_size): flat_pop = [] for creature_set in population: flat_pop += creature_set new_flat_pop = Evolution.evolve_creatures(flat_pop, mutation_rate, generation, sizes, screen_size) new_pop = [] for i in range(num_groups): creature_set = [] for j in range(creatures_per_group): creature_set.append(new_flat_pop[creatures_per_group * i + j]) new_pop.append(creature_set) return new_pop
def main () : population_size = 100 N = 10 k = 6 p = 0.99 lamda = [0,1,1] number_of_neighbors = 25 number_of_generation = 100 mut_prob = 1./N seed = 1000 landscape = Landscape.Landscape(N,k,seed,p) evolution = Evolution.Evolution(landscape,population_size, 1, number_of_neighbors,Archive.Archive(10,""), N) mth = ["None","N","R"] for i in range(3): print " =====================================================================" archive = Archive.Archive(10,mth[i]) evolution.archiving = archive #evolution.lamda = lamda[i] history = evolution.run(number_of_generation,mut_prob) maxs = [ ] for gen in history : values = [genotype.fitness for genotype in gen] maxs.append(numpy.max(values)) plt.plot(maxs, label=r"$method = $" +str(mth[i])) plt.xlabel("Generation") plt.ylabel("Max Fitness") plt.title("Novelty Vs Fitness") plt.legend(loc="lower right", shadow=True, fontsize='12') plt.show()
def compare(n): t = time.time() #generte the BinImages from the same random image im2 = gen2.randomImage(n) im1 = Image1.BinImage(deepcopy(im2.image), False, True) evol1 = Evol1.Evolution(im1) evol2 = Evol2.Evolution(im2) t1 = time.time() print("\ngeneration of an image with ", n, " pixels : ", t1 - t, " seconds") algo1.algo1(evol1) t2 = time.time() print("first algorithm : ", (t2 - t1), " seconds") print(" ", (evol1.getNbActions()), " actions") algo2.algoB4W8(evol2) print("second algorithm : ", (time.time() - t2), " seconds") print(" ", (evol2.getNbActions()), " actions") return (evol1.getNbActions(), evol2.getNbActions())
def world(no_worlds, days, pop_density): pop_series = [] for p in pop_density: pop_series.append([]) for ps in range(len(pop_series)): for i in range(days): pop_series[ps].append(0) #Add pop series from many worlds for k in range(no_worlds): if k % 10 == 0: print("World ", k) ptypes = [ Strategy.ALLC, Strategy.ALLD, Strategy.Random, Strategy.GRIM, Strategy.TFT, Strategy.TTFT, Strategy.TFTT, Strategy.STFT, Strategy.PAVLOV ] game_para = [0.5, 0, 1, 0.2] total_turns = 20 total_res = 1000 r = Evolution.Replicator(game_para, total_turns, total_res, ptypes, copy.deepcopy(pop_density)) tempps = r.play_days(days) for ps in range(len(pop_series)): for d in range(days): pop_series[ps][d] += tempps[ps][d] #Take average of all worlds for ps in range(len(pop_series)): for d in range(days): pop_series[ps][d] /= no_worlds plot(pop_series, ptypes, game_para, no_worlds)
from Tools import * from Scenario import * from NSGA import * from Evolution import * import matplotlib.pyplot as plt tool_box = Tools() flow_data = tool_box.read_flow_data_from_txt() loc_data = tool_box.read_loc_data_from_txt() time_data = tool_box.read_slot_data_from_txt() scenario = Scenario(flow_data, loc_data, time_data) # scenario.generate_initial_solution() print 'scenario generated' problem = NSGA_problem(scenario) evolve = Evolution(problem, 50, 100) selected_individuals = evolve.evolve() f = open('gene.txt', 'w') for i in selected_individuals: s = '' for g in i.features: s = s + ',' + str(g) f.write(s + '\n') f.close() x = [problem.f1(i) for i in selected_individuals] y = [problem.f2(i) for i in selected_individuals] print x, y plt.plot(x, y, 'ro') plt.show()
if (__name__ == '__main__'): parser = argparse.ArgumentParser(description='Genetic programming engine') parser.add_argument( '-test', dest='should_test', help='Predict single test sample using defined predictor function', action='store_true') args = parser.parse_args() root = os.path.dirname(os.path.realpath(__file__)) config = Config.Configuration() reset_storage(root) #X_train, y_train, X_val, y_val = Datasets.load(name = 'Random_Walk_With_Mommentum', config = config, root = root) #X_train, y_train, X_val, y_val = Datasets.load(name = 'Bitcoin_USD', config = config, root = root) X_train, y_train, X_val, y_val = Datasets.load( name='North_Carolina_Weather', config=config, root=root) if (args.should_test): print(' & '.join(['{:<.2f}'.format(x[0]) for x in X_train[0].tolist()])) print(X_train[0], y_train[0], test_predict(X_train[0], len(X_train[0]))) exit(0) evolution = Evolution.Evolution(root=root, config=config, X_train=X_train, y_train=y_train, X_val=X_val, y_val=y_val)
def setUp(self): "before each test" evol = Evolution.get_evolution("NoEvolution") self.pop = Evolution.SourcePopulation(Evolution.cosmology, evol)
S=['G0|52', [[(np.array([ 0.35 , 0.352]), 'l'), (np.array([ 0.15, 1.02]), 'f'), (np.array([ 0.8 , 0.52]), 'yf')], np.array([[0, 3, 4], [3, 0, 4], [4, 4, 0]])]] S =gen.random_structure(5,4) POP = gen.new_pop(simdata.halfpopulationsize * 2,4) print 'Breeding...' print 'Estimated time: ' + str(simdata.number_of_generations*simdata.halfpopulationsize*0.0161557520459/8.0) + ' s' generation = 0 for j in range(simdata.number_of_generations): #Breeding structures generation += 1 print 'Generation ' + str(generation) fPOP= rt.rated_pop(POP) fPOP.sort(key = lambda x: (-x[1][1],x[1][2]) ) sorted_pop = [copy.deepcopy(i[0]) for i in fPOP] POP = evol.remove_lowest(sorted_pop) POP =evol.refill_pop(POP,generation) print fPOP[0] S = fPOP[0][0] #take the supposetly best structure mod_graph(S) print 'Done' ########################################Yields################################# print rt.fitness(S) print S A=st.node_eq_mat(S) # for n=3 timing is 'good': 3 microsec B = np.linalg.inv(A) # 100 microsec //
from Evolution import * """ __author__ = Simon Hofmann" __credits__ = ["Simon Hofmann", "Katja Abramova", "Willem Zuidema"] __version__ = "1.0.1" __date__ "2016" __maintainer__ = "Simon Hofmann" __email__ = "*****@*****.**" __status__ = "Development" """ # Simulation of Evolution e1 = Evolution(simlength=5000) # os.listdir('poplists') filename = None # "sim5000.mut0.02.Gen12001-15000(Fitness 24.45)" # Filename starts with "sim..." if filename != "" and isinstance(filename, str): e1.reimplement_population(filename=filename, plot=False) print("File implemented:", e1.filename) n_gen = generation_request() print("Run Evolution from Generations {}-{}".format(e1.generation, e1.generation+n_gen)) e1.run_evolution(generations=n_gen, mutation_var=.25, complex_trials=True, fit_prop_sel=False, position_agent=[50, 50], angle_to_target=np.pi/2, distance_to_target=30) # mutation rate default 0.01 # Plot current file: # e1.reimplement_population(filename=filename, plot=True)
# -*- coding: utf-8 -*- """ Created on Tue Feb 18 15:11:51 2020 @author: nbarl """ import BinImage import Evolution from generation import randomImage from algo2 import findP, B4W8kinterchange, algoB4W8 image_test = [[0,0,0,0], [0,0,0,0], [0,1,1,0]] #im = BinImage.BinImage(image_test, False, True) im = randomImage(40) evol = Evolution.Evolution(im) algoB4W8(evol) evol.createGif("B4W8.gif", 100) print(evol.getNbActions())
# -*- coding: utf-8 -*- """ Created on Sat Oct 29 21:27:45 2016 @author: Alon """ import Evolution as Evo Ev = Evo.Evolution(usePrints=True, populationSize=30, numOfEvolutionSteps=10) Ev.run()
#print(evol.getNbActions()) """ #%% analyse complexité nbIter = 3 ns = [5,10,20,30,50,65] value = [] for n in ns : listOfValues = [] for i in range(nbIter) : print("generating...") image = generation.randomImage(n) evol = Evolution.Evolution(image) print("solving") algo1(evol) listOfValues.append(evol.getNbActions()) print(n, " pixels : ", evol.getNbActions(), " actions.\n") value.append(sum(listOfValues) / nbIter) plt.figure() plt.xlabel('nb of pixels') plt.ylabel('nb of exchanges') plt.title('complexity of the first algorithm') plt.plot(ns, value) plt.show()
import matplotlib.pyplot as plt if len(sys.argv) != 10: print("Неверное кол-во параметров") N = int(sys.argv[1]) b = float(sys.argv[2]) wa = float(sys.argv[3]) wc = float(sys.argv[4]) Emin = int(sys.argv[5]) Emax = int(sys.argv[6]) dt = float(sys.argv[7]) HPLANKS = float(sys.argv[8]) CNTSteps = int(sys.argv[9]) # 6.62606957e-27 Hforsize = Hamiltonian.makeHamiltonian(False, N, b, wa, wc, Emin, Emax, 1) R = Evolution.generateDensityMatrix(Hforsize.shape[0]) g = Evolution.cmpGen(R, dt, HPLANKS, N, b, wa, wc, Emin, Emax) results = [] for i in range(CNTSteps): results.append(next(g)) xAxis = [i for i in range(CNTSteps)] plt.plot(xAxis, results, '-b') plt.show() # print(results) # print(xAxis)
import Evolution import Hamiltonian import sys import matplotlib.pyplot as plt N = 5 wa = 0.0006 Emin = 0 Emax = 5 dt = 0.0001 HPLANKS = 1 CNTSteps = 10000 Hforsize = Hamiltonian.makeHamiltonian(False, N, 0, 0, 0, Emin, Emax, 1) R = Evolution.generateDensityMatrix(Hforsize.shape[0]) tests = [(0.0001, 1000), (0.0001, 100), (0.0001, 10), (0.0001, 1), (0.0001, 0.1)] # tests = [(1, 10000000), (0.0001, 0.1)] xAxis = [k for k in range(CNTSteps)] for i in range(len(tests)): g = Evolution.cmpGen(R, dt, HPLANKS, N, tests[i][0], wa, tests[i][1], Emin, Emax) results = [] for j in range(CNTSteps): results.append(next(g)) plt.plot(xAxis, results, label='b/(h*wc) =' + str(tests[i][0]/(tests[i][1]*HPLANKS))) plt.xlabel('steps') plt.ylabel('mse')
from Evolution import * e = Evolution() e.iniExperiment()
def setUp(self): "before each test" self.evol1 = Evolution.get_evolution("NoEvolution") self.evol2 = Evolution.get_evolution("HB2006SFR")
def test_get_evolution(self): with self.assertRaises(NotImplementedError): Evolution.get_evolution("Test")
# -*- coding: utf-8 -*- """ Created on Wed Mar 1 12:56:34 2017 @author: Alon """ import DNAexample as dna import Evolution as Evo Ev = Evo.Evolution(dna,usePrints=True,populationSize=20,numOfEvolutionSteps=100) Ev.run()
def main(): a = Evolution(False) a.Calculate()
max_fit = c.nom max_fit_foods = c.num_foods_eaten best_creature = c.ID num_foods_eaten += c.num_foods_eaten print ('GENERATION', str(generation)) print ('Fittest creature:', best_creature) print ('Max fitness:', max_fit) print ('Average fitness:', tot_fit / length) print ('Number of foods eaten total:', num_foods_eaten) print ('Foods eaten by fittest creature:',max_fit_foods) print () flatten = [] for i in tests: flatten += i new_tests = Evolution.evolve_creatures(flatten, mutation_rate, generation) tests = [] for i in range(6): c = [] for j in range(10): c.append(new_tests[10*i + j]) tests.append(c)
def preprocessing_data(x): avg = np.average(x, axis=0) m = np.min(x, axis=0) M = np.max(x, axis=0) return [avg, avg - m, M - avg] exp_h_fmax = [] exp_h_favg = [] exp_h_div = [] if __name__ == '__main__': fp = open("checkpoint.txt", "w+") #file pointer for e in range(config.NUMBER_OF_EXPERIMENTS): ea = Evolution(nn_layer) ea.evolution(verbose=False, exp=e, fp=fp) exp_h_fmax.append(ea.h_fmax) exp_h_favg.append(ea.h_favg) exp_h_div.append(ea.h_div) print('Experiment %d done' % (e)) fp.close() x = np.arange(ea.num_gen) exp_h_fmax = preprocessing_data(exp_h_fmax) y = exp_h_fmax[0].tolist() yl = exp_h_fmax[1].tolist() yh = exp_h_fmax[2].tolist() plt.figure() plt.title('Max Fit')