Esempio n. 1
0
def main():
    pop = init.initPop(300)
    itera = 100  #迭代次数
    each = 30  #每轮迭代的遗传计算次数
    tplt = "{:8}\t{:8}\t{:8}"
    gen = Genetic()
    bests = []  #用以存储每代最优值
    print(tplt.format("Gen", "Avg", "Best"))
    for i in range(1, itera):
        pop = gen.evaluate(pop)
        bests.append(gen.printGen(pop, i))
        for j in range(1, each):
            rand = random.random()
            if rand < 0.7:  #变异率设为0.3
                ind = gen.select(pop)
                pop.remove(ind)
                ind.mark = 2
                ind.gene = gen.mutate(ind.gene, 4)
                pop.append(ind)
            else:
                pop = gen.mate(pop)
    res = numpy.array(bests)
    x = numpy.arange(1, 99)
    y = res[x]
    pyplot.title('GP result')
    pyplot.xlabel('Gen')
    pyplot.ylabel('Best')
    pyplot.plot(x, y)
    pyplot.show()
Esempio n. 2
0
def test_mutate():
    g = Genetic()
    for i in range(100):
        a = Individual()

        o = g.mutate(a)
        assert not o.dna.__contains__(None)
Esempio n. 3
0
 def test_mutate2(self):
     point, mutations = Genetic.mutate((1, 0), 0, 0.5, 0.5)
     self.assertEqual((1, 0), point)
     self.assertEqual(0, mutations)
Esempio n. 4
0
 def test_mutate(self):
     point, mutations = Genetic.mutate((1, 0), 1, 0.5, 0.5)
     self.assertNotEqual((1, 0), point)
     self.assertEqual(2, mutations)
def main():
    filename = newFile()
    simu = []
    for x in range(MAX_PARALLEL):
        simu.append(Multi())
        simu[-1].multi_start()
    joints_seg = simu[0].parent_pipe.recv()
    #simulation.setup()
    #################### genetic
    #fitness odleglosc od zrodka (x albo y) plus 10x za kazda noge na ziemi minus[kat podst - aktualny] - x3(xyx)

    #10*sim_data[1][1] - (0 - abs(sim_data[2][1])) - (0 - abs(sim_data[2][2])) + [10*x for x in sim_data[0]]
    genetica = Genetic(POPILATION_SIZE, CHROMOSOME_SIZE, GAIT_STEPS, MAX_MIN,
                       joints_seg, BEST_SAMPLES, LUCKY_FEW, TOURNAMENT,
                       MUTATION_CHANCE)
    #resetBasePositionAndOrientation
    population = []
    population = genetica.gen_population()
    #print(population)
    #population[0] = convertToSim(ppp[0])
    #population[1] = convertToSim(ppp[1])

    pop_data = []
    pop_fitness = [0, 0]
    for generation in range(GENERATIONS):
        print("Generation:",
              str(generation) + " previous 2 best fitness: ",
              str(pop_fitness[0]), str(pop_fitness[1]))
        weighted_population = []

        slicedd = slicePop(population)
        #print(len(slicedd))
        for slic in slicedd:
            #print('.',end=" ",flush=True)
            #sys.stdout.flush()
            #sys.stdout.write('.')
            #sys.stdout.flush()

            for idx, individual in enumerate(slic):
                #print('lel')
                #print(individual)
                #print('pop')
                #print(len(population))
                #print('simu')
                #print(len(simu))
                #print(idx)
                simu[idx].indi = individual
                simu[idx].parent_pipe.send(individual)

            #print('lel2')
            t = 0
            while True:
                #print('in loop1')
                try:
                    for sim in simu:
                        #print('in loop1 lel')
                        if sim.simok == False:
                            rec = sim.parent_pipe.recv()
                            if rec == "simok":
                                sim.simok = True
                                t += 1
                    if t == MAX_PARALLEL:
                        t = 0
                        break
                except:
                    continue
            #print('lel3')
            while True:
                #print('in loop2')
                try:
                    for sim in simu:
                        rec = sim.parent_pipe.recv()
                        contact, base_pos, base_angle = rec[-1]
                        if len(contact) == 6 and len(base_pos) == 3 and len(
                                base_angle) == 3:
                            sim.data = rec
                            sim.parent_pipe.send('dataok')
                            t += 1
                    if t == MAX_PARALLEL:
                        t = 0
                        break
                except:
                    continue

            for sim in simu:
                sim.simok = False
                sim.parent_pipe.send('reset')
            #print('lel4')
            while True:
                #print('in loop3')
                try:
                    for sim in simu:
                        rec = sim.parent_pipe.recv()
                        if rec == "resok":
                            t += 1
                    if t == MAX_PARALLEL:
                        t = 0
                        break
                except:
                    continue

            for sim in simu:
                #fitness_val = genetica.fitness(sim.data[0],sim.data[1],sim.data[2])
                dd = 0
                for x in sim.data:
                    #print(dd)
                    #print(len(sim.data))
                    if x == sim.data[-1]:
                        dd += genetica.fitness(x[0], x[1], x[2])
                    else:
                        dd += genetica.stability(x[0], x[1], x[2])
                fitness_val = dd
                #print("lelelee")
                #print(sim.indi)
                individual = convertToGen(sim.indi)
                #print("lvggjvjhg")
                #print(len(individual))
                pair = (individual, fitness_val)
                weighted_population.append(pair)

        population = []
        #for x in range(GAIT_STEPS)
        pop_sorted, pop_fitness = genetica.sort_pop(weighted_population)
        #print(pop_sorted[0])
        print(pop_fitness)
        #saveToFile(str(generation)+" best fitness: " + str(pop_fitness[0]), [pop_sorted + pop_fitness])
        saveToFile(
            filename, "Generation: " + str(generation) + " best fitness: " +
            str(pop_fitness[0]), [pop_fitness[:15], pop_sorted[:15]])
        #print("saved to file")

        #2 parents survive
        a = convertToSim(pop_sorted[0])
        b = convertToSim(pop_sorted[1])
        population = [a, b]
        #print("D-1")
        #print(a)
        #print("D0")
        #print(b)
        #print("D1")
        #print(population)
        #nn = [genetica.mutate(a,1,1), genetica.mutate(a,1,1), genetica.mutate(b,1,1)]
        y = 0
        while y < 2:
            z = genetica.mutate(a, 1, 1)
            if z not in population:
                population.append(z)
                y += 1
        #print("D2")
        #print(z)
        y = 0
        while y < 2:
            z = genetica.mutate(b, 1, 1)
            if z not in population:
                population.append(z)
                y += 1
        #print("D3")
        #print(z)
        #population = [a, b, genetica.mutate(a,1,1), genetica.mutate(a,1,1), genetica.mutate(b,1,1)]

        old_sel = genetica.select_population(pop_sorted)
        #print("old_sel")
        #print(old_sel[0])
        #for ind in old_sel:
        #    population.append(convertToSim(ind))
        #old_sel = genetica.tournamen(old_s el)
        #print(len(old_sel[0]))
        #print(old_sel)

        children = genetica.get_children(old_sel, len(population))

        #for x in range(TOURNAMENT):
        #    population.append(genetica.gen_chromosome())

        for indiv in children:
            #print("D4x")
            #print(indiv)
            while True:
                #print('child loop2')
                #print("D4445")
                #print(indiv)
                #print('size')
                #print(len(indiv))
                ind = convertToSim(indiv)
                #print("D5")
                #print(indiv)
                mu = genetica.mutate(ind)
                if mu not in population:
                    population.append(mu)
                    break

        #print("lele2")
        #print("population size")
        #print(len(population))
        #print(population)
    print("end")
    for sim in simu:
        sim.multi_stop()
def main():
    simu = []

    for x in range(MAX_PARALLEL):
        simu.append(Multi())
        simu[-1].multi_start()

    t=0
    while not (t == MAX_PARALLEL):
        for sim in simu:
            if sim.parent_pipe.poll():
                joints_seg = sim.parent_pipe.recv()
                if len(joints_seg)==6:
                    t+=1
    #simulation.setup()
#################### genetic
#fitness odleglosc od zrodka (x albo y) plus 10x za kazda noge na ziemi minus[kat podst - aktualny] - x3(xyx)

#10*sim_data[1][1] - (0 - abs(sim_data[2][1])) - (0 - abs(sim_data[2][2])) + [10*x for x in sim_data[0]]
    genetica = Genetic(POPILATION_SIZE, CHROMOSOME_SIZE, GAIT_STEPS, MAX_MIN, joints_seg, BEST_SAMPLES, LUCKY_FEW, TOURNAMENT, MUTATION_CHANCE, CROSSOVER_CHANCE)
#resetBasePositionAndOrientation
    #population = []
    gen = 0

    ##########################################prev
    population,gen, prevfile = readFromFile('/run/media/desu/n1/projekty/spider/algorithm/gen/simple/uproszczenie_kopiowanie/generations-02_05_2019_03_49.txt')
    temp = []
    for ind in population:
        temp.append(convertToSim(ind))
    population = temp
    del temp
    filename, history =newFile(prevfile)
    ##
    ###############################################new
    '''
    filename, history =newFile()
    population = genetica.gen_population()

    ##
    '''

    #print("population F{}".format(population))
    logger.debug('new pop: %s', str(population))

    #print(population)
    #population[0] = convertToSim(ppp[0])
    #population[1] = convertToSim(ppp[1])

    pop_data = []
    pop_fitness = [0,0]
    pop_sorted = [0,0]



    for generation in range(1,GENERATIONS+1):
        #FITNESS_MAX_HISTORY.append(pop_fitness[0])
        #show_plot(fig, li, generation)
        #print("Generation:", str(generation) + " previous 2 best fitness: ",str(pop_fitness[0]), str(pop_fitness[1]) )
        #print("Generation: {}, previous 2 best fitness: {}, {}, chromosomes: {}, {}".format(generation+gen,pop_fitness[0],pop_fitness[1], pop_sorted[0], pop_sorted[1]) )
        print("Generation:", str(generation+gen) + " previous 2 best fitness: ",str(pop_fitness[0]), str(pop_fitness[1]) )
        weighted_population = []

        slicedd = slicePop(population)
        #print(len(slicedd))

        logger.debug('check1 pop: %d', len(population))
        popCurr = 0
        for slic in slicedd:
            print("current populations", popCurr, "of",POPILATION_SIZE, end="\r")
            for idx, individual in enumerate(slic):
                simu[idx].indi = individual
                #print(individual)
                y = copytoLegs(individual)
                logger.debug('sent: %s', str(y))
                y = stepRepeat(y)
                logger.debug('repeated %s', y)
                logger.debug('%d', len(y))
                simu[idx].parent_pipe.send(y)

            t=0
            while not (t == MAX_PARALLEL):#if all processes sent data
                for sim in simu:
                    if sim.simok == False:
                        if sim.parent_pipe.poll():
                            rec = sim.parent_pipe.recv()
                            logger.debug('rec1 %s', str(rec))
                            if rec == "simok":
                                sim.simok = True
                                t+=1
            t=0
            while not (t == MAX_PARALLEL):
                for sim in simu:
                    if sim.parent_pipe.poll():
                        rec = sim.parent_pipe.recv()#[-1]#!!!!!!!!!!!!!!!!!tylko ostatnie biore? i potem zapisuje? co z polkrokami
                        logger.debug('rec2 %s', str(rec))
                        logger.debug('rec2 len %d', len(rec))
                        if len(rec)==GAIT_STEPS*STEP_REPEAT:#if len(contact) == 6 and len(base_pos) == 3 and len(base_angle) == 3:
                            #contact, base_pos, base_angle, diff = rec
                            sim.data = rec
                            sim.parent_pipe.send('dataok')
                            logger.debug('M dataok sent')
                            t+=1
            t=0

            for sim in simu:
                sim.simok = False
                sim.parent_pipe.send('reset')
                logger.debug('M reset sent')

            while not (t == MAX_PARALLEL):
                for sim in simu:
                    if sim.parent_pipe.poll():
                        rec = sim.parent_pipe.recv()
                        logger.debug('rec3 %s', str(rec))
                        if rec == "resok":
                            t+=1
            t=0

            for sim in simu:
                dd = 0
                for x in sim.data:
                    #print(len(sim.data))
                    if x == sim.data[-1]:
                        dd+=genetica.fitness(x)
                    else:
                        dd+=genetica.stability(x)
                fitness_val = dd

                individual = convertToGen(sim.indi)

                pair = (individual, fitness_val)
                weighted_population.append(pair)
            popCurr+=MAX_PARALLEL
        population = []

        logger.debug('check2')
        #for x in range(GAIT_STEPS)
        #pop_sorted, pop_fitness = genetica.sort_pop(weighted_population)
        pop_sorted,  pop_fitness = genetica.sort_pop(weighted_population)
        #pop_sort = [pop_sorted, pop_fitness]
        #print(pop_sorted[0])
        logger.debug('%s',str(pop_fitness))
        #saveToFile(str(generation)+" best fitness: " + str(pop_fitness[0]), [pop_sorted + pop_fitness])
        #saveToFile(filename, "Generation: " + str(generation)+ " best fitness: " + str(pop_fitness[0]), [pop_fitness[:15], pop_sorted[:15]])
        saveToFile(filename, "Generation: " + str(generation+gen)+ " best fitness: " + str(pop_fitness[0]), [pop_fitness, pop_sorted])
        saveToFile(history, str(generation+gen)+ "," + str(pop_fitness[0]), [])
        #print("saved to file")
        logger.debug('check3')

        #2 parents survive
        #print(pop_sorted[1])


        for x in range(CHROM_TO_COPY):
            a = convertToSim(pop_sorted[x])
            if (a not in population):
                population.append(a)
            for y in range(0, 5):
                while (1):
                    b = genetica.mutate(a,1,GAIT_STEPS)
                    if (b not in population):
                        population.append(b)
                        break
            for y in range(0, 5):
                while (1):
                    b = genetica.mutate(a,1,GAIT_STEPS, RANDOM_MUTATE_POSITIONS)
                    if (b not in population):
                        population.append(b)
                        break


        new_gen_population = genetica.gen_population()
        new_gen_population = random.sample(new_gen_population, NEWGENES)

        population += new_gen_population

        logger.debug('check4')
        logger.debug('INITIAL population: %s', str(population))

        old_sel = pop_sorted

        pop = [x[0] for x in weighted_population] #population
        b = [x[1] for x in weighted_population] #fitness

        logger.debug('pop: %s', str(pop))
        logger.debug('fitn: %s', str(b))

        children, parents = genetica.get_children(pop,b, len(population)+LUCKY_FEW)

        logger.debug('check5')
        logger.debug('children: %s', str(children))
        logger.debug('parents: %s', str(parents))


        lucky = genetica.select_lucky_few(list(pop), parents)


        logger.debug('check6')

        for x in lucky:
            y = convertToSim(x)

            logger.debug('lucky: %s', str(y))

            population.append(y)

        logger.debug('population after: %d', len(population))
        logger.debug('check7')

        for indiv in children:
            ind = convertToSim(indiv)
            while (1):
                mu = genetica.mutate(ind, steps_num = random.randint(0,GAIT_STEPS))
                if mu not in population:
                    population.append(mu)
                    break
        logger.debug('check8')

    print("end")
    for sim in simu:
        sim.multi_stop()