def test(self): """TODO: document this.""" startTime = datetime.datetime.now() vis = Vis() def fnDisplay(population, gen, info): avg = Fitness(0, 0, 0, 0, 0, score=0) for ind in population: avg = avg + ind.fitness avg = avg // len(population) max_fit = avg for ind in population: if max_fit < ind.fitness: max_fit = ind.fitness fitness_diversity = np.std( [ind.fitness.score for ind in population]) gene_diversity = np.std([[allele for allele in ind.genes] for ind in population], axis=0) max_allele_deviation = np.amax(gene_diversity) vis.add_generation(max_fit.score, avg.score, (fitness_diversity, np.mean(gene_diversity)), max_fit.hits, max_fit.misses, info) print("Gen " + str(gen) + ":\nAvg Fitness: " + str(avg) + "\nMax Fitness: " + str(max_fit) + "\nGene Diversity: " + str(np.mean(gene_diversity)) + ", Max Allele Deviation: " + str(max_allele_deviation) + "\nElapsed Time: " + str(datetime.datetime.now() - startTime) + "\n -- ") def fnGetFitness(genes): return self.get_fitness(genes) def fnCreate(): return self.create_gene() muts = generate_mutations() genetic.evolve(POPULATION_SIZE, REPRODUCTION_RATES, MUTATION_RATE, fnGetFitness, fnDisplay, muts, fnCreate) input("END?")
def create_riff_db(initial_pop, options): """ Create a database of riffs to be used by the "composer" to generate it's master pieces """ # Ideally categorise or create new riff_dbs for every scale? sys.stderr.write("Creating riff database: ") tick = ticker() g = genetic.evolve(initial_pop, options.pop_limit, options.mutation_rate) for i in xrange(options.generations): tick.next() g.next() sys.stderr.write("\n") pop = g.next() return pop
def optimize(npoints, deltap, ipop, ngen, situation): """ Call genetic functions and return the best population. npoints: number of values per individual deltap: maximum possible value in an individual's list of values ipop: number of initial population ngen: number of generations situation: circle or travel """ target = 0 p = genetic.population(ipop, npoints, 0, deltap) fitness_history = [ genetic.grade(p, target, situation, ngen=ngen), ] for i in xrange(ngen): p = genetic.evolve(p, target, situation, i, ngen) fitness_history.append( genetic.grade(p, target, situation, gen=i, ngen=ngen)) return p.pop()
def evolve(self, *args, **kwargs): self.best = genetic.evolve(*args, **kwargs) self.slope = self.best[0] self.y_int = self.best[1]
import genetic #import custom_two_param_score #import custom_one_param_score import custom_data_score #rf = genetic.getrankfunction(custom_two_param_score.buildhiddenset(), custom_two_param_score.scorefunction) #print genetic.evolve(2, 500, rf, mutationrate = 0.2, breedingrate = 0.1, pexp = 0.7, pnew = 0.1).display() #rf = genetic.getrankfunction(custom_one_param_score.buildhiddenset(), custom_one_param_score.scorefunction) #print genetic.evolve(1, 500, rf, mutationrate = 0.2, breedingrate = 0.1, pexp = 0.7, pnew = 0.1).display() rf = genetic.getrankfunction(custom_data_score.buildhiddenset(), custom_data_score.scorefunction) print genetic.evolve(1, 500, rf, mutationrate = 0.2, breedingrate = 0.1, pexp = 0.7, pnew = 0.1).display()
population = [] for track in file: notes = track.split() track = Track() for note in notes: track.add_notes(note) gene = MusicGene(track) population.append(gene) return population if __name__ == "__main__": fluidsynth.init(SF2, DRIVER) population = import_population("initial.db") g = genetic.evolve(population) print "Generation #%d"%0 for i in xrange(len(population)): print "Track #%d"%i population[i].play() for i in xrange(10): pdb.set_trace() pop = g.next() print "Generation #%d"%i for i in xrange(len(population)): print "Track #%d"%i population[i].play()
start = time.time() # 1d genetic for i in range(numOfParam): p = g.population(paramRange1[i], i) for j in range(1, numOfGen1d + 1): print("#########################################################") print("#########################################################") print("#########################################################") print(str(j) + "EVOLUTION" + " FOR PARAM " + str(i)) print("#########################################################") print("#########################################################") print("#########################################################") f = open("log.txt", "a") f.write(str(j) + "EVOLUTION" + " FOR PARAM " + str(i) + "\n") f.close() p = g.evolve(p, 0) paramRange2.append(g.getParamRange(p, i)) f = open("log.txt", "a") f.write("ParamRange," + str(paramRange2[0]) + "," + str(paramRange2[1]) + "," + str(paramRange2[2]) + "," + str(paramRange2[3]) + "," + str(paramRange2[4]) + "," + str(paramRange2[5]) + "," + str(paramRange2[6]) + "," + str(paramRange2[7]) + "," + str(paramRange2[8]) + "," + str(paramRange2[9]) + "," + str(paramRange2[10]) + "\n") f.close() end = time.time() f = open("log.txt", "a") cost = end - start
def solve(): # Create the weighted graph object used for all tests graphgen = graphGenerator(10, 20, 100) randomgraph = graphgen.wgraph # Greedy Algorithm testing # Does not require more than one run, as every run yields the same result and approximately the same time startgreedy = timeit.default_timer() greedyresult = randomgraph.greedytsp(0) elapsedgreedy = timeit.default_timer() - startgreedy print "Final length of Greedy TSP Tour:", greedyresult[1] # print "Final Greedy TSP Algorithm pathlist:", greedyresult[0] # Simulated Annealing Algorithm testing # Run 100 annealing sessions and return basic statistical # analysis of resulting tour lengths and time simannealdata = [] simannealtimedata = [] simnumruns = 100 for i in range (simnumruns): startanneal = timeit.default_timer() graph = SimAnnealingTSPGraph(randomgraph) agent = SimAnnealingTSPAgent() bestgraph = graph count = 0 shufflecount = 0 while count < 10: if shufflecount >= 1: random.shuffle(tspgraph.pathlist) tspgraph = agent.anneal(graph) if tspgraph.graph.pathlength(tspgraph.pathlist) < bestgraph.graph.pathlength(bestgraph.pathlist): bestgraph = tspgraph count +=1 shufflecount +=1 simelapsed = timeit.default_timer() - startanneal simannealdata.append(bestgraph.graph.pathlength(bestgraph.pathlist)) simannealtimedata.append(simelapsed) print "Final length of Simulated Annealing TSP Tour for run",i+1,":", bestgraph.graph.pathlength(bestgraph.pathlist) # print "Final Simulated Annealing TSP Algorithm path-list for run",i+1,":", bestgraph.pathlist # Genetic Algorithm testing # Run 100 instances of the genetic algorithm and return basic # statistical analysis of resulting tour lengths and time target_score = greedyresult[1] geneticdata = [] genetictimedata = [] gennumruns = 100 for j in range (gennumruns): startgenetic = timeit.default_timer() genetictsp = evolve(randomgraph, target_score) print "Final length of Genetic TSP tour for run",j+1,":", genetictsp[1] # print "Final Genetic TSP tour path-list for run",j+1,":", genetictsp[0].pathlist geneticelapsed = timeit.default_timer() - startgenetic geneticdata.append(genetictsp[1]) genetictimedata.append(geneticelapsed) print "========================================================" print "================== FINAL RESULTS =======================" print "========================================================" print "============= GREEDY ALGORITHM RESULTS =================" print "Minimum tour length:", greedyresult[1] print "Time elapsed:", elapsedgreedy, "seconds" print "========================================================" print "=========== SIMULATED ANNEALING RESULTS ================" print "Out of", simnumruns, "runs:" print "Minimum (best) value:", min(simannealdata) print "Mean value:", float(sum(simannealdata))/len(simannealdata) print "Range:", min(simannealdata), "to", max(simannealdata) print "Minimum (best) time:", min(simannealtimedata), "seconds" print "Mean time:", float(sum(simannealtimedata))/len(simannealtimedata), "seconds" print "Range of times:", min(simannealtimedata), "to", max(simannealtimedata), "seconds" print "========================================================" print "============== GENETIC ALGORITHM RESULTS ===============" print "Out of", gennumruns, "runs:" print "Minimum (best) value:", min(geneticdata) print "Mean value:", float(sum(geneticdata))/len(geneticdata) print "Range:", min(geneticdata), "to", max(geneticdata) print "Minimum (best) time:", min(genetictimedata), "seconds" print "Mean time:", float(sum(genetictimedata))/len(genetictimedata), "seconds" print "Range of times:", min(genetictimedata), "to", max(genetictimedata), "seconds" print "========================================================"
paramRange2[3], paramRange2[4], paramRange2[5], paramRange2[6], paramRange2[7], paramRange2[8], paramRange2[9], paramRange2[10]) for i in range(1, numOfGen2d + 1): print("#########################################################") print("#############################################################") print("#############################################################") print(str(i) + "EVOLUTION") print("#########################################################") print("#############################################################") print("#############################################################") f = open("log.txt", "a") f.write(str(i) + "Evolution\n") f.close() extra = 2 + int(i / 2) p, tmp = g.evolve(p2, 1, extra=extra) fitness_history.append(tmp) print("#############################################################") print("#############################################################") print("#############################################################") print("Grading the Final Population") f = open("log.txt", "a") f.write("Grading the Final Population\n") f.close() fitness_history.append(g.grade(p, 2 + int(numOfGen2d / 2))) print("#############################################################") print("#############################################################") print("#############################################################") end = time.time()
__author__ = "ARturo" import genetic as gn target = 371 p_count = 100 i_length = 5 i_min = 0 i_max = 100 p = gn.population(p_count, i_length, i_min, i_max) fitness_history = [gn.grade(p, target)] for x in xrange(100): p = gn.evolve(p, target) fitness_history.append(gn.grade(p, target)) from operator import add print reduce(add, p[1], 0) print reduce(add, p[2], 0)
import step_gen as describers import genetic from ops import basic_functions as functions if __name__ == '__main__': print('starting') hidden_set = describers.build_hidden_set(size=10000) # for row in hidden_set[:20]: # print(row) ranker = genetic.get_rank_function( hidden_set ) genetic.evolve( ranker, depth=4, pop_size=100, functions=functions, maxgen=30, mutation_rate=.3, breeding_rate=.6, pexp=.5, pnew=.1 )