Esempio n. 1
0
def runAlgorithms(jobs, clusters, root):
    mid = time.time()
    sortedList = sorted(clusters, key=getKey, reverse=True)
    for newJob in sorted(jobs, key=getKey2, reverse=True):
        fisrtFit(newJob, sortedList)
    utilization_info(sortedList, root)
    print("value of FFD: ", fitness(sortedList))
    end = time.time()
    print("elapsed time FFD: ", end - mid)

    mid = time.time()
    gen = Memetic.Genetic(root)
    gen.find_optimum_allocation(jobs, clusters, False, None)
    root.debug("Genetic:")
    utilization_info(clusters, root)
    end = time.time()
    print("elapsed time genetic: ", end - mid)

    mid = time.time()
    gwo = GrayWolf(root)
    gwo.find_optimum_allocation(jobs, clusters, False, None)
    root.debug("Gray Wolf:")
    utilization_info(clusters, root)
    end = time.time()
    print("elapsed time GWO: ", end - mid)

    mid = time.time()
    sa = SimulatedAnnealing(root)
    sa.find_optimum_allocation(jobs, clusters, False, None)
    root.debug("Simulated annealing:")
    utilization_info(clusters, root)
    end = time.time()
    print("elapsed time SA: ", end - mid)
Esempio n. 2
0
def main():
    filename, algorithm, cut_off_sec, random_seed = format_check(
    )  # check input format
    city, dim, edge_weight_type, coord = parse_input(
        filename)  # parse input information
    adj_mat = adjacency_mat(dim, edge_weight_type, coord)  # input matrix
    write_adj_mat_file(adj_mat, city, dim)  # save input matrix as csv

    if random_seed == None:
        random_seed = 0
    else:
        random_seed = int(random_seed)

    if algorithm == 'Approx':
        output = Output(filename, algorithm, cut_off_sec,
                        algorithm)  # init output object

        start_MST = time.time()
        c, tour = compute(dim, adj_mat, cut_off_sec=cut_off_sec)
        total_time = time.time() - start_MST

        output.solution([c] + tour)  # generate solution file
        output.sol_trace([('%.4f' % total_time, c)
                          ])  # generate solution trace file

    elif algorithm == 'BnB':
        output = Output(filename, algorithm, cut_off_sec,
                        algorithm)  # init output object

        bnb = BranchNBound(
            adj_mat, dim,
            cut_off_sec)  # param: dist_matrix, num_city, time_limit
        path, cost, trace_list = bnb.run_branch_and_bound()

        output.solution([cost] + path)  # generate solution file
        output.sol_trace(trace_list)  # generate solution trace file

    elif algorithm == 'LS1':  # Iterated LocalSearch
        output = Output(filename, algorithm, cut_off_sec, algorithm,
                        random_seed)  # init output object

        ils = ILS(adj_mat, dim, cut_off_sec, random_seed
                  )  # param: dist_matrix, num_city, time_limit, random_seed
        path, cost, trace_list = ils.iterated_local_search()

        output.solution([cost] + path)  # generate solution file
        output.sol_trace(trace_list)  # generate solution trace file

    elif algorithm == 'LS2':  # Simulated Annealing
        output = Output(filename, algorithm, cut_off_sec, algorithm,
                        random_seed)  # init output object

        sa = SA(adj_mat, dim, 1e30, 1, 0.999, random_seed, cut_off_sec)
        path, cost, trace_list = sa.run_simulated_annealing()

        output.solution([cost] + path)  # generate solution file
        output.sol_trace(trace_list)  # generate solution trace file
Esempio n. 3
0
    def get_best_ranking(self, initial_ranking, initial_temp, temp_length,
                         cooling_ratio, num_non_improve):

        search = SimulatedAnnealing(tournament=self,
                                    initial_ranking=initial_ranking,
                                    initial_temp=initial_temp,
                                    temp_length=temp_length,
                                    cooling_ratio=cooling_ratio,
                                    num_non_improve=num_non_improve)

        return search.search()
Esempio n. 4
0
 def SimAnn(self):
     sim = SimulatedAnnealing(self.function, 100, 1000, 250, 
                              .975, True, True)
     for i in range (len(self.population)):
         #print(sim.FX.getX())
         sim.setVariables(self.population[i].FX.getX(), self.population[i].FX.getY())
         sim.SA()
         self.population[i].FX.setVars(sim.getBestX(), sim.getBestY())
         self.population[i].FX.bestSolution = sim.bestSolution
         #print(self.population[i].FX.getX())
     self.sortListFitness()
     self.hiveAdmin()
def main():
    listOfPawn = []
    makingInput(listOfPawn)
    board = Board(listOfPawn)

    board.initRandomState()
    # board.printBoard()
    menu()
    a = inputMenu()
    if (a == 1):
        # print("Ini hill climbing")
        useHillClimbing = HillClimbing(board)
        newBoard = useHillClimbing.algorithm()
        newBoard.printBoard()
        differentColor, sameColor = newBoard.calculatePawnAttack()
        print(str(sameColor) + " " + str(differentColor))
        print(newBoard.scoringListOfPawnWithColor())
    elif (a == 2):
        # print("Ini Simulated Annealing")
        choice = menuSetting()
        if (choice == 1):
            t, desRate, desStep = inputSettingSimulatedAnnealing()
        else:  # choice == 2
            t = 10
            desRate = 0.1
            desStep = 10
        useSimulatedAnnealing = SimulatedAnnealing(t, desRate, desStep, board)
        newBoard = useSimulatedAnnealing.algorithm()
        newBoard.printBoard()
        differentColor, sameColor = newBoard.calculatePawnAttack()
        print(str(sameColor) + " " + str(differentColor))
        print(newBoard.scoringListOfPawnWithColor())
    else:  # a == 3
        # print("Ini GA")
        choice = menuSetting()
        if (choice == 1):
            N, probCross, probMuta, generations = inputSettingGeneticAlgorithm(
            )
        else:  #choice == 2
            generations = 50
            probCross = 1
            probMuta = 0.3
            N = 50
        useGeneticAlgorithm = GeneticAlgorithm(board, N, probCross, probMuta,
                                               generations)
        geneticAlgorithmResult = useGeneticAlgorithm.algorithm()
        board = copy.deepcopy(geneticAlgorithmResult)
        board.printBoard()
        differentColor, sameColor = board.calculatePawnAttack()
        print(str(sameColor) + " " + str(differentColor))
        print(board.scoringListOfPawnWithColor())
Esempio n. 6
0
def main():
    # Tuning based on user
    k_coloring = 4
    nodes = 10

    # Graph Generator
    graph = GraphGenerator(nodes)
    graph.printAJ()

    # Algorithms
    # Simple Backtracking
    print("SIMPLE BACKTRACKING")
    bt = Backtracking(graph, k_coloring)
    bt.backtracking()
    bt.print()

    # Backtracking with arc consistency
    print(
        "========================================================================="
    )
    print("BACKTRACKING WITH ARC CONSISTENCY")
    ac = ArcConsistency(graph, k_coloring)
    ac.backtracking()
    ac.print()

    # Backtracking with forward checking
    print(
        "========================================================================="
    )
    print("BACKTRACKING WITH FORWARD CHECKING")
    fc = ForwardChecking(graph, k_coloring)
    fc.backtracking()
    fc.print()

    # Local Search Genetic Algorithm
    print(
        "========================================================================="
    )
    print("GENETIC ALGORITHM")
    ga = GA(graph, k_coloring)
    ga.train()

    # Local Search Simulated Annealing
    print(
        "========================================================================="
    )
    print("SIMULATED ANNEALING")
    sa = SimulatedAnnealing(graph, k_coloring)
    sa.simulate()
Esempio n. 7
0
def main():
    print("Digite o tipo de resolução desejada:")
    print("1-Simulated Annealing 2-Algoritmo Genetico 3-Hill Climbing")
    tipo = input()

    inicio = time.time()
    corrente = time.time() - inicio
    if tipo == '3':
        #Pega a matriz do arquivo
        matriz = climb.getMatrizArquivo('matriz.txt')
        #Cria o objeto
        hc = climb.HillClimbing()
        #Init da matriz no objeto
        hc.setMatriz(matriz)
        print("\nMatriz inicial\n")
        #Imprime a matriz Inicial
        climb.imprimeMatriz(matriz)
        print("Quantidade de ataques entre pares de rainhas:" +
              str(climb.getTotalAtackTabuleiro(matriz)))
        print("---------------------------------------")
        #imprime a matriz com o resultado
        climb.imprimeMatriz(hc.hill(20))
    elif tipo == '1':
        simulatedannealing = SimulatedAnnealing('matriz.txt')

    elif tipo == '2':
        algoritmogenetico = AlgoritmoGenetico('matriz.txt')

    else:
        print("Função não encontrada\n")

    decorrido = time.time() - inicio
    print("\nTempo de execução:", decorrido, "segundos")
Esempio n. 8
0
 def SimAnn(self):
     sim = SimulatedAnnealing(self.function, 100, 1000, 250, .975, True,
                              True)
     for i in range(len(self.population)):
         #print(sim.FX.getX())
         sim.setVariables(self.population[i].FX.getX(),
                          self.population[i].FX.getY())
         sim.SA()
         self.population[i].FX.setVars(sim.getBestX(), sim.getBestY())
         self.population[i].FX.bestSolution = sim.bestSolution
         #print(self.population[i].FX.getX())
     self.sortListFitness()
     self.hiveAdmin()
Esempio n. 9
0

# Prendo una soluzione casuale nel range continuo [-1,2]
def greedy_sol():
    # Scelgo un numero nell'intervallo [-1,2] e lo provo
    return uniform(-1.0, 2.0)


# Prendo una soluzione in un intorno stabilito eps
def perturb_sol(x1):
    eps = 0.5
    x2 = round(uniform(x1 - eps, x1 + eps), 3)
    while x2 <= -1.0 or x2 >= 2.0:
        x2 = round(uniform(x1 - eps, x1 + eps), 3)
    return x2


# Funzione che calcola l'energia del sistema
def energy(x):
    return -(1.0 + x * sin(10 * pi * x))


# Funzione obiettivo da massimizzare
def obj_function(x):
    return 1.0 + x * sin(10 * pi * x)


x0 = greedy_sol()
SA = SimulatedAnnealing(x0, 100.0, 0.01, 50, obj_function, energy, perturb_sol)
SA.run(debug=True)
SA.plot_performance('temperature', 'score')
        v = [ds[i][j] for i in range(N_CPU)]
        x1[j] = sorted(range(len(v)), key=v.__getitem__)[0]
    return x1


def perturb_sol(x1):
    # Scelgo un job e cambio la CPU di appartenenza
    job = randint(0, N_JOBS - 1)
    x2 = [x for x in x1]
    x2[job] = randint(0, N_CPU - 1)
    return x2


# Funzione che calcola l'energia del sistema
def energy(x):
    return sum([float(dataset[x[i]][i]) for i in range(len(x))])


# Funzione obiettivo da massimizzare
def obj_function(x):
    return sum([float(dataset[x[i]][i]) for i in range(len(x))])


# 40 righe X 800 colonne
dataset = leggi_dati()
x0 = greedy_sol(dataset)
SA = SimulatedAnnealing(x0, 1.0, pow(10, -20), 300, obj_function, energy,
                        perturb_sol)
SA.run(debug=True)
SA.plot_performance('temperature', 'total cpu time')
print(['greedy_col = ', energy(x0)])
Esempio n. 11
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 30 09:01:40 2019

@author: chandanav
"""
from JobShopLoader import JobShopLoader
from Utilities import Utilities
from SimulatedAnnealing import SimulatedAnnealing
import matplotlib.pyplot as plt

# Initialization of the objects
jobshopLoader = JobShopLoader()
utilitiesObj = Utilities()
simulatedAnnealing = SimulatedAnnealing()

# Loading the data from the input file
jobs = jobshopLoader.load("data.txt")

# Calling the search algorithm to find the best solution for scheduling the jobs on machines
cost, solution = simulatedAnnealing.search(jobshopLoader,
                                           utilitiesObj,
                                           maxTime=20,
                                           T=200,
                                           termination=10,
                                           halting=10,
                                           mode='random',
                                           shrink=0.8)

# Display the solution
Esempio n. 12
0
    def create_initial_solution(self):
        return self.Solution.random_solution(self)


if __name__ == "__main__":
    HasAnnFile = True
    path = sys.argv[1]
    print(str(sys.argv[1]))
    task = TSP_Task(path)

    #SIM_ANN começa aqui --------------------------------------
    try:
        print(str(sys.argv[2]))
    except IndexError:
        HasAnnFile = False
        print("No Ann_Params file passed")
    if HasAnnFile:
        ann_testname, ann_testparams = read_AnnealingParams(sys.argv[2])
        print("\n\t" + str(ann_testname))
        for testparams in ann_testparams:
            print("\t\t(" + testparams[0] + "," + testparams[1] + "," +
                  testparams[2] + ")")
            (best, best_eval, start_temp, temp, alpha, elapsed_time) =\
             SA.simulated_annealing(task,int(testparams[0]),float(testparams[1]),int(testparams[2]))
            print("\t\tBest = " + str(best.cities) + " with eval = " +
                  str(best_eval))
            print("\t\tStarting Temp = " + str(start_temp) + "; End Temp = " +
                  str(temp))
            print("\t\tElapsed Time" + str(elapsed_time))
            break
    # SIM_ANN termina aqui --------------------------------------
        #Evento con el que capturamos si se presiono un boton del mouse
        if event.type == pygame.MOUSEBUTTONDOWN:
            #si se presiono el boton izquierdo
            if event.button == 1:
                #obtiene la posicion del mouse dobde se presiono
                x_mouse, y_mouse = pygame.mouse.get_pos()
                #dibuja un circulo en la posion
                drawPoints()
        #Evento con el que capturamos si se presiono un boton del teclado
        if event.type == pygame.KEYDOWN:
            #Aplicamos el algoritmo SimulatedAnnealing
            if event.key == pygame.K_SPACE:

                flat = True
                rgb = (133, 193, 233)
                sa = SimulatedAnnealing(pointsA, 10000, 0.003)
                sa.run()
                for i in range(pointsA.get_size()):
                    pointsA.set_coordinates(i, sa.points.get_coordinates(i))
                screen.blit(backGround, (0, 0))
                boolTime = False
                drawLine()

        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    screen.blit(backGround, (0, 0))
    if pointsA.get_size() > 0:
        drawPoints()
        drawLine()
 def __init__(self):
     self.repository = Repository()
     self.sa = SimulatedAnnealing(self.repository)
     self.ga = GeneticAlgorithm(self.repository)
     self.table = Table('')
Esempio n. 15
0
def main():
    # nodes = int(input('Podaj liczbe wierzcholkow: '))
    # rozmiar = int(input('Podaj maksymalny rozmiar wspolrzednej: '))
    # losuj(nodes, rozmiar)

    plik = open('dane.txt', 'r')
    nodes = int(plik.readline())

    graph = [[i for i in range(nodes)] for _ in range(nodes)]
    coordinates = list(range(nodes))
    odwiedzony = list(range(nodes))

    for i in range(1, nodes + 1):
        linia = plik.readline()
        dane = linia.split()
        wsp_x = int(dane[1])
        wsp_y = int(dane[2])
        coordinates[i - 1] = (wsp_x, wsp_y)

    for i in range(nodes):  # dodawanie krawedzi
        for j in range(i + 1):
            add_edge(graph, coordinates, i, j)

    for i in range(nodes):  # ustawiamy wszystkie wierzcholki na nieodwiedzone
        odwiedzony[i] = False

    naj = inf
    rozw = []
    for i in range(
            nodes
    ):  # naj - najlepszy wynik greedy przy startowaniu z wszystkich wierzcholkow
        wynik, rozwGreedy = greedyWithFirst(graph, nodes, odwiedzony, i)
        if wynik < naj:
            naj = wynik
            rozw = rozwGreedy

    r = 0.999
    print(naj, rozw)
    #while r < 0.9999:
    #    r += 0.0001
    #    print(SimulatedAnnealing(graph, nodes, naj, rozw, T, Tmin, r))
    for r in range(990, 999, 1):
        T = 100.0
        Tmin = 1.0
        r = r / 1000
        print(T, Tmin, r)
        wynik, rozwAnnealing = SimulatedAnnealing(graph, nodes, naj, rozw, T,
                                                  Tmin, r)
        if wynik < naj:
            naj = wynik
            rozw = rozwAnnealing
    for r in range(9990, 9999, 1):
        r = r / 10000
        T = 100.0
        Tmin = 1.0
        print(T, Tmin, r)
        wynik, rozwAnnealing = SimulatedAnnealing(graph, nodes, naj, rozw, T,
                                                  Tmin, r)
        if wynik < naj:
            naj = wynik
            rozw = rozwAnnealing

    zapis_do_pliku(coordinates, nodes, rozw)
    print()
from Function import MyFunction
from SimulatedAnnealing import SimulatedAnnealing
from Probability import MyProbability
import matplotlib.pyplot as plt

myfun = MyFunction(-10, 10)
"""
parameter = Temperature,Minimum Temperature,koefisien,length of itenary each temperatur,Function,Probability
"""

sA = SimulatedAnnealing(1.0, 0.0001, 0.99, 100, myfun, MyProbability())

solution, result = sA.getSolution()
print("Best Solution")
print(solution)
print("length of iteration", len(result))
"""grafik all solution"""
plt.plot(range(len(result)), result)
plt.show()
Esempio n. 17
0
def get_move():
    anneal = SimulatedAnnealing(BLUE_PLAYER, board)
    # pprint(board)
    return steps[anneal.anneal(board, time_allowance=sleeptime)]
    def run(self):
        """ Runs a ModelMapVMPackingExperiment

        Returns:
            Results of experiment

        """
        self.logger.info("Running experiment %s", self.title)

        # Load all data
        self._loadData()

        # Prepare unknown function ground truth model
        _X = self.unknown_slice.data[self.domain_columns]
        _y = self.unknown_slice.data[self.codomain_columns]
        self.unknown_model.fit(_X, _y)

        # Setup models for multitask learning if necessary by passing the dataset for the authoritative slice

        for model in self.map.map_modeling_methods:
            try:
                if model.multi_task:

                    dom = []

                    if hasattr(self.map, "C_feature_names"):
                        dom = self.map.C_feature_names

                    dom = dom + [self.authoritative_slice.codomain_columns]

                    model.set_auth_tasks(self.authoritative_slice.data[dom],
                                         self.authoritative_slice.data[self.authoritative_slice.codomain_columns])
            except AttributeError:
                pass

        for model in self.direct_modeling_methods:
            try:
                if model.multi_task:
                    model.set_auth_tasks(self.authoritative_slice.data[self.authoritative_slice.domain_columns],
                                         self.authoritative_slice.data[self.authoritative_slice.codomain_columns])
            except AttributeError:
                pass

        # Prepare Simulated Annealing parameters

        # Initial position for SA
        initial_conf = [[0.1, 4, 4], [0.1, 4, 4], [0.1, 4, 4], [0.1, 4, 4]]
        domain = [{0: 0.1, 1: 0.25, 2: 0.5, 3: 1.0},
                  {0: 1, 1: 2, 2: 4, 3: 8, 4: 16, 5: 32, 6: 48},
                  {0: 1, 1: 2, 2: 4, 3: 8, 4: 16, 5: 32, 6: 64, 7: 128, 8: 256, 9: 512, 10: 1024}]
        constraints = [1.0, 48, 1024]
        models_unk =  [self.UnknownModel, self.UnknownModel, self.UnknownModel, self.UnknownModel]
        models_map = [self.ModelMapPredictMap, self.ModelMapPredictMap, self.ModelMapPredictMap, self.ModelMapPredictMap]
        models_direct = [self.ModelMapPredictDirect, self.ModelMapPredictDirect, self.ModelMapPredictDirect,
                         self.ModelMapPredictDirect]

        SA_num_steps = 250
        SA_num_substeps = 100

        # Run Simulated Annealing for authoritative model to find true best performance
        random.seed(1)

        if self.run_ground_truth_SA:
            print('Starting optimization on ground truth data')
            auth_results = SimulatedAnnealing(initial_conf, domain, models_unk, constraints, num_steps=SA_num_steps,
                                     num_substeps=SA_num_substeps,log_domain=self.exp2_domain)
        else:
            auth_results = [[[0.25, 16, 256], [0.5, 16, 512], [0.1, 8, 128], [0.1, 8, 128]],[732.71266664]]

        print('Ground truth best configuration = ' + str(auth_results[0]))
        print('Ground truth best total throughput = ' + str(auth_results[1]))

        exp_results = pd.DataFrame(
            columns=["number_of_samples", "run_id", "modeling_technique", "modeling_method", "tpmC", "truth",
                     "error", "config", "actuals"])

        for num_samples in self.sampling_budgets:

            self.logger.info("Training using " + str(num_samples) + " samples.")

            if num_samples > self.unknown_slice.data.shape[0]:
                self.logger.debug("requested sampling budget %s is greater than the available sample %s", num_samples,
                                  self.unknown_slice.data.shape[0])
                num_samples = self.unknown_slice.data.shape[0]

            self.logger.info("Training using " + str(num_samples) + " samples.")

            # Run multiple iterations to remove random noise

            for run_i in [self.num_runs]:

                # Generate the training set.  Set random_state to be able to replicate results.
                # The training set contains progressively more samples, but using the same random seed, every training
                # set is guaranteed to be a superset of the previous one
                training_set = self.unknown_slice.data.sample(num_samples, random_state=run_i + 1)

                # -------------------------------------------------------------
                # Mapping technique
                # Construct the map
                self.modelmap = ModelMap.ModelMap(authoritative_models=self.authoritative_models,
                                               map=self.map,
                                               direct_modeling_methods=self.direct_modeling_methods,
                                               model_selection=self.model_selection,
                                               logger=self.logger
                                               )

                # Fit the map to the training data.
                self.modelmap.fit(training_set[self.domain_columns], training_set[self.codomain_columns])

                for index in range(len(self.map.map_modeling_methods)):

                    self.modeling_method_index = index

                    print('Starting optimization on ' +  self.map.map_modeling_methods[index].label)

                    # Run Simulated Annealing for map model
                    random.seed(run_i + 1)
                    results = SimulatedAnnealing(initial_conf, domain, models_map, constraints, num_steps=SA_num_steps,
                                                 num_substeps=SA_num_substeps,log_domain=self.exp2_domain)

                    print()
                    print(str(index) + " **************************************************************************")
                    print(str(index) + " Map model = " + self.map.map_modeling_methods[index].label)
                    print(str(index) + ' Best predicted configuration using map model = ' + str(results[0]))
                    print(str(index) + ' Best predicted total throughput using map model = ' + str(results[1]))

                    # Compute actual results
                    actual_result = ObjectiveFunc(results[0], models_unk, constraints,log_domain=self.exp2_domain)[0]

                    print(str(index) + ' Actual individual throughput = ')
                    actuals = ""
                    for i in range(len(models_unk)):
                        # Get a performance model from the list
                        fun = models_unk[i]
                        if self.exp2_domain:
                            actuals = actuals + str(fun(np.log2(results[0][i])))
                            print(str(index) + " * " + str(results[0][i]) + "=" + str(fun(np.log2(results[0][i]))))
                        else:
                            actuals = actuals + str(fun(results[0][i]))
                            print(str(index) + " * " + str(results[0][i]) + "=" + str(fun(results[0][i])))

                    print(str(index) + ' Actual total throughput = ' + str(actual_result))

                    print(str(index) + ' Ground truth optimal total throughput = ' + str(auth_results[1][0]))

                    error = abs(actual_result - auth_results[1][0])/auth_results[1][0] * 100.0

                    print(str(index) + ' Error = ' + str(error) + "%")

                    exp_results.loc[exp_results.shape[0]] = [num_samples, run_i, "mapping" , self.map.map_modeling_methods[index].label,
                                                             actual_result, auth_results[1][0], error,
                                                             str(results[0]), actuals]

                for index in range(len(self.direct_modeling_methods)):

                    self.modeling_method_index = index

                    # Run Simulated Annealing for direct model
                    random.seed(run_i + 1)
                    results = SimulatedAnnealing(initial_conf, domain, models_direct, constraints, num_steps=SA_num_steps,
                                                 num_substeps=SA_num_substeps,log_domain=self.exp2_domain)

                    print()
                    print(str(index) + " **************************************************************************")
                    print(str(index) + " Direct model = " + self.direct_modeling_methods[index].label)
                    print(str(index) + ' Best predicted configuration using direct model = ' + str(results[0]))
                    print(str(index) + ' Best predicted total throughput using direct model = ' + str(results[1]))

                    # Compute actual results
                    actual_result = ObjectiveFunc(results[0], models_unk, constraints,log_domain=self.exp2_domain)[0]

                    print(str(index) + ' Actual individual throughput = ' + str(actual_result))
                    actuals = ""
                    for i in range(len(models_unk)):
                        # Get a performance model from the list
                        fun = models_unk[i]
                        if self.exp2_domain:
                            actuals = actuals + str(fun(np.log2(results[0][i])))
                            print(str(index) + " * " + str(results[0][i]) + "=" + str(fun(np.log2(results[0][i]))))
                        else:
                            actuals = actuals + str(fun(results[0][i]))
                            print(str(index) + " * " + str(results[0][i]) + "=" + str(fun(results[0][i])))

                    print(str(index) + ' Ground truth optimal total throughput = ' + str(auth_results[1][0]))

                    error = abs(actual_result - auth_results[1][0])/auth_results[1][0]  * 100.0

                    print(str(index) + ' Error = ' + str(error) + "%")

                    exp_results.loc[exp_results.shape[0]] = [num_samples, run_i, "direct",
                                                             self.direct_modeling_methods[index].label,
                                                             actual_result, auth_results[1][0], error,
                                                             str(results[0]), actuals]


                # End of loop over self.num_runs
        # End of loop over num_samples

        results_dir = "results/" + self.title
        try:
            os.makedirs(results_dir)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise

        # Dump iteration results
        exp_results.to_pickle(path=os.path.join(results_dir, self.title + EXP_RESULTS_FILE_EXT + str(self.num_runs) +
                                                ".DataFrame"))
        exp_results.to_csv(os.path.join(results_dir, self.title + EXP_RESULTS_FILE_EXT + str(self.num_runs) + ".csv"))
Esempio n. 19
0
executions = 100
iterations = 1e+5
theads = 50

stop = lambda k, vector, function: k >= iterations
stopp = lambda k, vector, function: k >= iterations / theads

function = opt_functions.ackley
_min = -32
_max = 32
dim = 12

hc = HillClimb(dim, function, stop)
hcp = ParallelHC(theads, dim, function, stopp)
st = SimulatedAnnealing(dim, function, stop)

hc_candidates = []
hcp_candidates = []
st_candidates = []

for i in range(executions):
    hc_candidates.append(hc.execute(_min, _max))
    hcp_candidates.append(hcp.execute(_min, _max))
    st_candidates.append(st.execute(_min, _max))
    print('{}/{}'.format(i + 1, executions))

hc_results = [function(cand) for cand in hc_candidates]
hcp_results = [function(cand) for cand in hcp_candidates]
st_results = [function(cand) for cand in st_candidates]
     print("\nThe option is not a valid number.")
 else:
     if opt == 1:
         #file_name = input('Insert the name of the file (type: name.txt): ')
         file_name = "kroA100.tsp"
         #file_name = "ch150.tsp"
         if file_name[-4:] == ".tsp":
             ui.set_repository(read_from_file(file_name, ui.get_repository()))
         else:
             print("The name doesn't follow the type specified (type: name.txt).")
     elif opt == 2:
         print("2")
     elif opt == 3:
         print_distance_matrix(ui.get_repository())
     elif opt == 4:
         sa = SimulatedAnnealing(ui.get_repository())
         ui.set_sa(sa)
         try:
             T = int(input('Insert temperature value: '))
             T_min = float(input('Insert minimum temperature value: '))
             alpha = float(input('Insert alpha value: '))
             iterations = int(input('Insert number of iterations: '))
             '''
             T = 10
             T_min = 0.00001
             alpha = 0.9999
             iterations = 10
             '''
             text_file = open("Tests.txt", "a")
             text_file.write("Test:\n")
             text_file.write("\n")
Esempio n. 21
0
    print("Bad args")
    exit(1)

if "--happycat" in sys.argv:
    function = Functions.happy_cat
elif "--griewank" in sys.argv:
    function = Functions.griewank
elif "--salomon" in sys.argv:
    function = Functions.griewank
else:
    print("Bad args")
    exit(1)

if "--localsearch" in sys.argv:
    result = LocalSearch.minimalize_function(function, x, seconds_to_run)
elif "--annealing" in sys.argv:
    result = SimulatedAnnealing.minimalize_function(function, x,
                                                    seconds_to_run)
elif "--swarm" in sys.argv:
    result = ParticleSwarm.minimalize_function(function, x, seconds_to_run)
else:
    print("Bad args")
    exit(1)

output = ""
for i in range(4):
    output += str(result[0][i]) + " "

print(output)
print(result[1])
Esempio n. 22
0
from random import randint
n = int(input("What is the number of queens: "))

while n < 4 :
    print("Solution cannot be found for a number less than 4.\nEnter another number")
    n = int(input("What is the number of queens: "))
print("\n1. Hill Climbing\n2. Random Restart Hill Climbing\n3. Simulated Annealing\n4. Genetic\n")
algorithm = int(input("Select which algorithm you would like to use: "))

queens = list([randint(0, n - 1) for x in range(n)])
#print(queens)

if algorithm == 1:

    result = HillClimbing(queens, n, 30)

elif algorithm == 2:

    result = RandomRestartHC(queens, n, int(np.log(n**7)))

elif algorithm == 3:

    result = SimulatedAnnealing(queens, n)

elif algorithm == 4:

    result = Genetic(n)



Esempio n. 23
0
    parametros_to = [500, 100, 50]
    parametros_alpha = [0.95, 0.85, 0.7]
    parametros_iteracoes = [350, 500]

    treino_csv = open("problemas/treino.csv")
    entradas = list(DictReader(treino_csv, delimiter=";"))

    resultados = open("resultados/treino_simulatedannealing.csv", "w")
    resultados.write("nome;to;alpha;iteracoes;tempo;estado;valor;tamanho\n")

    for to in parametros_to:
        for alpha in parametros_alpha:
            for iteracoes in parametros_iteracoes:
                for entrada in entradas:
                    nome, t, vt = entrada["nome"], float(entrada["t"]), eval(entrada["vt"])
                    estado, valor, tamanho, tempo = SimulatedAnnealing(t, vt, 120, iteracoes, to, alpha)

                    resultados.write(f"{nome};{to};{alpha};{iteracoes};{tempo};{estado};{valor};{tamanho}\n")

if algoritmo == 'GE' or run_all:
    parametros_tamanho_populacao = [10, 20, 30]
    parametros_taxa_crossover = [0.75, 0.85, 0.95]
    parametros_taxa_mutacao = [0.10, 0.20, 0.30]

    treino_csv = open("problemas/treino.csv")
    entradas = list(DictReader(treino_csv, delimiter=";"))

    resultados = open("resultados/treino_genetic.csv", "w")
    resultados.write("nome;tamanho_populacao;taxa_crossover;taxa_mutacao;tempo;estado;valor;tamanho\n")

    for tamanho_populacao in parametros_tamanho_populacao:
Esempio n. 24
0
    data_model.reversed_sections)
print('Best permuttation for reversed method (Hill Climb):', str(best_tour),
      'Distance:', str(best_distance), '\n')
plt.plot(climb, color="blue", label="Hill Climb (Reversing method)")
plt.ylabel('Distance')
plt.legend(loc="lower right")

best_tour, best_distance, climb = hill_climb.perform_algorithm(
    data_model.swapped_cities)
print('Best permuttation for swapping method (Hill Climb):', str(best_tour),
      'Distance:', str(best_distance), '\n')
plt.plot(climb, color="green", label="Hill Climb (Swapping method)")
plt.legend(loc="lower right")

# Simulated annealing
simulated_annealing = SimulatedAnnealing(initial_tour, data_model)
print('Starting temperature:', simulated_annealing.start_temp)

best_tour, best_distance, climb = simulated_annealing.perform_algorithm(
    data_model.reversed_sections)
print('Best permuttation for reversed method (Simulated Annealing):',
      str(best_tour), 'Distance:', str(best_distance), '\n')
plt.plot(climb, color="red", label="Simulated Annealing (Reversing method)")
plt.legend(loc="lower right")

best_tour, best_distance, climb = simulated_annealing.perform_algorithm(
    data_model.swapped_cities)
print('Best permuttation for swapping method (Simulated Annealing):',
      str(best_tour), 'Distance:', str(best_distance), '\n')
plt.plot(climb, color="pink", label="Simulated Annealing (Swapping method)")
plt.legend(loc="lower right")
Esempio n. 25
0
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD
from tensorflow.keras import backend as K

# LR: 0.010000 to 0.00001
# local update: 15 to 1
sa = SimulatedAnnealing(initial_temperature=100,
                        cooling=0.8,
                        number_variables=57,
                        upper_bounds=[
                            0.010000, 15, 99, 99, 99, 99, 99, 99, 99, 99, 99,
                            99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
                            99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
                            99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
                            99, 99, 99, 99, 99, 99, 99
                        ],
                        lower_bounds=[
                            0.010000, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                            0, 0, 0, 0, 0, 0, 0, 0
                        ],
                        computing_time=10000,
                        no_attempts=2)
'''
sa = SimulatedAnnealing(initial_temperature=100, cooling=0.8, number_variables=7,#57,
                        upper_bounds=[0.010000, 15, 9, 9, 9, 9, 9],
                        lower_bounds=[0.00001, 1, 0, 0, 0, 0, 0], computing_time=10000, no_attempts=2)
'''

NUM_USERS = 100
Esempio n. 26
0
def main():
    StartTime = time.time()
    SimulatedAnnealing(QUEENS, TEMP)
    CalculateTime(StartTime)
Esempio n. 27
0
    chess = ChessBoard(file_path)

    print('Pilihan algoritma:')
    print('1. Hill-Climbing')
    print('2. Simulated Annealing')
    print('3. Genetic')
    algo_choice = int(input('Masukkan nomor algoritma yang ingin dipakai: '))
    while algo_choice not in [1, 2, 3]:
        print()
        print('Input salah. Tolong ulangi.')
        algo_choice = int(input('Algoritma mana yang ingin dipakai? '))

    if algo_choice == 1:        # hill-climbing
        algo_name = 'Hill-Climbing'
        start_time = clock()
        chess = HillClimbingAlgorithm(chess)
    elif algo_choice == 2:      # simulated annealing
        algo_name = 'Simulated Annealing'
        start_time = clock()
        chess = SimulatedAnnealing(chess)
    else:                       # genetic (algo_choice == 3)
        algo_name = 'Genetic'
        start_time = clock()
        chess = geneticAlgorithm(chess)
    end_time = clock()

    print()
    print('Hasil dari algoritma ' + algo_name)
    chess.printBoardInfo()
    print('Waktu eksekusi:', end_time - start_time, 's')