class World: def __init__(self, inp): self.image_data = pygame.image.load("worldbigger.png").convert_alpha() self.width = self.image_data.get_width() self.height = self.image_data.get_height() if AI_DRIVE: self.population = Population(self, 20) else: self.car = Car(self, inp) def update(self): if AI_DRIVE: self.population.update() else: self.car.update() def render(self, display): display.blit(self.image_data, (0, 0)) if AI_DRIVE: self.population.render(display) else: self.car.render(display) def get_terrain(self, point): if point[0] < 0 or point[0] >= self.width: return True if point[1] < 0 or point[1] >= self.height: return True p_alpha = self.image_data.get_at((int(point[0]), int(point[1]))) return p_alpha == (255, 0, 0)
def __init__(self, inp): self.image_data = pygame.image.load("worldbigger.png").convert_alpha() self.width = self.image_data.get_width() self.height = self.image_data.get_height() if AI_DRIVE: self.population = Population(self, 20) else: self.car = Car(self, inp)
def test_get_fittest_pair(self): population = Population( members=[Genome([1, 2, 3, 4, 5, 6, 7, 8]), Genome([8, 7, 6, 5, 4, 3, 2, 1]), Genome([4, 3, 2, 1, 8, 7, 6, 5])]) fittest_pair = population.get_fittest_pair(self._fitness_function) expected_fittest_pair = ( Genome([8, 7, 6, 5, 4, 3, 2, 1]), Genome([4, 3, 2, 1, 8, 7, 6, 5])) self.assertEqual(fittest_pair, expected_fittest_pair)
def beatYourElders(self, ancestry=1, plot=True, point_reset=True, threaded=False, n_threads=-1, config_tag=''): pops = [ pop for pop in self.populations if self.generations - pop.generation < ancestry ] Population.everybodyCompetes(pops, point_reset, threaded, n_threads) if plot: self.plotScorePerGeneration(pops, config_tag) self.plotMeanAndMaxPerGeneration(pops, config_tag)
def main(pol_n, len_i, len_g, lin_n, regen, n_threads, show, config_tag): THREADED = n_threads > 0 THREADS = n_threads def lineageName(pol_n, gen_n): return "test/BernBase{}gen{}.lineage".format(pol_n, gen_n) #********** Generate the asked number of generations ********* # check if(regen): lin_n = pol_n lins = [] # l is an int here individuals = [ Individual([Chromosome(), Chromosome()], pol_n-1) for _ in range(len_i) ] for indiv in individuals: for c in indiv.chromosomes: # generate a random set of weights for the chromosome weights_compressed = [[0]*pol_n]* (len(HEURISTICS)-1) for W_h in weights_compressed: tmp_w = [0]*pol_n for i in range(pol_n): W_h[i] = max(0,1 -random.random() -tmp_w[i]) tmp_w[i] = tmp_w[i] + W_h[i] c.set_genes(numpy.array(weights_compressed)) pop = Population(individuals, 1) print("First generation created for lineage number ", lin_n) lins.append(Lineage([pop], "0")) fname = lineageName(pol_n, lins[0].generations) print("saving to file : ", fname) lins[0].toFile(fname) # l is a lineage here for l in lins: while l.generations < len_g: print("Creating generation ",l.generations+1) l.nextGeneration(THREADED, THREADS) fname = lineageName(pol_n, l.generations) print("saving to file : ", fname) l.toFile(fname) lin = lins[-1] else: for g in range(len_g, 0, -1): try: fname = lineageName(pol_n, g) fh = open(fname, 'r') # Store configuration file values lin = Lineage.fromFile(fname) break except FileNotFoundError: if(g <= 1): print("No previous generations were found, please add the -r or --regenerate flag") exit("no files found : "+lineageName("<Bernstein base>", "<generationNumber>")) # print(lin) lin.beatYourElders(show, True, True, True, n_threads, config_tag)
def nextGeneration(self, threaded=False, n_threads=-1): popul = Population(self.populations[-1].individuals, self.generations + 1) t1 = time.time() popul.compete(True, threaded, n_threads) delta = time.time() - t1 print("duration of competition: {} seconds".format(int(delta))) deaths = popul.naturalySelect() popul.naturalyRenew(deaths) self.populations.append(popul) self.updtLen() return popul
def test_if_returns_best_phenotype(): pop = Population(mock_params, mock_judge, 1, 5) ph1 = Phenotype(3) ph2 = Phenotype(3) ph3 = Phenotype(3) ph1.genes = [True, True, True] ph2.genes = [True, False, False] ph3.genes = [False, False, False] mock_judge.goal_eval(1, 5, ph1) mock_judge.goal_eval(1, 5, ph2) mock_judge.goal_eval(1, 5, ph3) pop.push_phenotype(ph1) pop.push_phenotype(ph2) pop.push_phenotype(ph3) assert pop.get_the_best_error() == [True, False, False]
def test_if_creates_next_population_of_given_size(): pop = Population(mock_params, mock_judge, 1, 5) pop.generate_random_population() pop.create_next_epoch() assert len(pop.parents) == mock_params['mi']
def test_if_correctly_pushes_new_phenotype(): pop = Population(mock_params, mock_judge, 10, 10) ph = Phenotype(3) pop.push_phenotype(ph) assert len(pop.parents) == 1
def test_if_raises_typeerror_on_incorrect_B_param(): with pytest.raises(TypeError): pop = Population(mock_params, mock_judge, 10, '10')
def test_if_creates_empty_population(): pop = Population(mock_params, mock_judge, 10, 10) assert len(pop.parents) == 0
import csound_adapter from genetics import Population from instrument import Instrument IMAGE_VIEWER = 'eog' graph_filename = 'graph.jpg' iterations = 0 print '\n*** SOUND-EVOLUTION ***\n\nPress\n\n[1]\tto run option "population"'\ '\n[2]\tto run option "mutation"\n[3]\tto run option "make love"' a = int(raw_input('\n:- ')) if a == 3: P = Population(4, Instrument, {'const_prob': 0.7, 'max_children': 3}) while not raw_input( '\nPress return to continue, anything else to quit:- '): for n, i in enumerate(P.individuals): try: print i.to_instr() print '\nPlaying Sound #{}'.format(n + 1) i.to_graph(graph_filename) os.system("%s %s &" % (IMAGE_VIEWER, graph_filename)) csd = csound_adapter.CSD() csd.orchestra(i) csd.score('i 1 0 2') csd.play() except OSError: print '\nSkipping this iteration:- Csound crashed' n = int(
def fromStr(str): Str = str.split('\n\n') name = Str.pop(0).split(' ')[1] pops = [Population.fromStr(s) for s in Str] return Lineage(pops, name)
lins = [] # l is an int here for l in range(args.l): individuals = [ Individual([Chromosome(), Chromosome()], args.n) for _ in range(args.i) ] for indiv in individuals: for c in indiv.chromosomes: # generate a random set of weights for the chromosome weights_compressed = [[0] * pol_n] * (len(HEURISTICS) - 1) for W_h in weights_compressed: tmp_w = [0] * pol_n for i in range(pol_n): W_h[i] = max(0, 1 - random.random() - tmp_w[i]) tmp_w[i] = tmp_w[i] + W_h[i] c.set_genes(numpy.array(weights_compressed)) pop = Population(individuals, 1) print("First generation created for lineage number ", l) lins.append(Lineage([pop], str(l))) # l is a lineage here for l in lins: while l.generations < args.g: print("Creating generation ", l.generations + 1) l.nextGeneration(True) fname = "lin{}gen{}.lineage".format(l.name, l.generations) print("saving to file : ", "test/" + fname) l.toFile("test/" + fname)
def test_init_with_no_parameters(self): random_population = Population() self.assertEqual(random_population.size(), 50)
from instrument import * from genetics import Individual from genetics import Population import os IMAGE_VIEWER = "eog" graph_filename = "graph.jpg" iterations = 0 print '\n*** SOUND-EVOLUTION ***\n\nPress\n\n[1]\tto run option "population"\n[2]\tto run option "mutation"\n[3]\tto run option "make love"' a = int(raw_input('\n:- ')) if a==3: P = Population(4, Instrument, {'const_prob':0.7, 'max_children':3}) while not raw_input('\nPress return to continue, anything else to quit:- '): for n,i in enumerate(P.individuals): try: print i.to_instr() print '\nPlaying Sound #%d' %(n+1) i.to_graph(graph_filename) os.system("%s %s &" % (IMAGE_VIEWER, graph_filename)) csd = csound_adapter.CSD() csd.orchestra(i) csd.score('i 1 0 2') csd.play() except OSError: print '\nSkipping this iteration:- Csound crashed' n = int(raw_input('\nWhich sound did you like best: 1, 2, 3 or 4?:- '))-1 m = int(raw_input('Which sound did you like 2nd best: 1, 2, 3 or 4?:- '))-1