def natselect(population, tournsize):
    global globmin
    win, loose = True, False
    # gets two tournament winners
    dad, mom = tournament(population, tournsize,
                          win), tournament(population, tournsize, win)
    # creates children of the tournament winners
    mom, dad = partmapcrossover(dad, mom), partmapcrossover(mom, dad)
    # son = partmapcrossover(dad, mom)

    # tournament to select losers
    worstmom, worstdad = tournament(population, tournsize / 4,
                                    loose), tournament(population,
                                                       tournsize / 4, loose)
    # worstdad = tournament(population, tournsize, loose)
    mutater(mom)
    mutater(dad)
    # mutater(son)

    #### code if i want to do two children
    # make sure we still have that best individual
    if globmin not in population: mom = globmin
    # checks to make sure we are not trying to assign the same individual to
    # two different children
    if worstdad != worstmom:
        population[population.index(worstdad)] = dad
        dad.fitness = fitness(dad)
    population[population.index(worstmom)] = mom
    mom.fitness = fitness(mom)
예제 #2
0
def natselect(popn, iteration):
    tpopn = list()
    while len(tpopn) < POPULATION_SIZE * 8:
        if random.random() < .5:
            child = indermediary_recomb(parentselect(popn))
            mutate(child, iteration)
            tpopn.append(individual(child, fitness(child)))
        else:
            child = discrete_recomb(parentselect(popn))
            mutate(child, iteration)
            tpopn.append(individual(child, fitness(child)))
    return survivorselect(tpopn)
예제 #3
0
def tselection(population, cipher):
    k = 4
    res = []
    best = 1
    bestIndex = 0
    for i in range(5):
        temp = random.randint(0, len(population) - 1)
        res.append(population[temp])

    for i in range(5):
        cur = functions.fitness(str(res[i]), cipher)
        if cur < float(best):
            bestIndex = i
            best = cur

    return res[bestIndex]
예제 #4
0
def elitsm(prev, next, minimum, c):
    besti = 0
    best = 1
    global globalBest
    global globalfit
    k = globalBest, globalfit
    out = 0

    for i in range(len(next)):
        nex = functions.fitness(next[i], c)

        if nex == globalBest:
            out = 1
            break

        if nex < globalBest:
            globalBest = nex
            globalfit = next[i]
            out = 1
            break
    if out == 0:
        next[minimum] = globalfit

    return next
예제 #5
0
#Global Variables
g = 0         #instantaenous generation count
target_ras = 0  #global minima for convergence criteria
max_gen = 50  #generation for exit criteria
size = 100    #population size
mut_prob = 0.1  #overall mutation probability
fittest = []

#generation 0
population = genesis(size)
population = ras_calc(population)


while g <= max_gen: #exit criteria
    #evaluation
    parents = fitness(population)
    fittest.append(parents[0])
    ras_fittest = parents[0].ras

    # convergence criteria
    if ras_fittest <= target_ras:
        break

    #generation update (crossover,mutation,etc)
    g += 1
    children = mate(parents,mut_prob,g,max_gen)
    if children == None:
        break
    children = ras_calc(children)
    parents.extend(children) #
    population = parents
예제 #6
0
파일: B2.py 프로젝트: evedour/ANN_num_rec
        gens_needed = []
        average = 0

        # GA
        for iter in range(iterations):
            best_results_gen = []

            # ο αρχικός πληθυσμός παράγεται τυχαία
            population = np.random.randint(low=0, high=2, size=(num_indiv, 784))
            count = 0
            j = 0

            for gen in range(num_gen-1):
                print(f'Running generation number {gen} (iteration number {iter})')
                # population fitness
                fit = functions.fitness(population, x_test, y_test)
                fittest = np.min(fit)
                elit = population[np.where(fit == fittest)]
                fitness_history[iter, gen] = fittest
                best_results_gen.append(fittest)
                if gen > 0:
                    if best_results_gen[j] == best_results_gen[j-1] or best_results_gen[j] < best_results_gen[j-1] - 0.01 * best_results_gen[j-1]:
                        count += 1

                # επιλογή γονέων
                parents = np.zeros(population.shape)
                for i in range(0, num_indiv):
                    parents[i, :] = functions.select_parents(population, fit, 0.75)

                # crossover
                children = functions.mate(parents.astype(int), crossrate)
예제 #7
0
def GWO_TSP(map_cities, start, my_wolves, max_iter):
    map_cities_dynamic = {}
    wolves_updated = {}
    for i, w in my_wolves.items():
        wolves_updated[i] = w
    for i, m in map_cities.items():
        map_cities_dynamic[i] = m
    alpha_city = {}
    Tour = False
    start_city = map_cities[start]
    my_wolves_sorted = []
    r1, r2, C, A, alpha, beta, delta, direction, path, ll, X1, X2, X3 = [
    ], [], [], [], [], [], [], [], [], [], [], [], []
    a = 2
    i = 0
    r1.append(random.random())
    r1.append(random.random())
    A.append(2 * a * r1[0] - a)
    A.append(2 * a * r1[1] - a)
    path.append(start)
    del map_cities_dynamic[start]
    # loop with max number of iterations / cities / finish the tour
    # next posi is start in ll
    while (Tour != True) and (i < max_iter):
        # calculate the direction of each search wolf to the current city
        for k, w in my_wolves.items():
            r2.append(random.random())
            r2.append(random.random())
            C.append(2 * r2[0])
            C.append(2 * r2[1])
            direction.append(abs(C[0] * start_city[0] - w[0]))
            direction.append(abs(C[1] * start_city[1] - w[1]))
            w.append(direction)
            direction, C, r2 = [], [], []

        # calculate the fitness function and update α,β,δ
        my_wolves_sorted, alpha, beta, delta = functions.fitness(
            start_city, my_wolves)
        # update positions of OMEGA wolves
        for w in my_wolves.keys():
            if (w != alpha[0] and w != beta[0] and w != delta[0]):
                # calculate X1 = xa - a*da, X2, X3
                X1.append(alpha[1][0] - A[0] * alpha[1][2][0])
                X1.append(alpha[1][1] - A[1] * alpha[1][2][1])
                X2.append(beta[1][0] - A[0] * beta[1][2][0])
                X2.append(beta[1][1] - A[1] * beta[1][2][1])
                X3.append(delta[1][0] - A[0] * delta[1][2][0])
                X3.append(delta[1][1] - A[1] * delta[1][2][1])
                my_wolves[w][0] = (X1[0] + X2[0] + X3[0]) / 3
                my_wolves[w][1] = (X1[1] + X2[1] + X3[1]) / 3
                # update Xt (current position) => Xt+1 (next position)
        r1, r2, C, A, X1, X2, X3 = [], [], [], [], [], [], []

        # update parameters
        r1.append(random.random())
        r1.append(random.random())
        r2.append(random.random())
        r2.append(random.random())
        a = 2 * (1 - (i / 10))
        A.append(2 * a * r1[0] - a)
        A.append(2 * a * r1[1] - a)
        C.append(2 * r2[0])
        C.append(2 * r2[1])

        # find the next city
        for n, nxt in map_cities_dynamic.items():
            dist = functions.Euclidien(alpha[1][0], nxt[0], alpha[1][1],
                                       nxt[1])
            alpha_city[n] = dist
        ll = sorted(alpha_city.items(), key=lambda x: x[1])

        # delete the city founded from map_cities_dynamic and add it to path
        if len(map_cities_dynamic) != 0:
            del map_cities_dynamic[ll[0][0]]
            path.append(ll[0][0])
        else:
            Tour = True
            break
        start_city = map_cities[ll[0][0]]
        ll = []
        alpha_city = {}

        i += 1
    return path, wolves_updated
예제 #8
0
def geneticAlgorithm(initPop, crossOvRate, mutationRate, keySize, cip):
    generation = 0
    chromsome = initialChromo(pSize=initPop, keySize=keySize)

    global globalBest
    global globalfit
    for i in range(len(chromsome)):
        gk = functions.fitness(chromsome[i], cip)
        if gk < globalBest:
            globalBest = gk
            globalfit = chromsome[i]

    tempChromsome = []

    mR = int((initPop / 100) * mutationRate)

    #File generation----------you can set this too if you like

    file = open("co3pm1str1run5(SAMPLE FOR TESTING).txt", "w")
    file.write("------------\n")
    file.write("Parameter set number: 1 \n")
    file.write("Crossover: High point crossover \n")
    file.write("Mutation rate: " + str(mutationRate) + "\n")
    file.write("Crossover rate: " + str(crossOvRate) + "\n")
    file.write("Seed: " + str(sd) + "\n")
    file.write("Key size: " + str(keySize) + "\n")
    file.write("Cipher: " + str(cip) + "\n")
    file.write("Initital population: " + str(initPop) + "\n")
    file.write("----------------\n")
    file.write("\n")

    for i in range(100):
        while True:

            p1 = tselection(chromsome, cip)
            o = p1
            p2 = tselection(chromsome, cip)
            q = p2

            rand = random.randint(0, 100)
            if rand <= crossOvRate:

                #parameter4-------------------------------------------
                #Crossovers ---------- Uncomment one of below to test-

                # p1,p2 = uniformCo(str(p1),str(p2))
                # p1,p2 = highPointCO(p1,p2)
                p1, p2 = onePointCO(str(p1), str(p2))

                p1 = ''.join(p1)
                p2 = ''.join(p2)
            o1 = p1
            q1 = p2

            if mR != 0:
                p1 = mutation(p1)
                p2 = mutation(p2)
                mR = mR - 2

            if len(tempChromsome) != initPop:
                tempChromsome.append(''.join(p1))
                if len(tempChromsome) != initPop:
                    tempChromsome.append(''.join(p2))

            if len(tempChromsome) == initPop:
                break

        fitnesesss = [functions.fitness(i, cip) for i in tempChromsome]
        avg = statistics.mean(fitnesesss)
        mini = (min(fitnesesss))

        minimum = (fitnesesss.index(min(fitnesesss)))
        # print(minimum,min(fitnesesss))

        tempChromsome = elitsm(chromsome, tempChromsome, minimum, cip)

        chromsome = copy.deepcopy(tempChromsome)

        tempChromsome.clear()

        # Applying crossover rate
        cR = int((initPop / 100) * crossOvRate)

        # Applying mutation rate
        mR = int((initPop / 100) * mutationRate)
        generation = generation + 1

        print("Best fitness:", globalBest, "  ;  Average fitness:", avg)
        tmp = "Best fitness: " + str(
            globalBest) + "  ;  Average fitness: " + str(avg) + "\n"

        file.write(tmp)

    file.write("Best solution fitness: " + str(globalBest) +
               "  ,  Best solution chromosome: " + str(globalfit))
    file.close()
def evaluate_population(cars, models, track, win, dt, draw_vision_lines,
                        generation_number):

    pygame.display.update()

    pause = False
    running = True
    while running:
        #pygame.time.delay(dt)
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                running = False

            if event.type == pygame.KEYDOWN and event.key == pygame.K_v:
                draw_vision_lines = not draw_vision_lines

            if event.type == pygame.KEYDOWN and event.key == pygame.K_p:
                pause = True

            if event.type is pygame.QUIT:
                pygame.quit()
                quit()

        pause = check_pause(pause, win)

        # Draw track
        win.blit(track.surface, (0, 0))

        for model, icar in zip(models, cars):

            if icar.running:

                # Update car position and vision
                icar.vision()
                vision_lines, intersection_points, distance = wall_distance(
                    icar, track)
                distance = distance.reshape((1, 5))

                # Propagate through network
                nn_output = model.predict(distance)
                take_action(nn_output, icar)

                icar.update(dt=dt)

                crash_detection(icar, track)
                fitness(icar, distance, dt)

                draw_vision(draw_vision_lines, win, vision_lines,
                            intersection_points)

            icar.draw_model(win)

        running_list = [icar.running for icar in cars]
        if not any(running_list):
            running = False

        write_text(win, generation_number)
        pygame.display.update()

    fitness_list = [icar.fitness for icar in cars]

    return fitness_list, draw_vision_lines
예제 #10
0
        
        if event.type is pygame.QUIT: 
            pygame.quit()
            quit()
    
    keyes = pygame.key.get_pressed()
    if keyes[pygame.K_LEFT]:
        icar.steering_angle -= icar.steering_rate
    elif keyes[pygame.K_RIGHT]:
        icar.steering_angle += icar.steering_rate
    else:
        icar.steering_angle = 0

    icar.vision()
    vision_lines, intersection_points, distance = wall_distance(icar, track)
    icar.update(dt=dt)
    
    crash_detection(icar, track)
    fitness(icar, distance, dt)
    
    draw_vision(draw_vision_lines, win, vision_lines, intersection_points)
    icar.draw_model(win)
    
    if not icar.running:
        running = False
    
    pause = check_pause(pause, win)
    pygame.display.update()
    
        
pygame.quit()