def population_based_search (): # Generate initial population pop = [] for i in range(POP_SIZE): c = genetic.Chromosome(None) # pass None to get a random gene sequence c = local_search(c) pop.append(c) for i in range(GENERATIONS): print('Generation', i) new_pop = generate_new_population(pop) pop = update_population(pop, new_pop, POP_SIZE) if has_converged(pop): pop = restart_population(pop) # i = 0 REPORT_EVERY = 1 if i % REPORT_EVERY == 0: out_pop = [''.join([g.representation for g in c.sequence]) for c in pop] out_pop = sorted(out_pop, reverse=True) with open('out/' + str(i) + '.json', 'w') as file: file.write(json.dumps(out_pop, indent=2, ensure_ascii=False)) return pop
def db_reconstruct_organisms(cur, start_time, population_name, generation): ''' Function to reconstruct a list of organisms (genetic.Organism objects) of a population within a simulation (as identified by the starting time of the simulation) at a specific generation. @param cur: Database cursor from connect_database() function. @param start_time: Starting time of current simulation in the format of <date>-<seconds since epoch>; for example, 2013-10-11-1381480985.77. @param population_name: Name of the population @param generation: Current number of generations simulated. @return: A list of Organisms (genetic.Organism objects) ''' import genetic as g start_time = str(start_time) population_name = str(population_name) generation = str(generation) # query plan: SEARCH TABLE organisms USING INDEX # organisms_index2 (generation=?) cur.execute("select distinct org_name from organisms where \ start_time = '%s' and pop_name = '%s' and generation = '%s'" % (start_time, population_name, generation)) names = [x[0] for x in cur.fetchall()] agents = [0] * len(names) for i in range(len(names)): org_name = str(names[i]) org = g.Organism() org.genome = [] org.status['identity'] = org_name # query plan: SEARCH TABLE organisms USING INDEX # organisms_index2 (generation=? AND org_name=?) cur.execute("select key, value from organisms where \ generation = '%s' and org_name = '%s' and \ start_time = '%s' and pop_name = '%s'" % (generation, org_name, start_time, population_name)) for r in cur.fetchall(): key = str(r[0]) value = str(r[1]) if key == 'alive': org.status['alive'] = value elif key == 'vitality': org.status['vitality'] = float(value) elif key == 'parents': if value == '': value = '[]' else: value = value.split('|') org.status['parents'] = value elif key == 'age': org.status['age'] = float(value) elif key == 'gender': org.status['gender'] = value elif key == 'lifespan': org.status['lifespan'] = float(value) elif key == 'fitness': try: org.status['fitness'] = ast.literal_eval(value) except: org.status['fitness'] = value elif key == 'blood': if value == '': value = '[]' else: value = value.split('|') org.status['blood'] = value elif key == 'deme': org.status['deme'] = str(value) elif key == 'location': value = tuple([int(x) for x in value.split('|')]) org.status['location'] = value elif key == 'death': org.status['death'] = value elif key.startswith('chromosome'): chr_position = key.split('_')[1] sequence = [str(x) for x in str(value)] cur.execute("select value from parameters where \ key='background_mutation' and start_time='%s'" % start_time) background_mutation = float(cur.fetchone()[0]) cur.execute("select value from parameters where \ key='chromosome_bases' and start_time='%s'" % start_time) bases = str(cur.fetchone()[0]).split('|') chromosome_bases = bases chromosome = g.Chromosome(sequence, chromosome_bases, background_mutation) org.genome.append(chromosome) else: try: org.status[key] = ast.literal_eval(value) except: org.status[key] = value agents[i] = org return agents
def fnDisplay(genes, wins, ties, losses, generation): print("-- generation {} --".format(generation)) display( genetic.Chromosome(genes, Fitness(wins, ties, losses, len(genes)), None), startTime)
###################################################################### # GA Program #3: Simulates crossover events between 2 chromosomes ###################################################################### import sys, os sys.path.append(os.path.join(os.path.dirname(os.getcwd()), 'copads')) import genetic as g c1 = g.Chromosome([0] * 50, [1, 2, 3, 4]) # integer chromosome c2 = g.Chromosome(['A'] * 50, ['A', 'B', 'C', 'D']) # alphabet chromosome print('INITIAL CHROMOSOMES ==================================') print('Integer chromosome sequence: ' + str(c1.sequence)) print('Alphabet chromosome sequence: ' + str(c2.sequence)) for x in range(10, 50, 10): print() (g1, g2) = g.crossover(c1, c2, x) print('Crossover at base ' + str(x)) print('Integer chromosome sequence: ' + str(g1.sequence)) print('Alphabet chromosome sequence: ' + str(g2.sequence))
Licence: Python Software Foundation License version 2 Reference: Ling, MHT. 2012. An Artificial Life Simulation Library Based on Genetic Algorithm, 3-Character Genetic Code and Biological Hierarchy. The Python Papers 7: 5. ''' import genetic as g import dose_world as w from dose_parameters import chromosome_size, background_mutation_rate from dose_parameters import cytoplasm_size, population_size from dose_parameters import maximum_generations from dose_parameters import world_x, world_y, world_z Chromosome = g.Chromosome(initial_chromosome, ['0','1','2','3','4','5','6','7','8','9'], background_mutation_rate) class Organism(g.Organism): cytoplasm = [0]*cytoplasm_size def __init__(self): self.genome = [Chromosome.replicate()] def get_cytoplasm(self): return ','.join([str(x) for x in self.cytoplasm]) def fitness(self): pass def mutation_scheme(self): pass class Population(g.Population): def __init__(self, pop_size=population_size,
###################################################################### # GA Program #2: Simulates different rates of mutation (5 to 25% above # background mutation rate. Fitness is the average of the chromosome # where 1-4 is allowed; hence, all 4 organisms should converge to the # average of 2.5 but at different rates. ###################################################################### import sys, os sys.path.append(os.path.join(os.path.dirname(os.getcwd()), 'copads')) import genetic as g c = g.Chromosome([0] * 200, [1, 2, 3, 4]) o = g.Organism([c]) oset = [o.clone() for x in range(5)] print('Generation \tMutation rate above background rate') print('Count \t\t', '\t'.join(['5%', '10%', '15%', '20%', '25%'])) print('=' * 60) for x in xrange(100): print(x, '\t\t', '\t'.join([str(oset[x].fitness()) for x in range(5)])) for mut in range(1, 6): oset[mut - 1].mutation_scheme('point', float(mut) / 20)