Beispiel #1
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)
Beispiel #2
0
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
Beispiel #4
0
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]
Beispiel #5
0
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']
	
Beispiel #6
0
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
Beispiel #7
0
def test_if_raises_typeerror_on_incorrect_B_param():
    with pytest.raises(TypeError):
        pop = Population(mock_params, mock_judge, 10, '10')
Beispiel #8
0
def test_if_creates_empty_population():
    pop = Population(mock_params, mock_judge, 10, 10)
    assert len(pop.parents) == 0
Beispiel #9
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(
    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)