예제 #1
0
def main():

    random.seed()
    numpy.random.seed()

    string_length = 8
    popsize = 20
    mating_pool_size = int(popsize * 0.5)  # has to be even
    tournament_size = 3
    mut_rate = 0.2
    xover_rate = 0.9
    gen_limit = 50

    # initialize population
    gen = 0  # initialize the generation counter
    population = initialization.permutation(popsize, string_length)
    fitness = []
    for i in range(0, popsize):
        fitness.append(evaluation.fitness_8queen(population[i]))
    print("generation", gen, ": best fitness", max(fitness), "average fitness",
          sum(fitness) / len(fitness))

    # evolution begins
    while gen < gen_limit:

        # pick parents
        parents_index = parentSelection.MPS(fitness, mating_pool_size)
        #        parents_index = parentSelection.tournament(fitness, mating_pool_size, tournament_size)
        #        parents_index = parentSelection.random_uniform(popsize, mating_pool_size)

        # in order to randomly pair up parents
        random.shuffle(parents_index)

        # reproduction
        offspring = []
        offspring_fitness = []
        i = 0  # initialize the counter for parents in the mating pool
        # offspring are generated using selected parents in the mating pool
        while len(offspring) < mating_pool_size:

            # recombination
            if random.random() < xover_rate:
                off1, off2 = recombination.permutation_cut_and_crossfill(
                    population[parents_index[i]],
                    population[parents_index[i + 1]])
            else:
                off1 = population[parents_index[i]].copy()
                off2 = population[parents_index[i + 1]].copy()

            # mutation
            if random.random() < mut_rate:
                off1 = mutation.permutation_swap(off1)
            if random.random() < mut_rate:
                off2 = mutation.permutation_swap(off2)

            offspring.append(off1)
            offspring_fitness.append(evaluation.fitness_8queen(off1))
            offspring.append(off2)
            offspring_fitness.append(evaluation.fitness_8queen(off2))
            i = i + 2  # update the counter

        # form the population of next generation
        population, fitness = survivorSelection.mu_plus_lambda(
            population, fitness, offspring, offspring_fitness)
        #        population, fitness = survivorSelection.replacement(population, fitness, offspring, offspring_fitness)
        #        population, fitness = survivorSelection.random_uniform(population, fitness, offspring, offspring_fitness)

        gen = gen + 1  # update the generation counter
        print("generation", gen, ": best fitness", max(fitness),
              "average fitness",
              sum(fitness) / len(fitness))

    # evolution ends

    # print the final best solution(s)
    k = 0
    for i in range(0, popsize):
        if fitness[i] == max(fitness):
            print("best solution", k, population[i], fitness[i])
            k = k + 1
def mainTask(exchange, exchangeFit, migrate, migrateFit, procNum, migrateTo,
             migrateToF, migrateFrom, migrateFromF):

    random.seed()
    numpy.random.seed()
    popsize = 400
    mating_pool_size = int(popsize * 0.5)
    tournament_size = 10
    mut_rate = 0.2  # our mutation operator improvement is inside the main generation loop where it is updated dynamically according to our improvement formula
    xover_rate = 0.9
    gen_limit = 500
    prevFitness = [
    ]  # we store previous fitnesses for past generattions so that if multiple generations start pproducing the same best fitness we can stop the algorithm
    start_time = time.time()  # this is used to calculate the runtime
    iteration = 0  # this is a variable used to kkeep count of how many migrations has happened , we use it to makke sure we don't try to go out of bounds when moving to population2

    # initialize population

    cityList = []
    file = open(
        "TSP_Uruguay_734.txt", 'r'
    )  # we read the file , this can be changed to any file name (sahara or canada etc)
    words = list(file.read().split())
    for i in range(0, len(words), 3):
        cityList.append(
            City(float(words[i + 1]), float(words[i + 2]), "City",
                 int(words[i])))
    file.close()

    distanceList = [
    ]  # this is a list to precalculate distances in order for us to find them instead of calculating every time
    for i in range(0, len(cityList)):
        distToCity = []
        for j in range(0, len(cityList)):
            distToCity.append(cityList[i].getDistance(cityList[j]))
        distanceList.append(distToCity)
    gen = 0  # initialize the generation counter
    population = initialization.permutation(popsize, cityList)
    fitness = []
    for i in range(0, popsize):
        fitness.append(evaluation.fitness_TSP(population[i], distanceList))
    print("generation", gen, ": best fitness", (1 / (max(fitness))),
          "average fitness", 1 / (sum(fitness) / len(fitness)))

    while gen < gen_limit:

        # pick parents
        parents_index = parentSelection.tournament(fitness, mating_pool_size,
                                                   tournament_size)
        random.shuffle(parents_index)

        # reproduction
        offspring = []
        offspring_fitness = []
        i = 0  # initialize the counter for parents in the mating pool
        while len(offspring) < mating_pool_size:

            # recombination
            if random.random() < xover_rate:
                off1, off2 = recombination.order_cross(
                    population[parents_index[i]],
                    population[parents_index[i + 1]])
            else:
                off1 = population[parents_index[i]].copy()
                off2 = population[parents_index[i + 1]].copy()

            # mutation
            if random.random() < mut_rate:
                off1 = mutation.permutation_swap(off1)
            if random.random() < mut_rate:
                off2 = mutation.permutation_swap(off2)
            offspring.append(off1)
            offspring_fitness.append(evaluation.fitness_TSP(
                off1, distanceList))
            offspring.append(off2)
            offspring_fitness.append(evaluation.fitness_TSP(
                off2, distanceList))
            i = i + 2  # update the counter

        # survivor selection
        population, fitness = survivorSelection.mu_plus_lambda(
            population, fitness, offspring, offspring_fitness)

        gen = gen + 1
        mut_rate = mut_rate - (0.1 * mut_rate *
                               (gen / gen_limit))  # improved mutation operator

        #Island Model
        chosenIndex = []
        if ((gen % 10) == 0):
            for j in range(0, 10):  # select 10 best individuals
                current = 0
                maxIndex = 0
                maxim = 0
                for i in range(0, len(fitness)):
                    current = fitness[i]
                    if ((current > maxim) and (i not in chosenIndex)):
                        maxim = current
                        maxIndex = i
                chosenIndex.append(maxIndex)
                if (len(exchange) < 10):
                    exchange.append(population[maxIndex])
                    exchangeFit.append(fitness[maxIndex])
                else:
                    exchange.pop(0)
                    exchangeFit.pop(0)
                    exchange.append(population[maxIndex])
                    exchangeFit.append(fitness[maxIndex])
            migrateTo.append(exchange)
            migrateToF.append(exchangeFit)
            if (
                    procNum == 2
            ):  #we check to see if this is population2 before moving individuals to it , because in population 1 there is no one to migrate yet so there's no need to run this for pop 1
                if (
                        iteration < len(migrateFromF)
                ):  #migration start , and check if there's any more migrations left
                    for i in range(0, popsize):
                        for x in range(0, len(migrateFromF[iteration])):
                            if (migrateFromF[iteration][x] > fitness[i]):
                                population[i] = migrateFrom[iteration][x]
                                fitness[i] = migrateFromF[iteration][x]
                    migrateFrom[iteration] = []
                    migrateFromF[iteration] = []
                iteration = iteration + 1
            #end Island Model

        #generation limitation method
        if (len(prevFitness) < 10):
            prevFitness.append((1 / (max(fitness))))
        else:
            prevFitness.pop(0)
            prevFitness.append((1 / (max(fitness))))
        print("population: ", procNum, "generation", gen, ": best fitness",
              (1 / (max(fitness))), "average fitness",
              1 / (sum(fitness) / len(fitness)))
        print("--- %s seconds ---" % (time.time() - start_time))
        if (len(prevFitness) >= 10):
            count = 0
            for i in range(0, len(prevFitness)):
                if ((1 / (max(fitness))) == prevFitness[i]):
                    count = count + 1
            if (count == 10):
                gen = gen_limit
        # generationn Limitation end
    return population, fitness
예제 #3
0
def main():

    experiment = [
        # nothing yet
    ]

    stat = ["mean", "std", "aes", "sr"]

    evos = 0

    while evos < 20:

        trial = [-1, []]    # [seccessed-generatiohn, best-fitness]
        recorded = False


        random.seed()
        numpy.random.seed()

        string_length = 8
        popsize = 20    # original 20
        mating_pool_size = int(popsize*0.5) # has to be even
        tournament_size = 4
        mut_rate = 0.2
        xover_rate = 0.9
        gen_limit = 50

        # initialize population
        gen = 0 # initialize the generation counter
        population = initialization.permutation(popsize, string_length)
        fitness = []
        for i in range(0, popsize):
            fitness.append(evaluation.fitness_8queen(population[i]))
        print("generation", gen, ": best fitness", max(fitness), "average fitness", sum(fitness)/len(fitness))

        # evolution begins
        while gen < gen_limit:

            # pick parents
            #parents_index = parentSelection.MPS(fitness, mating_pool_size)
            parents_index = parentSelection.tournament(fitness, mating_pool_size, tournament_size)
            #parents_index = parentSelection.random_uniform(popsize, mating_pool_size)

            # in order to randomly pair up parents
            random.shuffle(parents_index)

            # reproduction
            offspring =[]
            offspring_fitness = []
            i= 0 # initialize the counter for parents in the mating pool
            # offspring are generated using selected parents in the mating pool
            while len(offspring) < mating_pool_size:

                # recombination
                if random.random() < xover_rate:
                    off1,off2 = recombination.permutation_cut_and_crossfill(population[parents_index[i]], population[parents_index[i+1]])
                else:
                    off1 = population[parents_index[i]].copy()
                    off2 = population[parents_index[i+1]].copy()

                # mutation
                if random.random() < mut_rate:
                    off1 = mutation.permutation_swap(off1)
                if random.random() < mut_rate:
                    off2 = mutation.permutation_swap(off2)

                offspring.append(off1)
                offspring_fitness.append(evaluation.fitness_8queen(off1))
                offspring.append(off2)
                offspring_fitness.append(evaluation.fitness_8queen(off2))
                i = i+2  # update the counter

            # form the population of next generation
            population, fitness = survivorSelection.mu_plus_lambda(population, fitness, offspring, offspring_fitness)
    #        population, fitness = survivorSelection.replacement(population, fitness, offspring, offspring_fitness)
    #        population, fitness = survivorSelection.random_uniform(population, fitness, offspring, offspring_fitness)

            gen = gen + 1  # update the generation counter
            print("generation", gen, ": best fitness", max(fitness), "average fitness", sum(fitness)/len(fitness))

            trial[1].append( max(fitness) )
            #trial[1].append( sum(fitness)/len(fitness) )

            if max(fitness) == 28 and recorded == False:
                trial[0] = gen + 1
                recorded = True

        # evolution ends

        # print the final best solution(s)
        k = 0
        for i in range (0, popsize):
            if fitness[i] == max(fitness):
                print("best solution", k, population[i], fitness[i])
                k = k+1

        evos = evos + 1
        experiment.append(trial)

    bests = []
    sr = []

    for trial in experiment:
        final = trial[1][49]
        bests.append(final)

        if trial[0] != -1:
            sr.append(trial[0])

    stat[0] = numpy.mean(bests)
    stat[1] = numpy.std(bests)
    stat[3] = sr
    stat[2] = numpy.mean(stat[3])




    output_file = open("trace.js", "a")

    output_file.write("let tourn_miu = ")
    output_file.write(json.dumps(experiment))
    output_file.write(";\n")
    output_file.write("let tourn_miu_stat = ")
    output_file.write(json.dumps(stat))
    output_file.write(";\n")

    output_file.close()
def main():

    random.seed()
    numpy.random.seed()

    string_length = 8
    popsize = 20
    mating_pool_size = int(popsize * 0.5)  # has to be even
    tournament_size = 3
    mut_rate = 0.2
    xover_rate = 0.9
    gen_limit = 100

    # initialize population
    cityList = []
    c1 = City(2, 5, "c1")
    c2 = City(4, 5, "c2")
    c3 = City(9, 5, "c3")
    c4 = City(12, 10, "c4")
    c5 = City(20, 11, "c5")
    c6 = City(13, 14, "c6")
    c7 = City(20, 19, "c7")
    c8 = City(21, 12, "c8")
    c9 = City(210, 120, "c9")
    c10 = City(165, 22, "c10")
    c11 = City(35, 26, "c11")
    c12 = City(50, 50, "c12")
    c13 = City(205, 120, "c13")
    c14 = City(154, 20, "c14")
    c15 = City(150, 200, "c15")
    c16 = City(130, 150, "c16")
    c17 = City(135, 125, "c17")
    c18 = City(110, 145, "c18")
    c19 = City(25, 132, "c19")
    c20 = City(60, 124, "c20")
    cityList.append(c1)
    cityList.append(c2)
    cityList.append(c3)
    cityList.append(c4)
    cityList.append(c5)
    cityList.append(c6)
    cityList.append(c7)
    cityList.append(c8)
    cityList.append(c9)
    cityList.append(c10)
    cityList.append(c11)
    cityList.append(c12)
    cityList.append(c13)
    cityList.append(c14)
    cityList.append(c15)
    cityList.append(c16)
    cityList.append(c17)
    cityList.append(c18)
    cityList.append(c19)
    cityList.append(c20)
    gen = 0  # initialize the generation counter
    population = initialization.permutation(popsize, cityList)
    fitness = []
    for i in range(0, popsize):
        fitness.append(evaluation.fitness_8queen(population[i]))
    print("generation", gen, ": best fitness", max(fitness), "average fitness",
          sum(fitness) / len(fitness))

    # evolution begins
    while gen < gen_limit:

        # pick parents
        #parents_index = parentSelection.MPS(fitness, mating_pool_size)
        parents_index = parentSelection.tournament(fitness, mating_pool_size,
                                                   tournament_size)
        #        parents_index = parentSelection.random_uniform(popsize, mating_pool_size)

        # in order to randomly pair up parents
        random.shuffle(parents_index)

        # reproduction
        offspring = []
        offspring_fitness = []
        i = 0  # initialize the counter for parents in the mating pool
        # offspring are generated using selected parents in the mating pool
        while len(offspring) < mating_pool_size:

            # recombination
            if random.random() < xover_rate:
                off1, off2 = recombination.permutation_cut_and_crossfill(
                    population[parents_index[i]],
                    population[parents_index[i + 1]])
            else:
                off1 = population[parents_index[i]].copy()
                off2 = population[parents_index[i + 1]].copy()

            # mutation
            if random.random() < mut_rate:
                off1 = mutation.permutation_swap(off1)
            if random.random() < mut_rate:
                off2 = mutation.permutation_swap(off2)

            offspring.append(off1)
            offspring_fitness.append(evaluation.fitness_8queen(off1))
            offspring.append(off2)
            offspring_fitness.append(evaluation.fitness_8queen(off2))
            i = i + 2  # update the counter

        # form the population of next generation
        population, fitness = survivorSelection.mu_plus_lambda(
            population, fitness, offspring, offspring_fitness)
        #        population, fitness = survivorSelection.replacement(population, fitness, offspring, offspring_fitness)
        #        population, fitness = survivorSelection.random_uniform(population, fitness, offspring, offspring_fitness)

        gen = gen + 1  # update the generation counter
        print("generation", gen, ": best fitness", max(fitness),
              "average fitness",
              sum(fitness) / len(fitness))

    # evolution ends

    # print the final best solution(s)
    k = 0
    for i in range(0, popsize):
        if fitness[i] == max(fitness):
            print("best solution", k)
            for j in range(0, len(population[i])):
                print("city : ", population[i][j].name, "position : (",
                      population[i][j].x, ",", population[i][j].y, ")")
            print("fitness :", fitness[i])
            k = k + 1
예제 #5
0
파일: main.py 프로젝트: ERElli/CS3201-Final
def main():
    checkSysArgs()
    distances = load_file(sys.argv[1])
    if sys.argv[1] == "WesternSahara":
        filename = "../TSP_WesternSahara_29.txt"
    elif sys.argv[1] == "Uruguay":
        filename = "../TSP_Uruguay_734.txt"
    elif sys.arg[1] == "Canada":
        filename = "../TSP_Canada_4663.txt"
    string_length = len(distances)
    popsize = 100
    mating_pool_size = int(popsize * 0.5)  # has to be even
    tournament_size = 6
    mut_rate = 0.3
    xover_rate = 0.9
    gen_limit = 2500
    fitnessThreshold = 20
    plot_population = []

    gen = 0
    population = initialization.permutation(popsize, string_length)

    for i in range(popsize):
        population[i].fitness = evaluation.fitness(population[i], distances)

    maxFitness = 0
    totalFitness = 0
    prev_averageFitness = 10000
    convergence_counter = 0
    scramble = False
    gen_points = [50,100,150]
    while convergence_counter < 300:
        parents = parentSelection.tournament_sel(population, mating_pool_size, tournament_size)
        # parents = parentSelection.MPS(population, mating_pool_size)

        random.shuffle(parents)

        offspring = []
        i = 0

        while len(offspring) < mating_pool_size:

            # RECOMBINATION
            if random.random() < xover_rate:
                if gen < gen_points[0]:
                    # off1, off2 = recombination.Alternating_Edges(parents[i], parents[i+1])
                    # off1, off2 = recombination.cut_and_crossfill(parents[i], parents[i + 1])
                    # off1, off2 = recombination.OrderCrossover(parents[i], parents[i + 1])
                    # off1, off2 = recombination.PMX(parents[i], parents[i + 1])
                    off1 = recombination.sequential_constructive_crossover(parents[i], parents[i+1], distances)
                    off2 = recombination.sequential_constructive_crossover(parents[i], parents[i+1], distances)
                else:
                    # off1, off2 = recombination.Alternating_Edges(parents[i], parents[i+1])
                    # off1, off2 = recombination.cut_and_crossfill(parents[i], parents[i + 1])
                    # off1, off2 = recombination.OrderCrossover(parents[i], parents[i + 1])
                    off1, off2 = recombination.PMX(parents[i], parents[i + 1])
                    # off1 = recombination.sequential_constructive_crossover(parents[i], parents[i+1], distances)
                    # off2 = recombination.sequential_constructive_crossover(parents[i], parents[i+1], distances)
            else:
                off1 = parents[i]
                off2 = parents[i + 1]

            # MUTATION
            if random.random() < mut_rate:
                # off1 = mutation.insert(off1)
                off1 = mutation.inversion(off1)
                # off1 = mutation.random(off1)
                # off1 = mutation.scramble(off1)
                # off1 = mutation.swap(off1)
            if random.random() < mut_rate:
                # off2 = mutation.insert(off2)
                off2 = mutation.inversion(off2)
                # off2 = mutation.random(off2)
                # off2 = mutation.scramble(off2)
                # off2 = mutation.swap(off2)

            # FITNESS EVALUATION
            off1.fitness = evaluation.fitness(off1, distances)
            offspring.append(off1)

            off2.fitness = evaluation.fitness(off2, distances)
            offspring.append(off2)

        # SURVIVOR SELECTION
        population = survivorSelection.mu_plus_lambda(population, offspring)
        # population = survivorSelection.mu_lambda(population, offspring)
        # population = survivorSelection.round_robin_tournament(population, offspring)
        # population = survivorSelection.random_uniform(population, offspring)
        # population = survivorSelection.simulated_annealing(population, offspring)

        gen += 1

        minPathLength = 1 / max(individual.fitness for individual in population)
        totalPathLengths = sum(1 / individual.fitness for individual in population)
        averagePathLength = totalPathLengths / len(population)

        if (averagePathLength - minPathLength) < 100:
            convergence_counter += 1
        else:
            convergence_counter = 0

        print("generation {}: Min Path {}, Average Path {}, diff {}"
              .format(gen, minPathLength, averagePathLength, averagePathLength -minPathLength))
    k = 1
    for i in range(0, popsize):
        if(1/population[i].fitness) == minPathLength:
            plot_population.append(population[i].path)
            print("best solution {} {} {}".format(k, population[i].path, 1/population[i].fitness))
            k+=1
    plot.plotTSP(plot_population[0], serializer.readFile(filename))
예제 #6
0
def main():

    distanceDictionary = {}
    populationSize = 500
    matingPoolSize = int(populationSize * 0.5)
    mutRate = 0.2
    xOverRate = 0.9
    genLimit = 15000
    fileName = "TSP_WesternSahara_29.txt"

    # Asks user which file they want to load
    files = ["TSP_WesternSahara_29.txt", "TSP_Uruguay_734.txt", "TSP_Canada_4663.txt"]
    print("Which is the file you want to load?\n[1] "+ files[0] + "\n[2] " + files[1] + "\n[3] " + files[2] + "\n")
    fileNum = input("Enter number: ")
    type(fileNum)
    fileName = files[int(fileNum) - 1]
    print("\nLoading:" + fileName + "\n")

    startTime = datetime.now()

    coordinates = []
    current = []
    avgFitVsGenArray = [] # for ploting at the end

    # Get data from file
    with open(fileName, 'r') as file:
        for line in file:
            line = line.replace("\n","")
            current = line.split(" ")
            for i in range(len(current)):
                current[i] = float(current[i])
            coordinates.append(current)
            current = []

    # Pre Calculations of all possible distances
    distanceDictionary = distance.preCal(coordinates)

    gen = 0
    # Create initial population
    population = initialization.randomization(populationSize, coordinates)

    # For fitness pass in array and if it is a population
    fitnessArray = fitness.preCalSumOfDistance(population, distanceDictionary, True) # Pre Calculation Method

    # To be used in MPS
    correctedFitnessArray = fitness.fitnessCorrection(fitnessArray)

    pastFit = 0
    stall = 0
    while gen < genLimit:

        # Pick parents
        parentsIndex = parentSelection.MPS(correctedFitnessArray, matingPoolSize)

        # Randomly pair up parents
        random.shuffle(parentsIndex)

        # Reproduction
        offspring = []
        offspringFitness = []
        # Initialize the counter(i) for the parents in the mating pool
        i = 0
        # Offspring are generated using selected parents in the mating pool
        while len(offspring) < matingPoolSize:
            # Recombination
            if random.random() < xOverRate:
                off1, off2 = recombination.modifiedNPointCrossover(population[parentsIndex[i]].copy(),population[parentsIndex[i+1]].copy())
            else:
                off1 = population[parentsIndex[i]].copy()
                off2 = population[parentsIndex[i+1]].copy()

            # Mutation
            if random.random() < mutRate:
                if stall > 10: # Switch to random swap
                    off1 = mutation.randomSwap(off1)
                else: # Scramble Mutation
                    off1 = mutation.scrambleMutation(off1)
            if random.random() < mutRate:
                if stall > 10: # Switch to random swap
                    off1 = mutation.randomSwap(off1)
                else: # Scramble Mutation
                    off2 = mutation.scrambleMutation(off2)

            offspring.append(off1)
            offspringFitness.append(fitness.preCalSumOfDistance(off1, distanceDictionary, False)) # Pre Calculation Method

            offspring.append(off2)
            offspringFitness.append(fitness.preCalSumOfDistance(off2, distanceDictionary, False)) # Pre Calculation Method
            # Update counter
            i += 2
        if pastFit == round(sum(fitnessArray)/len(fitnessArray),2):
            stall += 1
        else:
            pastFit = round(sum(fitnessArray)/len(fitnessArray),2)
            stall = 0

        # Plot for avg fit vs gen
        avgFitVsGenArray.append(round(sum(fitnessArray)/len(fitnessArray),2))
        # Population for the next generation
        population, fitnessArray = survivorSelection.mu_plus_lambda(population, fitnessArray, offspring, offspringFitness)

        # Update the generation counter
        gen += 1
        print("generation", gen, ": best fitness", min(fitnessArray), "average fitness", round(sum(fitnessArray)/len(fitnessArray),2))
    # Evolution ends

    # Stop timing of program
    print('\nTime elasped: ', datetime.now() - startTime, '\n')

    # The final best solution(s)
    drawThis = -1
    bestSolAppeared = 0
    for i in range (0, populationSize):
        if fitnessArray[i] == min(fitnessArray):
            bestSolAppeared += 1
            drawThis = i

    print("best solution", min(fitnessArray),"appeared",bestSolAppeared,"time(s)\n")


    # Draw solution to screen
    visual.drawGraph(population[drawThis], math.floor(min(fitnessArray)), genLimit, fileName, populationSize)

    # Draw avg fit vs gen to screen
    visual.avgFitVsGen(avgFitVsGenArray, math.floor(min(fitnessArray)), genLimit, fileName, populationSize)