예제 #1
0
def executeEA():
    population = toolbox.populationCreator(n=eam.POPULATION_SIZE)

    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("min", np.min)
    stats.register("avg", np.mean)

    hof = tools.HallOfFame(eam.HALL_OF_FAME_SIZE)

    # Unregister unpicklable methods before sending the toolbox.
    toolbox.unregister("startSolution")
    toolbox.unregister("individualCreator")
    toolbox.unregister("populationCreator")
    # elitism.eaSimpleWithElitism
    population, logbook = elitism.eaSimpleWithElitism(
        population,
        toolbox,
        #  mu=HALL_OF_FAME_SIZE,
        #  lambda_=HALL_OF_FAME_SIZE * 4,
        cxpb=eam.P_CROSSOVER,
        mutpb=eam.P_MUTATION,
        ngen=eam.MAX_GENERATIONS,
        stats=stats,
        halloffame=hof,
        verbose=True)

    return hof, logbook, population
예제 #2
0
def main():

    # create initial population (generation 0):
    population = toolbox.populationCreator(n=POPULATION_SIZE)

    # prepare the statistics object:
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("min", np.min)
    stats.register("avg", np.mean)

    # define the hall-of-fame object:
    hof = tools.HallOfFame(HALL_OF_FAME_SIZE)

    # perform the Genetic Algorithm flow with hof feature added:
    population, logbook = elitism.eaSimpleWithElitism(population,
                                                      toolbox,
                                                      cxpb=P_CROSSOVER,
                                                      mutpb=P_MUTATION,
                                                      ngen=MAX_GENERATIONS,
                                                      stats=stats,
                                                      halloffame=hof,
                                                      verbose=True)

    # print best solution:
    best = hof.items[0]
    print()
    print("Best Solution = ", best)
    print("Best Fitness = ", best.fitness.values[0])

    # save best solution for a replay:
    car.saveActions(best)
예제 #3
0
def main():

    # create initial population (generation 0):
    population = toolbox.populationCreator(n=POPULATION_SIZE)

    # prepare the statistics object:
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("max", numpy.max)
    stats.register("avg", numpy.mean)

    # define the hall-of-fame object:
    hof = tools.HallOfFame(HALL_OF_FAME_SIZE)

    # perform the Genetic Algorithm flow with hof feature added:
    population, logbook = elitism.eaSimpleWithElitism(population,
                                                      toolbox,
                                                      cxpb=P_CROSSOVER,
                                                      mutpb=P_MUTATION,
                                                      ngen=MAX_GENERATIONS,
                                                      stats=stats,
                                                      halloffame=hof,
                                                      verbose=True)

    # print best solution found:
    print("- Best solution is: \n", test.formatParams(hof.items[0]),
          "\n => accuracy = ", hof.items[0].fitness.values[0])
예제 #4
0
def main():

    # create initial population (generation 0):
    population = toolbox.populationCreator(n=POPULATION_SIZE)

    # prepare the statistics object:
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("min", numpy.min)
    stats.register("avg", numpy.mean)

    # define the hall-of-fame object:
    hof = tools.HallOfFame(HALL_OF_FAME_SIZE)

    # perform the Genetic Algorithm flow with hof feature added:
    population, logbook = elitism.eaSimpleWithElitism(population, toolbox, cxpb=P_CROSSOVER, mutpb=P_MUTATION,
                                                      ngen=MAX_GENERATIONS, stats=stats, halloffame=hof, verbose=True)

    # print best solution found:
    best = hof.items[0]
    print("-- Best Ever Individual = ", best)
    print("-- Best Ever Fitness = ", best.fitness.values[0])

    # extract statistics:
    minFitnessValues, meanFitnessValues = logbook.select("min", "avg")

    # plot statistics:
    sns.set_style("whitegrid")
    plt.plot(minFitnessValues, color='red')
    plt.plot(meanFitnessValues, color='green')
    plt.xlabel('Generation')
    plt.ylabel('Min / Average Fitness')
    plt.title('Min and Average fitness over Generations')
    plt.show()
예제 #5
0
def main():

    # create initial population (generation 0):
    population = toolbox.populationCreator(n=POPULATION_SIZE)

    # prepare the statistics object:
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("max", numpy.max)
    stats.register("avg", numpy.mean)

    # define the hall-of-fame object:
    hof = tools.HallOfFame(HALL_OF_FAME_SIZE)

    # perform the Genetic Algorithm flow with hof feature added:
    population, logbook = elitism.eaSimpleWithElitism(population, toolbox, cxpb=P_CROSSOVER, mutpb=P_MUTATION,
                                                      ngen=MAX_GENERATIONS, stats=stats, halloffame=hof, verbose=True)

    # print best solution found:
    print("- Best solutions are:")
    for i in range(HALL_OF_FAME_SIZE):
        print(i, ": ", hof.items[i], ", fitness = ", hof.items[i].fitness.values[0])

    # extract statistics:
    maxFitnessValues, meanFitnessValues = logbook.select("max", "avg")

    # plot statistics:
    plt.plot(maxFitnessValues, color='red')
    plt.plot(meanFitnessValues, color='green')
    plt.xlabel('Generation')
    plt.ylabel('Max / Average Fitness')
    plt.title('Max and Average fitness vs. Generation')
    plt.show()
def main():

    # create initial population (generation 0):
    population = toolbox.populationCreator(n=POPULATION_SIZE)

    # prepare the statistics object:
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("max", np.max)
    stats.register("avg", np.mean)

    # define the hall-of-fame object:
    hof = tools.HallOfFame(HALL_OF_FAME_SIZE)

    # perform the Genetic Algorithm flow with elitism:
    population, logbook = elitism.eaSimpleWithElitism(population,
                                                      toolbox,
                                                      cxpb=P_CROSSOVER,
                                                      mutpb=P_MUTATION,
                                                      ngen=MAX_GENERATIONS,
                                                      stats=stats,
                                                      halloffame=hof,
                                                      verbose=True)

    # print info for best solution found:
    best = hof.items[0]
    print("-- Best Individual = ", best)
    print("-- Best Fitness = ", best.fitness.values[0])

    print("- Best solutions are:")
    for i in range(HALL_OF_FAME_SIZE):
        print(i, ": ", hof.items[i].fitness.values[0], " -> ", hof.items[i])

    # plot solution locations on x-y plane:
    plt.figure(1)
    globalMaxima = [[3.0, 2.0], [-2.805118, 3.131312], [-3.779310, -3.283186],
                    [3.584458, -1.848126]]
    plt.scatter(*zip(*globalMaxima), marker='x', color='red', zorder=1)
    plt.scatter(*zip(*population), marker='.', color='blue',
                zorder=0)  # plot solution locations on x-y plane:

    # plot best solutions locations on x-y plane:
    plt.figure(2)
    plt.scatter(*zip(*globalMaxima), marker='x', color='red', zorder=1)
    plt.scatter(*zip(*hof.items), marker='.', color='blue', zorder=0)

    # extract statistics:
    maxFitnessValues, meanFitnessValues = logbook.select("max", "avg")

    # plot statistics:
    plt.figure(3)
    plt.plot(maxFitnessValues, color='red')
    plt.plot(meanFitnessValues, color='green')
    plt.xlabel('Generation')
    plt.ylabel('Max / Average Fitness')
    plt.title('Max and Average fitness vs. Generation')

    plt.show()
def main():

    # create initial population (generation 0):
    population = toolbox.populationCreator(n=POPULATION_SIZE)

    # prepare the statistics object:
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("min", numpy.min)
    stats.register("avg", numpy.mean)

    # define the hall-of-fame object:
    hof = tools.HallOfFame(HALL_OF_FAME_SIZE)

    # perform the Genetic Algorithm flow with elitism:
    population, logbook = elitism.eaSimpleWithElitism(population,
                                                      toolbox,
                                                      cxpb=P_CROSSOVER,
                                                      mutpb=P_MUTATION,
                                                      ngen=MAX_GENERATIONS,
                                                      stats=stats,
                                                      halloffame=hof,
                                                      verbose=True)

    # print info for best solution found:
    best = hof.items[0]
    print("-- Best Individual = ", best)
    print("-- Best Fitness = ", best.fitness.values[0])
    print()
    print("number of colors = ", gcp.getNumberOfColors(best))
    print("Number of violations = ", gcp.getViolationsCount(best))
    print("Cost = ", gcp.getCost(best))

    # plot best solution:
    plt.figure(1)
    gcp.plotGraph(best)

    # extract statistics:
    minFitnessValues, meanFitnessValues = logbook.select("min", "avg")

    # plot statistics:
    plt.figure(2)
    plt.plot(minFitnessValues, color='red')
    plt.plot(meanFitnessValues, color='green')
    plt.xlabel('Generation')
    plt.ylabel('Min / Average Fitness')
    plt.title('Min and Average fitness vs. Generation')

    plt.show()
def main():
    # create initial population (generation 0):
    population = toolbox.populationCreator(n=POPULATION_SIZE)

    # prepare the statistics object:
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("min", np.min)
    stats.register("avg", np.mean)

    # define the hall-of-fame object:
    hof = tools.HallOfFame(HALL_OF_FAME_SIZE)

    # perform the Genetic Algorithm flow with elitism:
    population, logbook = elitism.eaSimpleWithElitism(population,
                                                      toolbox,
                                                      cxpb=P_CROSSOVER,
                                                      mutpb=P_MUTATION,
                                                      ngen=MAX_GENERATIONS,
                                                      stats=stats,
                                                      halloffame=hof,
                                                      verbose=True)

    # print info for best solution found:
    best = hof.items[0]
    print("-- Best Individual = ", best)
    print("-- length={}, height={}".format(len(best), best.height))
    print("-- Best Fitness = ", best.fitness.values[0])
    print("-- Best Parity Error = ", parityError(best))

    # plot best tree:
    nodes, edges, labels = gp.graph(best)
    g = nx.Graph()
    g.add_nodes_from(nodes)
    g.add_edges_from(edges)
    pos = nx.spring_layout(g)

    nx.draw_networkx_nodes(g, pos, node_color='cyan')
    nx.draw_networkx_nodes(g,
                           pos,
                           nodelist=[0],
                           node_color='red',
                           node_size=400)

    nx.draw_networkx_edges(g, pos)
    nx.draw_networkx_labels(g, pos, **{"labels": labels, "font_size": 8})

    plt.show()
def main():

    # create initial population (generation 0):
    population = toolbox.populationCreator(n=POPULATION_SIZE)

    # prepare the statistics object:
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("min", np.min)
    stats.register("avg", np.mean)

    # define the hall-of-fame object:
    hof = tools.HallOfFame(HALL_OF_FAME_SIZE)

    # perform the Genetic Algorithm flow with hof feature added:
    population, logbook = elitism.eaSimpleWithElitism(population,
                                                      toolbox,
                                                      cxpb=P_CROSSOVER,
                                                      mutpb=P_MUTATION,
                                                      ngen=MAX_GENERATIONS,
                                                      stats=stats,
                                                      halloffame=hof,
                                                      verbose=True)

    # print best individual info:
    best = hof.items[0]
    print("-- Best Ever Individual = ", best)
    print("-- Best Ever Fitness = ", best.fitness.values[0])

    print("-- Route Breakdown = ", vrp.getRoutes(best))
    print("-- total distance = ", vrp.getTotalDistance(best))
    print("-- max distance = ", vrp.getMaxDistance(best))

    # plot best solution:
    plt.figure(1)
    vrp.plotData(best)

    # plot statistics:
    minFitnessValues, meanFitnessValues = logbook.select("min", "avg")
    plt.figure(2)
    plt.plot(minFitnessValues, color='red')
    plt.plot(meanFitnessValues, color='green')
    plt.xlabel('Generation')
    plt.ylabel('Min / Average Fitness')
    plt.title('Min and Average fitness vs. Generation')

    # show both plots:
    plt.show()
예제 #10
0
def gaSolution():
	# random.seed(datetime.now())

	lPopulation = copy.deepcopy(POPULATION)

	# Get a toolbox
	toolbox = getToolbox()
	stats = getStats()
	hof = tools.HallOfFame(HALL_OF_FAME_SIZE)

	# Run GA algorithm
	populationLocal, logbook = elitism.eaSimpleWithElitism(lPopulation, toolbox, cxpb=P_CROSSOVER, mutpb=P_MUTATION, 
		ngen=MAX_GENERATIONS, stats=stats, halloffame=hof, verbose=True)

	minFitnessValues, meanFitnessValues = logbook.select("min", "avg")
	best = hof.items[0]

	return best, minFitnessValues, meanFitnessValues
예제 #11
0
def main():

    # create initial population (generation 0):
    population = toolbox.populationCreator(n=POPULATION_SIZE)

    # prepare the statistics object:
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("min", np.min)
    stats.register("avg", np.mean)

    # define the hall-of-fame object:
    hof = tools.HallOfFame(HALL_OF_FAME_SIZE)

    # perform the Genetic Algorithm flow with hof feature added:
    population, logbook = elitism.eaSimpleWithElitism(population,
                                                      toolbox,
                                                      cxpb=P_CROSSOVER,
                                                      mutpb=P_MUTATION,
                                                      ngen=MAX_GENERATIONS,
                                                      stats=stats,
                                                      halloffame=hof,
                                                      verbose=True)

    # print hall of fame members info:
    print("- Best solutions are:")
    for i in range(HALL_OF_FAME_SIZE):
        print(i, ": ", hof.items[i].fitness.values[0], " -> ", hof.items[i])

    # plot statistics:
    minFitnessValues, meanFitnessValues = logbook.select("min", "avg")
    plt.figure(1)
    sns.set_style("whitegrid")
    plt.plot(minFitnessValues, color='red')
    plt.plot(meanFitnessValues, color='green')
    plt.xlabel('Generation')
    plt.ylabel('Min / Average Fitness')
    plt.title('Min and Average fitness over Generations')

    # plot best solution:
    sns.set_style("whitegrid", {'axes.grid': False})
    nQueens.plotBoard(hof.items[0])

    # show both plots:
    plt.show()
예제 #12
0
def main():

    #создание начальной популяции:
    population = toolbox.populationCreator(n=POPULATION_SIZE)

    # prepare the statistics object:
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("min", np.min)
    stats.register("avg", np.mean)

    # создания объекта решений:
    hof = tools.HallOfFame(HALL_OF_FAME_SIZE)

    # реение задачи генетическим алгоритмом с использованием критерия элитраности:
    population, logbook = elitism.eaSimpleWithElitism(population,
                                                      toolbox,
                                                      cxpb=P_CROSSOVER,
                                                      mutpb=P_MUTATION,
                                                      ngen=MAX_GENERATIONS,
                                                      stats=stats,
                                                      halloffame=hof,
                                                      verbose=True)

    # выписка информации о решениях:
    print("- Best solutions are:")
    for i in range(HALL_OF_FAME_SIZE):
        print(i, ": ", hof.items[i].fitness.values[0], " -> ", hof.items[i])

    # вывод статистики в графическом виде:
    minFitnessValues, meanFitnessValues = logbook.select("min", "avg")
    plt.figure(1)
    sns.set_style("whitegrid")
    plt.plot(minFitnessValues, color='red')
    plt.plot(meanFitnessValues, color='green')
    plt.xlabel('Generation')
    plt.ylabel('Min / Average Fitness')
    plt.title('Min and Average fitness over Generations')

    # демонстрация лучшего решения на доске:
    sns.set_style("whitegrid", {'axes.grid': False})

    # демонстрация графика:
    plt.show()
예제 #13
0
def main():

    # create initial population (generation 0):
    population = toolbox.populationCreator(n=POPULATION_SIZE)

    # prepare the statistics object:
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("max", numpy.max)
    stats.register("avg", numpy.mean)

    # define the hall-of-fame object:
    hof = tools.HallOfFame(HALL_OF_FAME_SIZE)

    # perform the Genetic Algorithm flow with hof feature added:
    population, logbook = elitism.eaSimpleWithElitism(population,
                                                      toolbox,
                                                      cxpb=P_CROSSOVER,
                                                      mutpb=P_MUTATION,
                                                      ngen=MAX_GENERATIONS,
                                                      stats=stats,
                                                      halloffame=hof,
                                                      verbose=True)

    # print best solution found:
    best = hof.items[0]
    print()
    print("Best Solution = ", best)
    print("Best Score = ", best.fitness.values[0])
    print()

    # save best solution for a replay:
    cartPole.saveParams(best)

    # find average score of 100 episodes using the best solution found:
    print("Running 100 episodes using the best solution...")
    scores = []
    for test in range(100):
        scores.append(cart_pole.CartPole().getScore(best))
    print("scores = ", scores)
    print("Avg. score = ", sum(scores) / len(scores))
예제 #14
0
def mis(greedy, elitism, n_gen, mat_prob, mut_prob, tournsize, n_pop, nreps,
        filename, out1, out_filename):
    """
    Algoritmo genético para max independent set
    
    input:
        greedy:: Bool, indica si se añade un individuo representante de la solución obtenida por el algoritmo voraz
        elitism:: Bool, inidica si se aplica elitismo
        n_pop:: Int, tamaño de la población
        n_gen:: Int, número de generaciones
        mat_prob:: Float, probabilidad de cruce, entre 0 y 1
        mut_prob:: Float, probabilidad de mutación, entre 0 y 1
        tournsize:: Int, tamaño de torneo
        nreps:: Int, número de ejecuciones
        filename:: Str, nombre del fichero en el que se encuentra la instancia
        out1:: Str, path a la carpeta para guardar los resultados
        out_filename:: Str, nombre del fichero de salida en el que se guardan los resultados
    """

    start = time.time()
    E, N, G = read_MIS(filename)

    #minimiza el peso y maximiza el valor
    creator.create("Fitness", base.Fitness,
                   weights=(1.0, ))  #quiero maximizar el número de vértices:

    #representamos los individuos en una lista

    creator.create("Individual", list, fitness=creator.Fitness)

    toolbox = base.Toolbox()
    toolbox.register("greedy_mis", greedy_mis, filename)
    toolbox.register("attr_item", random.randint, 0,
                     1)  ## N = número de vértices
    toolbox.register("individual1", tools.initRepeat, creator.Individual,
                     toolbox.attr_item, N)
    toolbox.register("individual2", tools.initIterate, creator.Individual,
                     toolbox.greedy_mis)
    toolbox.register("population", tools.initRepeat, list)

    def evalMIS(individual):  #evalMIS

        for i in range(len(individual)):
            if individual[i] == 1:
                for j in range(
                        i + 1, len(individual)
                ):  #si los vértices i,j son adyacentes eliminamos j del conjunto
                    if individual[j] == 1 and (i + 1, j + 1) in G[i]:
                        individual[j] = 0
        v = sum(individual)
        return v,

    def cxSet(ind1, ind2):

        set1 = set()
        set2 = set()

        for i in range(
                len(ind1)
        ):  #creo los conjuntos con los vértices que hay en cada individuo i.e (ind1={1,5,6,87,543})
            if ind1[i] == 1:
                ind1[i] = 0
                set1.add(i + 1)
        for i in range(len(ind2)):
            if ind2[i] == 1:
                ind2[i] = 0
                set2.add(i + 1)

        ind_set = set1.union(set2)
        ind_grades = []  #lista de tuplas (vértice,grado)
        for i in ind_set:
            grade = 0
            for edge in G:
                if i in edge:
                    grade += 1
            ind_grades.append((i, grade))
        ind_grades.sort(
            reverse=False,
            key=lambda x: x[1])  #ordenamos la lista por grado(ascendiente)

        for i in ind_grades:  #añadimos vértices por grado de menor a mayor hasta que no podemos añadir más
            v = i[0]
            ind1[v - 1] = 1
            if evalMIS(ind1) == 0:
                ind1[v - 1] = 0
                ind2 = ind1
        return ind1, ind2  #ahora ind1 = ind2

    #mutation operator could randomly add one vertex to the list changing a zero to a one
    def mut(individual):
        i = random.randint(0, len(individual) - 1)
        if individual[i] == 1:
            mut(individual)
        else:
            individual[i] = 1
        return individual,

    dict_result = dict()
    dict_time = dict()
    dict_all_gen = dict()
    for i in range(nreps):

        #register these operators in the toolbox
        toolbox.register("evaluate", evalMIS)
        toolbox.register("mate", cxSet)
        toolbox.register("mutate", mut)
        toolbox.register("select", tools.selTournament, tournsize=tournsize)

        if greedy:
            pop1 = toolbox.population(toolbox.individual1, n=n_pop)
            pop2 = toolbox.population(toolbox.individual2, n=1)
            pop = pop1 + pop2
        else:
            pop = toolbox.population(toolbox.individual1, n=n_pop)

        hof = tools.HallOfFame(1)
        stats = tools.Statistics(lambda ind: ind.fitness.values)
        stats.register("avg", numpy.mean)
        stats.register("std", numpy.std)
        #stats.register("min", numpy.min)
        stats.register("max", numpy.max)

        if elitism:
            pop, logbook = eaSimpleWithElitism(pop,
                                               toolbox,
                                               mat_prob,
                                               mut_prob,
                                               n_gen,
                                               stats,
                                               halloffame=hof)
        else:
            pop, logbook = algorithms.eaSimple(pop,
                                               toolbox,
                                               mat_prob,
                                               mut_prob,
                                               n_gen,
                                               stats,
                                               halloffame=hof)

        result_list = logbook
        end = time.time()
        dict_all_gen[i] = list(result_list)
        dict_result[i] = result_list[-1]
        dict_time[i] = {'time': end - start}

    dfa = pd.DataFrame.from_dict(dict_all_gen, orient='index')
    dfa.to_csv(out1 + out_filename + 'all_gen.csv',
               sep=';',
               header=True,
               index=True)
    df1 = pd.DataFrame.from_dict(dict_result, orient='index')
    df2 = pd.DataFrame.from_dict(dict_time, orient='index')
    df = pd.concat([df1, df2], axis=1, sort=False)
    df.to_csv(out1 + out_filename + 'complete.csv',
              sep=';',
              header=True,
              index=True)
    df = df.describe()
    df.to_csv(out1 + out_filename + '.csv', sep=';', header=True, index=True)
def main():

    # create initial population (generation 0):
    population = toolbox.populationCreator(n=POPULATION_SIZE)

    # prepare the statistics object:
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("min", numpy.min)
    stats.register("avg", numpy.mean)

    # define the hall-of-fame object:
    hof = tools.HallOfFame(HALL_OF_FAME_SIZE)

    # perform the Genetic Algorithm flow with hof feature added:
    population, logbook = elitism.eaSimpleWithElitism(population,
                                                      toolbox,
                                                      cxpb=P_CROSSOVER,
                                                      mutpb=P_MUTATION,
                                                      ngen=MAX_GENERATIONS,
                                                      stats=stats,
                                                      halloffame=hof,
                                                      verbose=True)

    # print info for best solution found:
    best = hof.items[0]
    print("-- Best Individual = ", best)
    print("-- Best Fitness = ", best.fitness.values[0])

    print()
    print("Double check: ")
    # Pipe data
    ODs = 323.9  # Outer diameter of steel pipe, [mm]
    ts = 14.2  # Wall thickness of steel pipe, [mm]
    Es = 207  # Young's modulus of steel, [GPa]
    SMYS = 358  # SMYS for X52 steel, [MPa]
    rho_s = 7850  # Density of steel,[kg⋅m^−3]
    tFBE = 0.5  # Thickness of FBE insulation layer, [mm]
    rhoFBE = 1300  # Density of FBE, [kg⋅m^−3]
    tconc = 50  # Thickness of concrete coating,[mm]
    rho_conc = 2250  # Density of concrete,[kg⋅m^−3]

    # Environmental data
    d = 50  # Water depth, [m]
    rho_sea = 1025  # Density of seawater,[kg⋅m^−3]

    # Pipe Launch Rollers
    mu_roller = 0.1  # Roller friction for pipe on stinger.

    # Lay-Barge Input Data
    thetaPT = best[
        0]  # Angle of inclination of firing line from horizontal, [deg]
    LFL = best[1]  # Length of pipe on inclined firing line, [m]
    RB = best[
        2]  # Radius of over-bend curve  between stinger and straight section of firing line, [m]
    ELPT = best[
        3]  # Height of Point of Tangent above  Reference Point (sternpost at keel level),[m]
    LPT = best[
        4]  # Horizontal distance between Point of Tangent and Reference Point, [m]
    ELWL = best[5]  # Elevation of Water Level above Reference Point, [m]
    LMP = best[
        6]  # Horizontal distance between Reference Point and Marriage Point, [m]
    RS = best[7]  # Stinger radius, [m]
    CL = best[
        8]  # Chord length of the stinger between the Marriage Point and the
    # Lift-Off Point at the second from last roller , [m]

    Ttens_tonnef, TTS_ratio, TopS_ratio = static_pipe_lay(
        ODs, ts, Es, SMYS, rho_s, tFBE, rhoFBE, tconc, rho_conc, d, rho_sea,
        mu_roller, thetaPT, LFL, RB, ELPT, LPT, ELWL, LMP, RS, CL)

    print(
        "Ttens_tonnef: ",
        Ttens_tonnef,
    )
    print("TTS_ratio: ", TTS_ratio, " < 0.6")
    print("TopS_ratio: ", TopS_ratio, " < 0.9")

    # extract statistics:
    minFitnessValues, meanFitnessValues = logbook.select("min", "avg")

    # plot statistics:
    sns.set_style("whitegrid")
    plt.plot(minFitnessValues, color='red')
    plt.plot(meanFitnessValues, color='green')
    plt.xlabel('Generation')
    plt.ylabel('Min / Average Fitness')
    plt.title('Min and Average fitness over Generations')
    plt.savefig("gen.png")
    plt.show()
예제 #16
0
def msc(greedy, elitism, n_pop, n_gen, mat_prob, mut_prob, tournsize, nreps,
        filename, out1, out_filename):
    """
    Algoritmo genético para min set covering
    
    input:
        greedy:: Bool, indica si se añade un individuo representante de la solución obtenida por el algoritmo voraz
        elitism:: Bool, inidica si se aplica elitismo
        n_pop:: Int, tamaño de la población
        n_gen:: Int, número de generaciones
        mat_prob:: Float, probabilidad de cruce, entre 0 y 1
        mut_prob:: Float, probabilidad de mutación, entre 0 y 1
        tournsize:: Int, tamaño de torneo
        nreps:: Int, número de ejecuciones
        filename:: Str, nombre del fichero en el que se encuentra la instancia
        out1:: Str, path a la carpeta para guardar los resultados
        out_filename:: Str, nombre del fichero de salida en el que se guardan los resultados
    """

    start = time.time()
    n_rows, n_cols, rows_set, cols_set, costs_list, a, b, w = read_MSC(
        filename)
    #a[j] es el conjunto de columnas que cubren la fila j+1
    #b[j] es el conjunto de filas cubiertas por la columna j+1
    #w[j] es el numero de columnas que cubren la fila j+1

    creator.create("Fitness", base.Fitness,
                   weights=(-1.0, ))  #quiero minimimzar el número de conjuntos

    #representamos los individuos en una lista
    creator.create("Individual", list, fitness=creator.Fitness)

    toolbox = base.Toolbox()
    toolbox.register("greedy_msc_individual", greedy_msc_individual, filename)
    toolbox.register("attr_item", random.randint, 0, 1)
    toolbox.register("individual", tools.initRepeat, creator.Individual,
                     toolbox.attr_item, n_cols)
    #un individuo es una lista de 0, 1 donde individuo[i]=0 si la columna j NO forma parte del MSC
    #individuo[i]=1 si la columna j SÍ forma parte del MSC
    toolbox.register("individual2", tools.initIterate, creator.Individual,
                     toolbox.greedy_msc_individual)
    toolbox.register("population", tools.initRepeat, list)

    def evalMSC(individual):

        uncovered_rows = {i for i in range(n_rows)}
        unused_cols = []
        vertex = set()
        for i in range(n_cols):
            if individual[i] == 1:
                for row in b[i]:
                    uncovered_rows.discard(row - 1)
            if individual[i] == 0:
                unused_cols.append(i)

        covered = [
        ]  #lista de tuplas (columna, n de filas descubiertas que cubre columna)
        for col in unused_cols:
            n_covered = 0  #número de filas descubiertas por el individuo que recubre col
            for row in uncovered_rows:
                if row in b[col]:
                    n_covered += 1
            covered.append((col, n_covered))

        covered.sort(reverse=True, key=lambda x: x[
            1])  #ordenamos la lista por número de filas descubiertas que cubre
        #la columna col de mayor a menor
        while len(uncovered_rows) != 0:
            for tup in covered:
                col, n_covered = tup
                individual[col] = 1
                for row in b[col]:
                    uncovered_rows.discard(row - 1)

        v = sum(individual)

        return v,

    #mutation operator could randomly remove one vertex to the list changing a one to a zero
    def mut(individual):
        i = random.randint(0, len(individual) - 1)
        individual[i] = 0
        return individual,

    dict_result = dict()
    dict_time = dict()
    dict_all_gen = dict()
    for i in range(nreps):

        #register these operators in the toolbox
        toolbox.register("evaluate", evalMSC)
        toolbox.register("mate", tools.cxTwoPoint)
        toolbox.register("mutate", mut)
        toolbox.register("select", tools.selTournament, tournsize=tournsize)

        if greedy:
            pop1 = toolbox.population(toolbox.individual, n=n_pop)
            pop2 = toolbox.population(toolbox.individual2, n=1)
            pop = pop1 + pop2
        else:
            pop = toolbox.population(toolbox.individual, n=n_pop)

        hof = tools.HallOfFame(1)
        stats = tools.Statistics(lambda ind: ind.fitness.values)
        stats.register("avg", numpy.mean)
        stats.register("std", numpy.std)
        stats.register("min", numpy.min)
        stats.register("max", numpy.max)

        if elitism:
            pop, logbook = eaSimpleWithElitism(pop,
                                               toolbox,
                                               mat_prob,
                                               mut_prob,
                                               n_gen,
                                               stats,
                                               halloffame=hof)
        else:
            pop, logbook = algorithms.eaSimple(pop,
                                               toolbox,
                                               mat_prob,
                                               mut_prob,
                                               n_gen,
                                               stats=stats,
                                               halloffame=hof)

        result_list = logbook
        end = time.time()
        dict_all_gen[i] = list(result_list)
        dict_result[i] = result_list[-1]
        dict_time[i] = {'time': end - start}

    dfa = pd.DataFrame.from_dict(dict_all_gen, orient='index')
    dfa.to_csv(out1 + out_filename + 'all_gen.csv',
               sep=';',
               header=True,
               index=True)
    df1 = pd.DataFrame.from_dict(dict_result, orient='index')
    df2 = pd.DataFrame.from_dict(dict_time, orient='index')
    df = pd.concat([df1, df2], axis=1, sort=False)
    df.to_csv(out1 + out_filename + 'complete.csv',
              sep=';',
              header=True,
              index=True)
    df = df.describe()
    df.to_csv(out1 + out_filename + '.csv', sep=';', header=True, index=True)
예제 #17
0
def mvc(greedy, greedy_mejorado, elitism, n_gen, mat_prob, mut_prob, tournsize,
        n_pop, nreps, filename, out1, out_filename):
    """
    Algoritmo genético para min vertex cover
    
    input:
        greedy:: Bool, indica si se añade un individuo representante de la solución obtenida por el algoritmo voraz
        greedy_mejorado:: Bool, indica si se añade un individuo representante de la solución obtenida por el 
                                algoritmo voraz mejorado
        elitism:: Bool, inidica si se aplica elitismo
        n_pop:: Int, tamaño de la población
        n_gen:: Int, número de generaciones
        mat_prob:: Float, probabilidad de cruce, entre 0 y 1
        mut_prob:: Float, probabilidad de mutación, entre 0 y 1
        tournsize:: Int, tamaño de torneo
        nreps:: Int, número de ejecuciones
        filename:: Str, nombre del fichero en el que se encuentra la instancia
        out1:: Str, path a la carpeta para guardar los resultados
        out_filename:: Str, nombre del fichero de salida en el que se guardan los resultados
    """

    start = time.time()
    E, N, G = read_MIS(filename)

    #minimiza el peso y maximiza el valor
    creator.create("Fitness", base.Fitness,
                   weights=(-1.0, ))  #quiero minimimzar el número de vértices:

    #representamos los individuos en una lista
    creator.create("Individual", list, fitness=creator.Fitness)

    toolbox = base.Toolbox()
    toolbox.register("attr_item", random.randint, 0,
                     1)  ## N = número de vértices
    toolbox.register("greedy_mvc", greedy_mvc, filename)
    toolbox.register("greedy_mvc_mejorado", greedy_mvc_mejorado, E, N, G)
    toolbox.register("individual", tools.initRepeat, creator.Individual,
                     toolbox.attr_item, N)
    toolbox.register("individual2", tools.initIterate, creator.Individual,
                     toolbox.greedy_mvc)
    toolbox.register("individual3", tools.initIterate, creator.Individual,
                     toolbox.greedy_mvc_mejorado)
    toolbox.register("population", tools.initRepeat, list)

    def evalMVC(
        individual
    ):  #corrige los individuos que no sean MVC cubriendo los vértices que dejan descubiertos

        uncovered_vertex = {i for i in range(N) if individual[i] == 0}
        vertex = set()
        for i in uncovered_vertex:
            for edge in G[i]:
                u, v = edge
                vertex.add(v - 1)

        for i in vertex:
            individual[i] = 1

        v = sum(individual)

        return v,

    #mutation operator could randomly remove one vertex to the list changing a one to a zero
    def mut(individual):
        i = random.randint(0, len(individual) - 1)
        individual[i] = 0
        return individual,

    dict_result = dict()
    dict_time = dict()
    dict_all_gen = dict()
    for i in range(nreps):

        #register these operators in the toolbox
        toolbox.register("evaluate", evalMVC)
        toolbox.register("mate", tools.cxTwoPoint)
        toolbox.register("mutate", mut)
        toolbox.register("select", tools.selTournament, tournsize=tournsize)

        if greedy:
            pop1 = toolbox.population(toolbox.individual, n=n_pop)
            pop2 = toolbox.population(toolbox.individual2, n=1)
            pop = pop1 + pop2
        elif greedy_mejorado:
            pop1 = toolbox.population(toolbox.individual, n=n_pop)
            pop2 = toolbox.population(toolbox.individual3, n=1)
            pop = pop1 + pop2
        else:
            pop = toolbox.population(toolbox.individual, n=n_pop)

        hof = tools.HallOfFame(1)
        stats = tools.Statistics(lambda ind: ind.fitness.values)
        stats.register("avg", numpy.mean)
        stats.register("std", numpy.std)
        stats.register("min", numpy.min)
        stats.register("max", numpy.max)

        if elitism:
            pop, logbook = eaSimpleWithElitism(pop,
                                               toolbox,
                                               mat_prob,
                                               mut_prob,
                                               n_gen,
                                               stats,
                                               halloffame=hof)

        else:
            pop, logbook = algorithms.eaSimple(pop,
                                               toolbox,
                                               mat_prob,
                                               mut_prob,
                                               n_gen,
                                               stats,
                                               halloffame=hof)

        result_list = logbook
        end = time.time()
        dict_all_gen[i] = list(result_list)
        dict_result[i] = result_list[-1]
        dict_time[i] = {'time': end - start}

    dfa = pd.DataFrame.from_dict(dict_all_gen, orient='index')
    dfa.to_csv(out1 + out_filename + 'all_gen.csv',
               sep=';',
               header=True,
               index=True)
    df1 = pd.DataFrame.from_dict(dict_result, orient='index')
    df2 = pd.DataFrame.from_dict(dict_time, orient='index')
    df = pd.concat([df1, df2], axis=1, sort=False)
    df.to_csv(out1 + out_filename + 'complete.csv',
              sep=';',
              header=True,
              index=True)
    df = df.describe()
    df.to_csv(out1 + out_filename + '.csv', sep=';', header=True, index=True)
예제 #18
0
def tsp_ga(greedy, opt, elitism, n_pop, n_gen, mat_prob, mut_prob, tournsize,
           nreps, filename, out1, out_filename):
    """
    Algoritmo genético para TSP
    
    input:
        greedy:: Bool, indica si se añade un individuo representante de la solución obtenida por el algoritmo voraz
        opt::  Bool, indica si se añade un individuo representante de la solución obtenida por el 2-OPT
        elitism:: Bool, inidica si se aplica elitismo
        n_pop:: Int, tamaño de la población
        n_gen:: Int, número de generaciones
        mat_prob:: Float, probabilidad de cruce, entre 0 y 1
        mut_prob:: Float, probabilidad de mutación, entre 0 y 1
        tournsize:: Int, tamaño de torneo
        nreps:: Int, número de ejecuciones
        filename:: Str, nombre del fichero en el que se encuentra la instancia
        out1:: Str, path a la carpeta para guardar los resultados
        out_filename:: Str, nombre del fichero de salida en el que se guardan los resultados
    """

    nodelist, N = read_tsp(filename)
    distanceMatrix = distance_matrix(nodelist, N)

    creator.create("FitnessMin", base.Fitness,
                   weights=(-1.0, ))  # minimizar distancias
    creator.create("Individual",
                   array.array,
                   typecode='i',
                   fitness=creator.FitnessMin)

    toolbox = base.Toolbox()

    # Attribute generator
    toolbox.register("indices", random.sample, range(N), N)
    toolbox.register("greedy_tsp", greedy_tsp, distanceMatrix, N)
    toolbox.register("two_OPT_individual", two_OPT_individual, distanceMatrix,
                     N)

    # Structure initializers
    toolbox.register("individual1", tools.initIterate, creator.Individual,
                     toolbox.indices)
    toolbox.register("individual2", tools.initIterate, creator.Individual,
                     toolbox.greedy_tsp)
    toolbox.register("individual3", tools.initIterate, creator.Individual,
                     toolbox.two_OPT_individual)
    toolbox.register("population", tools.initRepeat, list)

    def evalTSP(individual):
        distance = distanceMatrix[individual[-1]][individual[0]]
        for gene1, gene2 in zip(individual[0:-1], individual[1:]):
            distance += distanceMatrix[gene1][gene2]
        return distance,

    dict_all_generation = dict()
    dict_result = dict()
    dict_time = dict()
    for i in range(nreps):

        start = time.time()

        toolbox.register("mate", tools.cxPartialyMatched)
        toolbox.register("mutate", tools.mutShuffleIndexes, indpb=0.05)
        toolbox.register("select", tools.selTournament, tournsize=tournsize)
        toolbox.register("evaluate", evalTSP)

        if greedy:
            pop1 = toolbox.population(toolbox.individual1, n=n_pop)
            pop2 = toolbox.population(toolbox.individual2, n=1)
            pop = pop1 + pop2
        elif opt:
            pop1 = toolbox.population(toolbox.individual1, n=n_pop)
            pop2 = toolbox.population(toolbox.individual3, n=1)
            pop = pop1 + pop2
        else:
            pop = toolbox.population(toolbox.individual1, n=n_pop)

        hof = tools.HallOfFame(1)
        stats = tools.Statistics(lambda ind: ind.fitness.values)
        stats.register("avg", np.mean)
        stats.register("std", np.std)
        stats.register("min", np.min)
        stats.register("max", np.max)

        if elitism:

            pop2, logbook = eaSimpleWithElitism(pop,
                                                toolbox,
                                                mat_prob,
                                                mut_prob,
                                                n_gen,
                                                stats=stats,
                                                halloffame=hof)
        else:

            pop2, logbook = algorithms.eaSimple(pop,
                                                toolbox,
                                                mat_prob,
                                                mut_prob,
                                                n_gen,
                                                stats=stats,
                                                halloffame=hof)

        result_list = logbook
        end = time.time()
        dict_all_generation[i] = list(result_list)
        dict_result[i] = result_list[-1]
        dict_time[i] = {'time': end - start}

    df = pd.DataFrame.from_dict(dict_all_generation, orient='index')
    df.to_csv(out1 + 'all_generation' + out_filename,
              sep=';',
              header=True,
              index=True)
    df1 = pd.DataFrame.from_dict(dict_result, orient='index')
    df2 = pd.DataFrame.from_dict(dict_time, orient='index')
    frames = [df1, df2]
    result = pd.concat(frames, axis=1, sort=False)
    result.to_csv(out1 + 'complete' + out_filename,
                  sep=';',
                  header=True,
                  index=True)
    result = result.describe()
    result.to_csv(out1 + out_filename, sep=';', header=True, index=True)
예제 #19
0
def main(greedy, elitism, n_pop, n_gen, mat_prob, mut_prob, tournsize, nreps,
         filename, out1, out_filename):
    """
    Algoritmo genético para el problema de la mochila
    
    input:
        greedy:: Bool, indica si se añade un individuo representante de la solución obtenida por el algoritmo voraz
        elitism:: Bool, inidica si se aplica elitismo
        n_pop:: Int, tamaño de la población
        n_gen:: Int, número de generaciones
        mat_prob:: Float, probabilidad de cruce, entre 0 y 1
        mut_prob:: Float, probabilidad de mutación, entre 0 y 1
        tournsize:: Int, tamaño de torneo
        nreps:: Int, número de ejecuciones
        filename:: Str, nombre del fichero en el que se encuentra la instancia
        out1:: Str, path a la carpeta para guardar los resultados
        out_filename:: Str, nombre del fichero de salida en el que se guardan los resultados
    """

    start = time.time()
    N, MAX_WEIGHT, items = read_knapsack(filename)

    #maximiza el valor
    creator.create("Fitness", base.Fitness, weights=(1.0, ))

    #representamos los individuos en un cjto
    creator.create("Individual", set, fitness=creator.Fitness)

    toolbox = base.Toolbox()
    toolbox.register("knapsack_greedy", knapsack_greedy, filename)
    toolbox.register("attr_item", random.randrange, N)  ## N = NBR_ITEMS
    toolbox.register("individual1", tools.initRepeat, creator.Individual,
                     toolbox.attr_item, N)  ## N = IND_INIT_SIZE
    toolbox.register("individual2", tools.initIterate, creator.Individual,
                     toolbox.knapsack_greedy)
    toolbox.register("population", tools.initRepeat, list)

    def evalKnapsack(individual):
        weight = 0.0
        value = 0.0
        for item in individual:
            value += items[item][0]
            weight += items[item][1]
        if weight > MAX_WEIGHT:
            return 0, 10000  # Ensure overweighted bags are dominated
        return value, weight

    #crossover in sets: producing two children from two parents, could be that the first
    #child is the intersection of the two sets and the second child their absolute difference
    def cxSet(ind1, ind2):
        """Apply a crossover operation on input sets. The first child is the
        intersection of the two sets, the second child is the difference of the
        two sets.
        """
        temp = set(ind1)  # Used in order to keep type
        ind1 &= ind2  # Intersection (inplace)
        ind2 ^= temp  # Symmetric Difference (inplace)
        return ind1, ind2

    #mutation operator could randomly add or remove an element from the set input individual
    def mutSet(individual):
        """Mutation that pops or add an element."""
        if random.random() < 0.5:
            if len(individual) > 0:  # We cannot pop from an empty set
                individual.remove(random.choice(sorted(tuple(individual))))
        else:
            individual.add(random.randrange(N))  ## N = IND_INIT_SIZE
        return individual,

    dict_result = dict()
    dict_time = dict()
    dict_all_gen = dict()
    for i in range(nreps):

        #register these operators in the toolbox
        toolbox.register("evaluate", evalKnapsack)
        toolbox.register("mate", cxSet)
        toolbox.register("mutate", mutSet)
        toolbox.register("select", tools.selTournament, tournsize=tournsize)

        if greedy:
            pop1 = toolbox.population(toolbox.individual1, n=n_pop)
            pop2 = toolbox.population(toolbox.individual2, n=1)
            pop = pop1 + pop2
        else:
            pop = toolbox.population(toolbox.individual1, n=n_pop)

        hof = tools.HallOfFame(1)
        stats = tools.Statistics(lambda ind: ind.fitness.values)
        stats.register("avg", numpy.mean)
        stats.register("std", numpy.std)
        stats.register("min", numpy.min)
        stats.register("max", numpy.max)

        pop, logbook = eaSimpleWithElitism(pop,
                                           toolbox,
                                           mat_prob,
                                           mut_prob,
                                           n_gen,
                                           stats,
                                           halloffame=hof)
        #pop, logbook = algorithms.eaSimple(pop, toolbox, mat_prob, mut_prob, n_gen, stats,
        #                         halloffame=hof)

        result_list = logbook
        end = time.time()
        dict_all_gen[i] = list(result_list)
        dict_result[i] = result_list[-1]
        dict_time[i] = {'time': end - start}

    dfa = pd.DataFrame.from_dict(dict_all_gen, orient='index')
    dfa.to_csv('Data_KNAPSACK/' + out1 + out_filename + 'all_gen.csv',
               sep=';',
               header=True,
               index=True)
    df1 = pd.DataFrame.from_dict(dict_result, orient='index')
    df2 = pd.DataFrame.from_dict(dict_time, orient='index')
    df = pd.concat([df1, df2], axis=1, sort=False)
    df.to_csv('Data_KNAPSACK/' + out1 + out_filename + 'complete.csv',
              sep=';',
              header=True,
              index=True)
    df = df.describe()
    df.to_csv('Data_KNAPSACK/' + out1 + out_filename + '.csv',
              sep=';',
              header=True,
              index=True)
예제 #20
0
def genetic_algorithm_vrp(population_size,
                          hall_of_fame_size,
                          max_generations,
                          vrp_fn,
                          best_genetic_fn,
                          min_fitness_fn,
                          mean_fitness_fn,
                          fitness_fn,
                          route_fn,
                          total_veh,
                          save=True,
                          verbose=False,
                          plot=False):
    '''
    @param population_size: population size for experiment
    @param hall_of_fame_size: hof size for experiment
    @param max_generations: max_gens for experiment
    @param vrp_fn: filename to save vrp object
    @param best_genetic_fn: filename to save best_genetic solution object
    @param min_fitness_fn: filename to save min fitness object
    @param mean_fitness_fn: filename to save mean fitness object
    @param fitness_fn: filename to save fitness function plot
    @param route_fn: filename to save optimal route plot
    @param total_veh: total number of vehicles for VRP
    '''
    # Create initial population (generation 0):
    population = toolbox.populationCreator(n=population_size)

    # Prepare the statistics object:
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("min", np.min)
    stats.register("avg", np.mean)

    # Define the hall-of-fame object:
    hof = tools.HallOfFame(hall_of_fame_size)

    # Perform the Genetic Algorithm flow with hof feature added:
    population, logbook = elitism.eaSimpleWithElitism(population,
                                                      toolbox,
                                                      cxpb=P_CROSSOVER,
                                                      mutpb=P_MUTATION,
                                                      ngen=max_generations,
                                                      stats=stats,
                                                      halloffame=hof,
                                                      verbose=False)

    # Best individual stats
    best = hof.items[0]
    if verbose:
        print("-- Best Ever Individual = ", best)
        print("-- Best Ever Fitness = ", best.fitness.values[0])

        print("-- Route Breakdown = ", vrp.getRoutes(best))
        print("-- total distance = ", vrp.getTotalDistance(best))
        print("-- max distance = ", vrp.getMaxDistance(best))

    # Main statistics
    minFitnessValues, meanFitnessValues = logbook.select("min", "avg")

    if save:
        cPickle.dump(vrp, open('Output/pkl_files/{}'.format(vrp_fn), 'wb'), -1)
        cPickle.dump(best, open('Output/{}'.format(best_genetic_fn), 'wb'), -1)
        cPickle.dump(minFitnessValues,
                     open('Output/pkl_files/{}'.format(min_fitness_fn), 'wb'),
                     -1)
        cPickle.dump(meanFitnessValues,
                     open('Output/pkl_files/{}'.format(mean_fitness_fn), 'wb'),
                     -1)

    if plot:
        # Plot Best Solution
        plt.figure(1)
        plt.xlabel('Latitude')
        plt.ylabel('Longitude')
        plt.title('Best Route with {} vehicles'.format(total_veh))
        vrp.plotData(best)
        plt.savefig('/Output/plots/{}'.format(route_fn))
        plt.show()

        # Plot solution
        plt.figure(2)
        plt.plot(minFitnessValues, color='red')
        plt.plot(meanFitnessValues, color='green')
        plt.xlabel('Generation')
        plt.ylabel('Min / Average Fitness')
        plt.title('Min and Average fitness vs. Generation')
        plt.savefig('/Output/plots/{}'.format(fitness_fn), dpi=300)
        plt.show()