def main(): gencount = 100 #dimensions d = 1053.7 ff = 0.5904 tline = 589.0957 tslab = 296.6 tstep = 10.5036 g0 = NIRZCG((d, ff, tline, tslab, tstep),(1750, 2250, 1001), target = 2000) g0.evaluate() oldbest = g0 genbest = list(zip(*g0.trans)) print(str(dt.time(dt.now())).split('.')[0],colored("seed:", 'cyan'),g0) gen = Generation(25, g0) for i in range(gencount): #str(dt.time(dt.now())).split('.')[0],colored("gen "+str(i), 'cyan') gen._evaluate(progress_txt = (str(dt.time(dt.now())).split('.')[0]+colored(" gen "+str(i), 'cyan'))) gen = gen.progeny() genbest.append([t for wl,t in gen.best.trans]) if gen.best.fom > oldbest.fom: print(colored("new best grating\n", 'green')+str(gen.best)) oldbest = gen.best writecsv("iter_best.csv",list(zip(*genbest)),tuple(["wl",0]+list(range(1,gencount+1))))
def __init__(self, parser, truecase_model): """ Perform syntactic simplification rules for Galician (this code is based on the one available at simpatico_ss/simplify.py for English). TODO: Relative and conjoint clauses are not supported by the Galician parser. Functions for these cases were left here as examples for feature implementations. @param parser: parser server. @truecase_model: truecase model """ ## markers are separated by their most used sense self.time = ['when', 'after', 'since', 'before', 'once'] self.concession = ['although', 'though', 'but', 'however', 'whereas'] self.justify = ['because', 'so', 'while'] self.condition = ['if'] self.condition2 = ['or'] self.addition = ['and'] ## list of all markers for analysis purposes self.cc = self.time + self.concession + self.justify + self.condition + self.addition + self.condition2 ## list of relative pronouns self.relpron = ['whom', 'whose', 'which', 'who'] ## initiates parser server self.parser = parser ## Generation class instance self.generation = Generation(self.time, self.concession, self.justify, self.condition, self.condition2, self.addition, self.cc, self.relpron, truecase_model)
def __init__(self, representation="pool", L=12, shared_core=False): super(GQN, self).__init__() # Number of generative layers self.L = L self.shared_core = shared_core # Representation network self.representation = representation if representation == "pyramid": self.phi = Pyramid() elif representation == "tower": self.phi = Tower() elif representation == "pool": self.phi = Pool() # Generation network if shared_core: self.inference_core = InferenceCore() self.generation_core = GenerationCore() else: self.inference_core = nn.ModuleList( [InferenceCore() for _ in range(L)]) self.generation_core = nn.ModuleList( [GenerationCore() for _ in range(L)]) # Distribution self.pi = Prior() self.q = Inference() self.g = Generation()
def evolve_generations_plateau(simulation_func, negligible, max_bad_gen_count, pop_size=60, num_fittest=5, num_random=10, num_elites=3): # Create start generation # While not done # Simulate generation # Check if should be done # Spawn next generation Generator = GenFFANN num_params = (GenFFANN.INPUTSIZE * GenFFANN.HIDDENSIZE) + (GenFFANN.HIDDENSIZE * GenFFANN.OUTPUTSIZE) print num_params current_gen = Generation(Generator, simulation_func, pop_size, num_fittest, num_random, num_elites, num_params) current_gen.spawn_random_generation() best_fitness = -100000 bad_gen_count = 0 gen_num = 0 while True: gen_num += 1 print "Running generation {0}".format(gen_num) fitness = current_gen.run() print "Fitness is {0} compared to {1}".format(fitness, best_fitness) if fitness - best_fitness <= negligible: bad_gen_count += 1 print "Bad Generation #{0}".format(bad_gen_count) else: bad_gen_count = 0 best_generator = current_gen.fittest[0] best_fitness = best_generator.fitness if bad_gen_count >= max_bad_gen_count: return best_generator current_gen = current_gen.spawn_next_generation()
def testDone(self): """"Test the Done method. Produce a generation with a set of tasks. Set the cost of the task one by one and verify that the Done method returns false before setting the cost for all the tasks. After the costs of all the tasks are set, the Done method should return true. """ random.seed(0) testing_tasks = range(NUM_TASKS) # The tasks for the generation to be tested. tasks = [IdentifierMockTask(TEST_STAGE, t) for t in testing_tasks] gen = Generation(set(tasks), None) # Permute the list. permutation = [(t * STRIDE) % NUM_TASKS for t in range(NUM_TASKS)] permuted_tasks = [testing_tasks[index] for index in permutation] # The Done method of the Generation should return false before all the tasks # in the permuted list are set. for testing_task in permuted_tasks: assert not gen.Done() # Mark a task as done by calling the UpdateTask method of the generation. # Send the generation the task as well as its results. gen.UpdateTask(IdentifierMockTask(TEST_STAGE, testing_task)) # The Done method should return true after all the tasks in the permuted # list is set. assert gen.Done()
def main(): print_run_info() generation = Generation(POPULATION, ELITE, CROSSOVER, MUTATE) generation_avg_fitness_list = [generation.avg_solution_fitness] run_count = 1 print('{}, {}'.format(run_count, generation.avg_solution_fitness)) for i in range(1, 3): solution_data = [] solution_data = solution_data + generation.elites + generation.untouched mutated_solutions = [] crossedover_solutions = [] for item in generation.mutations: mutated_solutions.append(item.mutate()) for i in range(0, int(len(generation.crossovers) / 2)): item = generation.crossovers[i] other_item = generation.crossovers[len(generation.crossovers) - i - 1] for new_item in item.crossover(other_item): crossedover_solutions.append(new_item) solution_data = solution_data + mutated_solutions + crossedover_solutions generation = Generation(POPULATION, ELITE, CROSSOVER, MUTATE, solution_data) run_count = run_count + 1 generation_avg_fitness_list.append(generation.avg_solution_fitness) print('{}, {}'.format(run_count, generation.avg_solution_fitness))
def test_generation_to_retrun_best_fit_people(self): best = Mock(spec=DNA) fitness = 5 mock_population = Mock(spec=Population) mock_population.best_fit = Mock(return_value=(best, fitness)) generation = Generation(1, mock_population) self.assertEquals((best, fitness), generation.best_fit())
def __init__(self): pygame.init() self.generation = Generation() self.population = self.generation.population self.gamespeed = 4 self.max_gamespeed = 10 self.high_score = 0 self.n_gen = 0 self.current_gen_score = 0 self.dinos = None self.genomes = [] self.screen = pygame.display.set_mode(scr_size) self.clock = pygame.time.Clock() pygame.display.set_caption('Genetic T-Rex Rush') self.jump_sound = pygame.mixer.Sound('sprites/jump.wav') self.die_sound = pygame.mixer.Sound('sprites/die.wav') self.checkPoint_sound = pygame.mixer.Sound('sprites/checkPoint.wav') self.scores = [] self.fig = plt.figure(figsize=(int(width/100), 5)) self.ax = plt.axes() plt.xlabel('Generation', fontsize=18) plt.ylabel('Score', fontsize=16) plt.show(block=False)
class AiPainter: def __init__(self, pName, gMax, gNum, size, pixel, pTerm): self.pObj = Picture(pName, size) self.gObj = Generation(gMax, gNum, self.pObj.height, self.pObj.width, pTerm) self.cObj = CanvasPainter(self.pObj.height, self.pObj.width, pixel) self.pName, self.gMax, self.gNum, self.size, self.pixel, self.pTerm = pName, gMax, gNum, size, pixel, pTerm def startPainting(self): start_time = time.time() for n in range(0, self.gMax): self.gObj.geneCreate(self.gNum, self.pObj.height, self.pObj.width, n) self.gObj.scoreCheck(self.pObj.height, self.pObj.width, self.pObj.img, self.gNum, self.gMax, n, self.pTerm) if self.gObj.strongestGene[1] > 97: self.gMax = n print(n) break print("--- %s seconds ---" %(time.time() - start_time)) def resultSave(self): self.cObj.painting(self.pName, self.pObj.height, self.pObj.width, self.pixel, self.gObj.geneSave, self.gMax, self.pTerm)
def __init__(self, parser, truecase_model): """ Perform syntactic simplification rules. @param parser: parser server. @param truecase_model: truecase model. """ #self.sentences = open(doc, "r").read().strip().split("\n") ## markers are separated by their most used sense self.time = ['cuando', 'despues', 'antes', 'before', 'once'] self.concession = ['aunque', 'pero', 'sino', 'however', 'whereas'] self.justify = ['so', 'mientras'] self.condition = ['si'] self.condition2 = ['o'] self.addition = ['y'] ## list of all markers for analysis purposes self.cc = self.time + self.concession + self.justify + self.condition + self.addition + self.condition2 ## list of relative pronouns self.relpron = ['que', 'whose', 'which', 'who'] ## initiates parser server self.parser = parser ## Generation class instance self.generation = Generation(self.time, self.concession, self.justify, self.condition, self.condition2, self.addition, self.cc, self.relpron, truecase_model)
def __init__(self, doc): """ Perform syntactic simplification rules. @param doc: document to be simplified. """ self.sentences = open(doc, "r").read().strip().split("\n") ## markers are separated by their most used sense self.time = ['when', 'after', 'since', 'before', 'once'] self.concession = ['although', 'though', 'but', 'however', 'whereas'] self.justify = ['because', 'so', 'while'] self.condition = ['if'] self.condition2 = ['or'] self.addition = ['and'] ## list of all markers for analysis purposes self.cc = self.time + self.concession + self.justify + self.condition + self.addition + self.condition2 ## list of relative pronouns self.relpron = ['whom', 'whose', 'which', 'who'] ## initiates parser server self.parser = Parser() ## Generation class instance self.generation = Generation(self.time, self.concession, self.justify, self.condition, self.condition2, self.addition, self.cc, self.relpron)
def test_generation_to_generate_next_generation(self): mock_population1 = Mock(spec=Population) mock_population2 = Mock(spec=Population) mock_population1.next_population = Mock(return_value=mock_population2) mock_target_DNA = Mock(spec=DNA) generation1 = Generation(1, mock_population1) generation2 = generation1.next_generation(mock_target_DNA) self.assertEquals(generation2.number, 2) self.assertEquals(generation2.population, mock_population2)
def __init__(self, tasks, next_generations): """Set up the next generations for this task. Args: tasks: A set of tasks to be run. next_generations: A list of generations as the next generation of the current generation. """ Generation.__init__(self, tasks, None) self._next_generations = next_generations
def main(): g = Generation(size=100, elite=0.05, mutate=0.10, tournament=10, mood=raw_input()) g.run(100, desired_length=13) g.best.info() lilypond.printPiece(g.best, 'best.ly') lilypond.printPiece(g.worst, 'worst.ly')
def __init__(self, tasks, parents, total_stucks): """Set up the meta data for the Genetic Algorithm. Args: tasks: A set of tasks to be run. parents: A set of tasks from which this new generation is produced. This set also contains the best tasks generated so far. total_stucks: The number of generations that have not seen improvement. The Genetic Algorithm will stop once the total_stucks equals to NUM_TRIALS defined in the GAGeneration class. """ Generation.__init__(self, tasks, parents) self._total_stucks = total_stucks
def main(): generation = Generation(100, [11, 11, 4, 4], 0.5, 10) print("Starting the program at generation 0") while True: try: command = input("Enter a command (sbs, asap, alap): ") if command == "sbs": generation.do_generation(render=True) print("That was generation {}.".format(str(generation.age - 1))) elif command == "asap": generation.do_generation() print("Just did generation {} as fast as possible.".format( str(generation.age - 1))) elif command == "alap": print( "Doing generations for as long as possible starting at generation {}." .format(str(generation.age))) print("Type Ctrl-C to exit the alaping") while True: try: generation.do_generation() print("Just did generation {}".format( str(generation.age - 1))) except KeyboardInterrupt: print("Exiting alap") break else: print("Not a valid command") except KeyboardInterrupt: print("Thanks for playing") print("Exiting now") sys.exit()
def doEvolve(self): evolGeneration = Generation(self.parentGeneration, self.goal, self.possibleAttributes) while not self.evolutionFinish: survivors = evolGeneration.sortTrolls() evolGeneration = Generation(survivors, self.goal, self.possibleAttributes) for Troll in survivors: if (Troll.look == self.goal.look) and (Troll.sex == self.goal.sex): print("The requested Troll was born!") print("fix me: name is missing " + str(Troll.look) + str(Troll.sex)) self.evolutionFinish = True break
def main(): generation = Generation() while True: generation.execute() generation.keep_best_genomes() generation.mutations()
def __init__(self, rows, cols): """Creates a game object.""" #self._board = Board(8, 8) self._rows = rows self._cols = cols self._current_generation = Generation(rows, cols)
def __init__(self, island_model, *args, **kwargs): super().__init__(*args, **kwargs) self._island_model = island_model # Assume existing members of the tree are a part of the founders if len(island_model.individuals) > 0: assert len(self._generations) is 0 self._generations.append(Generation(island_model.individuals))
def main(): generation = Generation() while True: generation.execute() print("Done") generation.keep_best_genomes() print("Storing") generation.mutations() print("Mutated")
def load_generation(filename): if len(filename) <= 2 or filename[len(filename)-2: len(filename)] != ".p": filename = filename + ".p" try: generation = pickle.load(open(filename, "rb")) print "Resuming from", filename print "Last Generation Processed:", generation.num score_str = "Sorted Scores" for individual in generation.population: score_str = score_str + " : {0}".format(individual.score) print score_str return generation except IOError: print "Could not open", filename + ",", "returning new Generation" generation = Generation() generation.populate() return generation
def load_generation(filename): if len(filename) <= 2 or filename[len(filename) - 2:len(filename)] != ".p": filename = filename + ".p" try: generation = pickle.load(open(filename, "rb")) print "Resuming from", filename print "Last Generation Processed:", generation.num score_str = "Sorted Scores" for individual in generation.population: score_str = score_str + " : {0}".format(individual.score) print score_str return generation except IOError: print "Could not open", filename + ",", "returning new Generation" generation = Generation() generation.populate() return generation
def main(): generation = Generation() lx, ly, rx, ry = get_location() epoch = 0 while True: epoch = epoch + 1 print("Geracao {}".format(epoch)) generation.execute(lx, ly, rx, ry, epoch) generation.keep_best_genomes() generation.mutations()
def _initialise(self, target_string): target_length = len(target_string) nucleotides = Nucleotides(string.printable) DNA.nucleotides = nucleotides population_initialise = PopulationInitialise(nucleotides) first_population = population_initialise.create( population_size=self.population_size, structure_size=target_length) first_generation = Generation(1, first_population) return [first_generation]
def main(): generation = Generation() i=0 while True: print("Generation "+str(i)+":") i += 1 generation.execute() generation.keep_best_genomes() generation.mutations()
def __init__(self, exe_set, parent_task): """Set up the base line parent task. The parent task is the base line against which the new tasks are compared. The new tasks are only different from the base line from one flag f by either turning this flag f off, or lower the flag value by 1. If a new task is better than the base line, one flag is identified that gives degradation. The flag that give the worst degradation will be removed or lower the value by 1 in the base in each iteration. Args: exe_set: A set of tasks to be run. Each one only differs from the parent_task by one flag. parent_task: The base line task, against which the new tasks in exe_set are compared. """ Generation.__init__(self, exe_set, None) self._parent_task = parent_task
def test_living_neighbors(self): g = Generation(5, 5) g.assign_neighbors() cells = [[0, 1, 0, 0, 1], [0, 0, 0, 1, 0], [0, 1, 1, 1, 1], [0, 0, 1, 1, 1], [1, 1, 1, 1, 1]] for row in range(5): for column in range(5): if cells[row][column] == 1: g._cells[row][column].live() correctCount = [[1, 0, 2, 2, 1], [2, 3, 5, 4, 4], [1, 2, 5, 6, 4], [3, 6, 7, 8, 5], [1, 3, 4, 5, 3]] for cell in g.cells(): self.assertEqual( cell.living_neighbors(), correctCount[cell.row][cell.column], f'cell[{row}][{column}] != {correctCount[row][column]}')
def __init__(self, exe_set, parents, specs): """Set up the tasks set of this generation. Args: exe_set: A set of tasks to be run. parents: A set of tasks to be used to check whether their neighbors have improved upon them. specs: A list of specs to explore. The spec specifies the flags that can be changed to find neighbors of a task. """ Generation.__init__(self, exe_set, parents) self._specs = specs # This variable will be used, by the Next method, to generate the tasks for # the next iteration. This self._next_task contains the best task in the # current iteration and it will be set by the IsImproved method. The tasks # of the next iteration are the neighbor of self._next_task. self._next_task = None
def createNewGeneration(generation, scorePerChild, ppid, pid): if(generation.generation_i >= 10300): growth = int(1*(generation.generation_i / 300)) else: growth = 0 n_random = 6 + growth n_elite = 2 + growth n_mutated_elite = 2 + growth #Crossover Rates n_crossover_mutated_elite = 2 + growth n_crossover_mutated_random = 2 + growth n_crossover_unmutated_elite = 2 + growth n_crossover_unmutated_random = 2 + growth #Gets indices of the elite children of population idxs_elite = heapq.nlargest(n_elite, range(len(scorePerChild)), key=scorePerChild.__getitem__) idxs_elite = np.array(idxs_elite) #print information about the best elite if(generation.generation_i % 20 == 0): print(str(scorePerChild[idxs_elite[0]]) + "/" + str(generation.num_clauses), generation.generation_i, len(generation.children), ppid, pid) #Create children elite_children = np.array(generation.children[idxs_elite]) random_children = np.array(createRandomChildren(n_random, generation.num_variables)) if(n_mutated_elite > len(elite_children)): print("n_mutated_elite > elite_children") n_mutated_elite = len(elite_children) mutate_elite = np.array([mutate(elite_children[i]) for i in (0, n_mutated_elite-1)]) #Create Crossovers crossover_unmutated_random = np.array(createCrossOvers(elite_children, random_children, n_crossover_unmutated_random)) crossover_unmutated_elite = np.array(createCrossOvers(elite_children, elite_children, n_crossover_unmutated_elite)) crossover_mutated_random = np.array(createCrossOvers(mutate_elite, random_children, n_crossover_mutated_random)) crossover_mutated_elite = np.array(createCrossOvers(elite_children, elite_children, n_crossover_mutated_elite)) # @todo make this more clean temp = np.array([]) temp = np.append(temp, elite_children) temp = np.append(temp,random_children) temp = np.append(temp,mutate_elite) temp = np.append(temp,crossover_unmutated_random) temp = np.append(temp,crossover_unmutated_elite) temp = np.append(temp,crossover_mutated_random) temp = np.append(temp,crossover_mutated_elite) temp = np.array(temp) temp = temp.reshape(int(len(temp)/729), 729) children = np.array(temp) return Generation(generation, children, generation.num_clauses, generation.num_variables)
def test_create(self): rows = 2 columns = 4 g = Generation(rows, columns) g.assign_neighbors() # # Is the world the correct size? # self.assertEqual(g.rows, rows) self.assertEqual(len(g._cells), rows) self.assertEqual(g.columns, columns) self.assertEqual(len(g._cells[0]), columns) # # Are all the cells correct? # for row in range(rows): for column in range(columns): self.assertFalse(g._cells[row][column].alive) self.assertEqual(g._cells[row][column].row, row) self.assertEqual(g._cells[row][column].column, column)
def run(self): max_unit = 0 for i in range(self.ran): print("Generation ", i) gen = Generation(self.p) #gen.hand.print_cards() gen.assign_unit_value(0) #gen.print_stats() gen.calc_fitness(self.step, 0) #for i in range(p.size): # print(gen.population.units[i].fitness) if (i == self.ran - 1): break max_val = 0 for i in range(gen.population.size): if (gen.population.units[i].fitness > max_val): max_unit = gen.population.units[i] max_val = gen.population.units[i].fitness print(max_unit.fitness) s = Step(gen) gen.population.units = s.generate_mating_pool() max_val = 0 max_unit = 0 for i in range(gen.population.size): if (gen.population.units[i].fitness > max_val): max_unit = gen.population.units[i] max_val = gen.population.units[i].fitness print(max_unit.weights) return max_unit.weights
def __init__(self, lamb, mu, turns, perturb, sourcefile): self.mu = mu self.lamb = lamb self.runs = turns LOG_FILENAME = os.path.abspath("./results/ealog.txt") # Set up a specific logger with our desired output level self.log = logging.getLogger('MyLogger') self.log.setLevel(logging.DEBUG) self.handler = logging.handlers.RotatingFileHandler( LOG_FILENAME, backupCount=5) self.log.addHandler(self.handler) # create an initial generation self.this_generation = Generation(lamb, mu, self.log) self.this_generation.random(sourcefile, perturb)
def worker(args): # Init gen = None last_backup = 0 if args.load_file is not None: gen = load_generation(args.load_file) last_backup = gen.num gen = gen.propagate() else: gen = Generation() gen.populate() save_file = args.save_file # For each generation for gen_num in range(1, args.gens+1): # INITIAL SCORING # Individual VS Elites and Coded Bots individual_pool = Pool(processes=args.processes) scores = individual_pool.map(initial_score_individuals, [(x, gen) for x in gen.population]) sorted_scores = [] individual_pool.close() individual_pool.join() for x in range(len(gen.population)): gen.population[x].score = scores[x] sorted_scores.append(gen.population[x].score) sorted_scores.sort() sorted_scores.reverse() # ELITE SCORING AND SORTING # Break Ties that cross the ELITE/NON-ELITE cutoff num_elites = constants.elite_size if sorted_scores[num_elites-1] == sorted_scores[num_elites]: tie_score = sorted_scores[num_elites] tied_individuals = [] for individual in gen.population: if individual.score == tie_score: tied_individuals.append(individual) # Break The Ties individual_pool = Pool(processes=args.processes) partial_scores = individual_pool.map(break_ties, [(tied_individuals[x], tied_individuals, x) for x in range(len(tied_individuals))]) individual_pool.close() individual_pool.join() # New scores are in range [tie_score, tie_score+1) fill_scores_from_partial(tied_individuals, partial_scores) scores = [] for x in range(len(gen.population)): scores.append(gen.population[x].score) gen.sort_by_score() # Clobber if necessary try: progress_q.get_nowait() except Queue.Empty: pass # If work is done or early stop is requested: save, inform, finish if gen_num == args.gens or not early_end_q.empty(): progress_q.put(ProgressInfo(scores, gen.num, last_backup, save_file)) save_generation(gen, save_file) break # Otherwise: inform and move to next generation else: if (gen_num % constants.backup_frequency) == (constants.backup_frequency-1): save_generation(gen, constants.default_backup) last_backup = gen.num progress_q.put(ProgressInfo(scores, gen.num, last_backup)) gen = gen.propagate()
return result if __name__ == '__main__': """ > python main.py """ args = parseArgs(sys.argv[1:]) if args['load'] == '': if args['simulate'] is True: mapLayout = args['layout'] carmap = CarMap(mapLayout, None) cars = randomStartEndPoint(args['number']) g = Generation(mapLayout, carmap, cars, args['amount'], args['generation']) results = g.run() print "Best in each generation:\n" counter = 0 for r in results[::2]: counter += 1 (a, s) = r print('[' + str(counter) + '] ' + '{0:.2f}'.format(a) + ' ' + s) print('\n-----------------------------------------------------------\n') print "Middle in each generation:\n" counter = 0 for r in results[1::2]: counter += 1
class EA(object): def __init__(self, lamb, mu, turns, perturb, sourcefile): self.mu = mu self.lamb = lamb self.runs = turns LOG_FILENAME = os.path.abspath("./results/ealog.txt") # Set up a specific logger with our desired output level self.log = logging.getLogger('MyLogger') self.log.setLevel(logging.DEBUG) self.handler = logging.handlers.RotatingFileHandler( LOG_FILENAME, backupCount=5) self.log.addHandler(self.handler) # create an initial generation self.this_generation = Generation(lamb, mu, self.log) self.this_generation.random(sourcefile, perturb) def run(self): for i in range(0,self.runs): print("\n\n=====\nGENERATION: {0}\n====".format(self.this_generation.number)) self.log.debug("\n\n=====\nGENERATION: {0}\n====".format(self.this_generation.number)) # this modifies the generation and adds babies self.this_generation.reproduce() self.this_generation.natural_selection() if self.this_generation.number % 10 == 0: self.this_generation.every_ten_tournament() self.this_generation.output_statistics() self.this_generation.number += 1 self.output_top() def output_top(self): num = 10 sols = [] for s in sorted(self.this_generation.population, key=lambda p: p.fitness, reverse=True): sols.append(s) self.this_generation.output_solutions_to_file(sols,"top10.txt")
# -*- coding: utf-8 -*- import os from generation import Generation from puntos import Puntos G = Generation(Puntos) def make_plot(fittest): ret = "" for point in fittest.conjunto: ret += str(point[0]) + " " + str(point[1]) + "\n" return ret def average(ls): return sum(ls) / len(ls) cont = 0 while True: G = G.spawn_new_gen() cont += 1 if cont % 40 == 1: fittest = max([(ind.fitness(), ind) for ind in G.individuals])[1] fitness = fittest.fitness() data_output = open("data.out", "w") graph_guide = open("graph.gnp", "w") data_output.write(make_plot(fittest))
def fitness(self): if self.fit: return self.fit score = 0.0 for J in xrange(config.simulations_per_individual): players = [[lambda x: self.string[len(x)], 'Individual']] players += [random.choice(bs) for i in xrange(6)] x = [] record = [] points = [0 for i in xrange(7)] for I in xrange(20): what = [p[0](x) for p in players] x.append([sum([1 if j == 'A' else 0 for j in what]), sum([1 if j == 'B' else 0 for j in what])]) money = [700/x[-1][0] if j == 'A' else 300/x[-1][1] for j in what] points = [sum(a) for a in zip(points, money)] record.append(points) score += (float(record[-1][0])/float(max(record[-1])))**config.value_power self.fit = score return score def get_description(self): return " - (%s), fitness ~ %f\n"%(self.string, self.fitness()) if __name__ == '__main__': G = Generation(f20) cont = 0 while True: print "Generation #%d"%cont cont += 1 G = G.spawn_new_gen(Debug=True)