def main( args ):
    wts = Weights( args.density_score_wt, args.overlap_score_wt, args.closab_score_wt, args.clash_score_wt )
    scorefxn = ScoreFunction( args.density_scorefile, args.overlap_scorefile, args.nonoverlap_scorefile, wts, args.null_frag_score )
    annealer = SimulatedAnnealing( scorefxn, args.steps_per_temp, args.starting_temperature, args.cooling_rate )
    annealer.set_to_quench()
    for run_id in range( args.nstruct ):
        annealer.run( run_id )
Exemple #2
0
def procesar2(archivo):
    datos = []
    ciudades = {}
    with open(archivo) as fp:
        for line in fp:
            if re.match('^[1-9]+', line) is not None:
                renglon = (line.strip()).split(' ')
                datos.append([int(renglon[1]), int(renglon[2])])
                ciudades[int(renglon[0])] = (int(renglon[1]), int(renglon[2]))

    start_time = time.time()
    #resultado = sm.optimized_travelling_salesman(datos)
    resultado = sm.travelling_salesman(datos)
    
    print("--- TSPc: %s seconds ---" % (time.time() - start_time))

    output = np.vstack(resultado)
    x = output[:,0]
    y = output[:,1]
    plt.figure()
    plt.plot(x, y, '-o')
    plt.plot(x[0], y[0], 'og')
    plt.axis('off')
    plt.show()

    start_time = time.time()
    init_state = list(ciudades.keys())
    random.shuffle(init_state)

    # create a distance matrix
    distance_matrix = {}
    for ka, va in ciudades.items():
        distance_matrix[ka] = {}
        for kb, vb in ciudades.items():
            if kb == ka:
                distance_matrix[ka][kb] = 0.0
            else:
                distance_matrix[ka][kb] = sa.distance(va, vb)

    tsp = sa.TravellingSalesmanProblem(init_state, distance_matrix)
    tsp.steps = 100
    # since our state is just a list, slice is the fastest way to copy
    tsp.copy_strategy = "slice"
    state, e = tsp.anneal()

    while state[0] != 1:
        state = state[1:] + state[:1]  # rotate NYC to start
    print("--- TSPa: %s seconds ---" % (time.time() - start_time))
    print("%f Km" % (e*1.60934)) #mile to km
    x = []
    y = []
    for i in state:
        dx, dy = ciudades[i]
        x.append(dx)
        y.append(dy)
    plt.figure()
    plt.plot(x, y, '-o')
    plt.plot(x[0], y[0], 'og')
    plt.axis('off')
    plt.show()
Exemple #3
0
 def test_calculate_L_2(self):
     sa.DISTANCE = sa.l_2
     self.assertEqual(sa.calculate_score(self.a_list, 1),
                      3.1622776601683795)
     self.assertEqual(sa.calculate_score(self.b_list, 2), 8.123105625617661)
     self.assertEqual(sa.calculate_score(self.both_list, 2),
                      11.285383285786041)
Exemple #4
0
    def arrange(self, event):
        self.frame_body.pack_forget()
        self.frame_body = Frame(self.frame)
        self.csp = None
        self.list_of_jadwal_ruangan = []
        self.list_of_jadwal_kegiatan = []

        self.csp = CSP(self.dasbor.entry_nama_file.get())

        if self.pilihan_algoritma.get() == 0:
            schedule = Schedule()
            hill = HillClimbing()
            hill.algorithm(schedule, self.csp, int(self.dasbor.entry_iterasi_maksimal.get()))
        elif self.pilihan_algoritma.get() == 1:
            Schedule1 = Schedule()
            Schedule1.inisialisasi(self.csp)
            SimulatedAnnealing1 = SimulatedAnnealing(float(self.dasbor.entry_T.get()), float(self.dasbor.entry_Tmin.get()), float(self.dasbor.entry_alpha.get()))
            SimulatedAnnealing1.inisialisasi(Schedule1, self.csp)
        elif self.pilihan_algoritma.get() == 2:
            for i in range(int(self.dasbor.entry_iterasi_maksimal.get())):
                PopulasiGA1 = PopulasiGA()
                PopulasiGA1.isiPopulasi(self.csp.getListOfJadwal(), self.csp.getListOfRuangan())
                PopulasiGA1.selection()
                PopulasiGA1.crossOver()
                PopulasiGA1.mutasi(self.csp)
                konflikMinimal, idxMinimal = PopulasiGA1.cekKonflikPopulasi()
                self.csp.setJumlahConflict2(konflikMinimal)
                if (konflikMinimal == 0):
                    break
            PopulasiGA1.assignToCSP(PopulasiGA1.getIndividuByIndex(idxMinimal), self.csp)

        self.dasbor.label_angka_jadwal_bentrok.config(text=str(self.csp.getJumlahConflict2()))
        self.dasbor.label_angka_persentase.config(text=str(self.csp.hitungEfisiensi()*100)+'%')

        for ruangan in self.csp.getListOfRuangan():
            self.list_of_jadwal_ruangan.append(JadwalRuangan(self.frame_body, ruangan))

        for kegiatan in self.csp.getListOfJadwal():
            self.list_of_jadwal_kegiatan.append(JadwalKegiatan(self.list_of_jadwal_ruangan, kegiatan))

        #BINDING
        for jadwal_ruangan in self.list_of_jadwal_ruangan:
            for index_baris in range (2,13):
                for index_kolom in range (1,6):
                    frame_jadwal_ruangan = jadwal_ruangan.matrix_of_frame_jadwal_ruangan[index_baris][index_kolom]
                    frame_jadwal_ruangan.bind('<Button-1>', lambda event, a=jadwal_ruangan, b=index_baris, c=index_kolom: self.pindah_jadwal(a,b,c))

        for jadwal_kegiatan in self.list_of_jadwal_kegiatan:
            for button in jadwal_kegiatan.list_of_button:
                button.bind('<Button-1>', lambda event, a=button.cget('text'), b=jadwal_kegiatan: self.pilih_kegiatan(a,b))

        #SHOW
        for jadwal_ruangan in self.list_of_jadwal_ruangan:
            jadwal_ruangan.show()

        for jadwal_kegiatan in self.list_of_jadwal_kegiatan:
            jadwal_kegiatan.show()

        self.frame_body.pack(side=TOP, expand=True)
def run_annealer( attr ):
    scorefxn, args, run_id = attr
    if exists("model_"+ str(run_id) +".pickle"): 
        return
    annealer = SimulatedAnnealing( scorefxn, args.steps_per_temp, args.starting_temperature, args.cooling_rate )
    if args.quench:
        annealer.set_to_quench() # recover_low for each temperature drop
    annealer.run( run_id )
def main():
    x = [i for i in range(5,26)]
    yGenA = []
    yBB = []
    ySA = []
    yDP = []
    yBF = []
    yGreed = []
    yDAC = []
    for n in range(5,26):
        ITEM_LIST, KNAPSACK_SIZE = Item.generateList(n)
        GeneticAlgorithm.ITEMS, GeneticAlgorithm.KNAPSACK_SIZE  = ITEM_LIST, KNAPSACK_SIZE
        BranchAndBoundAlgorithm.ITEMS, BranchAndBoundAlgorithm.KNAPSACK_SIZE  = ITEM_LIST, KNAPSACK_SIZE
        SimulatedAnnealing.ITEMS, SimulatedAnnealing.KNAPSACK_SIZE  = ITEM_LIST, KNAPSACK_SIZE
        DynamicProgramming.ITEMS, DynamicProgramming.KNAPSACK_SIZE  = ITEM_LIST, KNAPSACK_SIZE
        BruteForceAlgorithm.ITEMS, BruteForceAlgorithm.KNAPSACK_SIZE  = ITEM_LIST, KNAPSACK_SIZE
        GreedyAlgorithm.ITEMS, GreedyAlgorithm.KNAPSACK_SIZE  = ITEM_LIST, KNAPSACK_SIZE
        DivideAndConquerAlgorithm.ITEMS, DivideAndConquerAlgorithm.KNAPSACK_SIZE  = ITEM_LIST, KNAPSACK_SIZE

        Item.printItemList(ITEM_LIST)

        t0 = time()
        GeneticAlgorithm.main()
        tGenA = time()
        BranchAndBoundAlgorithm.main()
        tBB = time()
        SimulatedAnnealing.main()
        tSA = time()
        DynamicProgramming.main()
        tDP = time()
        BruteForceAlgorithm.main()
        tBF = time()
        GreedyAlgorithm.main()
        tGreed = time()
        DivideAndConquerAlgorithm.main()
        tDAC = time()

        yGenA.append(tGenA-t0)
        yBB.append(tBB - tGenA)
        ySA.append(tSA - tBB)
        yDP.append(tDP - tSA)
        yBF.append(tBF - tDP)
        yGreed.append(tGreed - tBF)
        yDAC.append(tDAC - tGreed)
    plt.plot(x, yGenA, label = "Genetic")
    plt.plot(x, yBB, label = "Branch and Bound")
    plt.plot(x, ySA, label = "Simulated annealing")
    plt.plot(x, yDP, label = "Dynamic")
    plt.plot(x, yBF, label = "Brute force")
    plt.plot(x, yGreed, label = "Greedy")
    plt.plot(x, yDAC, label = "Divide and conquer")

    plt.xlabel("number of items")
    plt.ylabel("time spent")
    plt.legend()
    plt.show()

    print()
Exemple #7
0
def main() :
    print("\n▀ ▄ ░ ▀ ▄ ░     █▀▀▄ ░ ░ █░░█ ▀▀█▀▀ █░░█ ░▀░ █▀▀▄ █▀▀▀     ░ ▄ ▀ ░ ▄ ▀")
    print("░ ░ █ ░ ░ █     █░░█ ▀ ▀ █▄▄█ ░░█░░ █▀▀█ ▀█▀ █░░█ █░▀█     █ ░ ░ █ ░ ░")
    print("▄ ▀ ░ ▄ ▀ ░     ▀░░▀ ░ ░ ▄▄▄█ ░░▀░░ ▀░░▀ ▀▀▀ ▀░░▀ ▀▀▀▀     ░ ▀ ▄ ░ ▀ ▄\n")
    fname = input("Masukan Nama File Input Bidak Catur : ")
    pawnInput = input_pawn(fname)
    print("Pilih Algoritma local search yang digunakan"),
    print("1. Hill Climbing")
    print("2. Simulated Annealing")
    print("3. Genetic Algorithm\n")
    str = input(">> Pilihan: ")
    while(not(int(str)==1 or int(str)==2 or int(str)==3)):
        print("Masukan Salah !")
        str = input(">> Pilihan: ")
    if (int(str) == 1) :
        print ("\n-- Solusi Hill Climbing --")
        finalState = hillClimbing.main(pawnInput)
    elif (int(str) == 2) :
        print ("\n-- Solusi Simulated Annealing --")
        finalState = SimulatedAnnealing.main(pawnInput)
    else :
        print ("\n-- Solusi Genetic Algorithm --")
        finalState = geneticalgorithm.main(pawnInput)
    print('\n')
    finalState.printChessBoard()
    print(finalState.sameColorCost, finalState.diffColorCost)
Exemple #8
0
def solve(G):
    """
    Args:
        G: networkx.Graph
    Returns:
        T: networkx.Graph
    """

    # TODO: your code here!

    # Base Case: If no edges, we return the graph itself.
    if len(G.edges()) == 0:
        return G, None, 0

    distance_matrix = nx.to_numpy_array(G)
    print(distance_matrix)
    init_state = list(G.nodes)
    # for node in G.nodes:
    #   init_state.append(str(node))

    network = SimulatedAnnealing.SimulatedAnnealing(init_state,
                                                    distance_matrix, G)
    network.set_schedule(network.auto(minutes=0.2))
    network.copy_strategy = "slice"
    path, cost = network.anneal()
    print(path)
    print(cost)
    T = nx.Graph()
    T.add_nodes_from(path)
    for first, second in zip(path, path[1:]):
        print(first)
        print(second)
        print(G.get_edge_data(first, second))
        T.add_edge(first, second, G[first][second]['weight'])
    return T
 def improve_solution(self, solution, method_type=1):
     if method_type == 1:
         method = FirstImproventDescent(solution)
     elif method_type == 2:
         method = BestImproventDescent(solution)
     elif method_type == 3:
         method = SimulatedAnnealing(solution)
     solution = method.solution
     return solution, solution.fo
Exemple #10
0
def main(input_file):
    offices_list = list()
    customers_list = list()

    input_data = InputReader.read(input_file)
    customers_list = input_data.customers_list

    office_index = 0
    for y in range(len(input_data.map)):
        for x in range(len(input_data.map[0])):
            if (input_data.map[y][x] > 0) and (input_data.map[y][x] <
                                               Terrain.cost_mountains):
                office = Node(office_index, x, y, input_data.map[y][x])

                offices_list.append(office)
                office_index += 1

    # dist_matrix = NodeUtils.distance_matrix(offices_list, customers_list)

    data_points = list()
    for c in customers_list:
        data_points.append([c.x, c.y])

    kmeans_time = time()
    initial_sol = gen_initial_solution(data_points, offices_list,
                                       customers_list,
                                       input_data.num_max_offices)
    # print(str(compute_initial_sol_value(initial_sol, dist_matrix, customers_list)))

    kmeans_time = time() - kmeans_time

    solution = list()
    for sol in initial_sol:
        solution.append(sol.office.index)

    [sol, cost, built_offices,
     sa_time] = sa.simulated_annealing(solution,
                                       offices_list,
                                       customers_list,
                                       verbose=False)
    sa.print_sol(sol, cost, built_offices)
    print("total time (s): " + str(kmeans_time + sa_time))
Exemple #11
0
def main():
    data_Lcopy = [
        "aa", "bb", "aaaa", "abab", "baba", "bbbb", "aaaaaa", "babbab",
        "aabaab", "abaaba", "baabaa", "abbabb", "bbabba", "bbbbbb", "abababab",
        "aabbaabb", "babababa"
    ]
    data_Lpal = [
        "a", "b", "aa", "bb", "aaa", "aba", "bab", "bbb", "aaaa", "abba",
        "baab", "bbbb", "aabaa", "baaab", "abbba", "abaaba", "abbabba"
    ]

    Gcon = Grammar(["a", "b"], ["P", "S"], ["X", "Y"], [
        PRule(Var("P", ["a"]), None, 0.333),
        PRule(Var("P", ["b"]), None, 0.333),
        PRule(Var("P", ["XY"]),
              [Var("P", ["X"]), Var("P", ["Y"])], 0.333),
        PRule(Var("S", ["X"]), [Var("P", ["X"])], 1.0)
    ])

    SA = SimulatedAnnealing(20, 10**-3, 0.995)
    result = SA.run(Gcon, data_Lcopy)
    print(result)
Exemple #12
0
def todo(files):
    coords = []
    with open(files, 'r') as f:
        i = 0
        for line in f.readlines():
            line = [float(x.replace('\n', '')) for x in line.split(' ')]
            coords.append([])
            for j in range(1, 3):
                coords[i].append(line[j])
            i += 1

    if __name__ == '__main__':
        #coords = [[round(random.uniform(-1000,1000),4),round(random.uniform(-1000,1000),4)] for i in range(100)]
        sa = SimAnneal(coords, stopping_iter=5000)
        sa.anneal()
        sa.visualize_routes()
        sa.plot_learning()
Exemple #13
0
 def asignarVuelos(self, dfVuelosEscogidos):
     #Sacar relacion codigoPuertas -> nuevo dfPuertas
     dfPuertasDisp = self.dfPuertas[self.dfPuertas['Estado'] == 1]
     #Quitar puertas asignadas
     for asignacion in self.asignaciones:
         if (asignacion['idVueloAsignado']):
             index = dfPuertasDisp[dfPuertasDisp['idPuerta'] ==
                                   asignacion['idPuerta']].index
             dfPuertasDisp = dfPuertasDisp.drop(index)
     print("dfPuertasDisp")
     print(dfPuertasDisp)
     resultado = SimulatedAnnealing.SimulatedAnnealing(
         dfPuertasDisp, dfVuelosEscogidos)
     print("Resultado de SA")
     print(resultado)
     #A partir del resultado del algoritmo, actualizar la estructura dict asignaciones
     #Resultado es un dataframe donde cada columna es un arreglo de 39 columnas con 0s y 1s
     for index, row in resultado.iterrows():
         #index corresponde al i-esimo elemento de dfVuelos escogidos
         codVueloAsignado = dfVuelosEscogidos.iloc[index]['idVuelo']
         print("codVueloAsignado:", codVueloAsignado)
         #Sacar ocurrencia de 1 en row
         nPuertaAsignada = -1
         i = 0
         for e in row:
             if (e == 1):
                 nPuertaAsignada = i
             i = i + 1
         print("nPuertaAsignada:", nPuertaAsignada)
         #Relacionar ocurrencia de 1 (sistema de filas de SA) con idPuerta
         codPuertaAsignada = dfPuertasDisp.iloc[nPuertaAsignada]['idPuerta']
         print("codPuertaAsignada:", codPuertaAsignada)
         #Actualizar BD interna de asignaciones
         for asignacion in self.asignaciones:
             if (asignacion['idPuerta'] == codPuertaAsignada):
                 asignacion['idVueloAsignado'] = codVueloAsignado
     return resultado
Exemple #14
0
    def build_tour(self,
                   instance='Cincinnati',
                   algorithm='BnB',
                   seed=1,
                   limit=1):

        if algorithm == 'BnB':
            bnb = BranchAndBound.BranchAndBound(self.graph, limit)
            return bnb.generate_tour()
        elif algorithm == 'MSTApprox':
            approx_1 = MSTApprox.MSTApprox(self.graph, instance, seed, limit)
            approx_1.generate_tour()
        elif algorithm == 'Heur':
            approx_2 = NNApprox.NNApprox(self.graph, instance, seed, limit)
            approx_2.generate_tour()
        elif algorithm == 'LS1':
            ls_1 = Opt2Search.Opt2Search(self.graph, instance, seed, limit)
            ls_1.generate_tour()
        elif algorithm == 'LS2':
            ls_2 = SimulatedAnnealing.SimulatedAnnealing(
                self.graph, instance, seed, limit)
            ls_2.generate_tour()
        else:
            return None
Exemple #15
0
	def random_move(self):
		queenToMove = random.randint(0,7)
		newPosition = random.randint(0,7)
		self.queens[queenToMove].move((queenToMove, newPosition))
		self.lastQueenMoved = self.queens[queenToMove]

	def revoke(self):		
		self.lastQueenMoved.revoke()		

if __name__ == "__main__":
	q0 = Queen((0,4))
	q1 = Queen((1,5))
	q2 = Queen((2,6))
	q3 = Queen((3,3))
	q4 = Queen((4,4))
	q5 = Queen((5,5))
	q6 = Queen((6,6))
	q7 = Queen((7,5))
	eq = EightQueens([q0,q1,q2,q3,q4,q5,q6,q7])

	eq.draw()

	eq.random_move()
	eq.draw()

	eq.revoke()
	eq.draw()

	SimulatedAnnealing.simulated_anneal(eq)
	eq.draw()
    # multi thread
    parser.add_argument("--multiprocessor", action="store_true", default=False, help="")
    parser.add_argument("--nprocs", type=int, help="numbers of CPUs you are going to use, default=20")
    args = parser.parse_args()
    print print_args( args )

    wts = Weights( args.density_score_wt, args.overlap_score_wt, args.closab_score_wt, args.clash_score_wt )

    scoretable = ScoreTable( args.selected_frags_path )
    scoretable.score_files_reader( args.density_scorefile, args.overlap_scorefile, args.nonoverlap_scorefile )

    scorefxn = ScoreFunction( scoretable, wts, args.null_frag_score )

    if args.multiprocessor:
        if not args.nprocs: n_procs = processors_availabilty( total_processors() )
        else: n_procs = args.nprocs

        to_pass = [ ( scorefxn, args, runid ) for runid in range( args.nstruct ) ]
        myPool = Pool( processes = n_procs )
        myResults = myPool.map_async( run_annealer, to_pass )
        myResults.get()

    else:
        for run_id in range( args.nstruct ):
            annealer = SimulatedAnnealing( scorefxn, args.steps_per_temp, args.starting_temperature, args.cooling_rate )
            if args.quench:
                annealer.set_to_quench()
            annealer.run( run_id )

Exemple #17
0
def procesar1():
    G = nx.Graph()
    G.add_edge('Ayala', 'Xochiltepec', weight=82.80)
    G.add_edge('Puente de Ixtla', 'Jojutla', weight=25.90)
    G.add_edge('Tlaltizapan', 'Yecapixtla', weight=78.40)
    G.add_edge('Tepoztlan', 'Zacatepec', weight=69.80)
    G.add_edge('Axochiapan', 'Zacatepec', weight=74.50)
    G.add_edge('Jojutla', 'Yecapixtla', weight=123.0)
    G.add_edge('Tepoztlan', 'Xochiltepec', weight=114.0)
    G.add_edge('Tepoztlan', 'Puente de Ixtla', weight=76.30)
    G.add_edge('Tlaltizapan', 'Yecapixtla', weight=60.20)
    G.add_edge('Tlaltizapan', 'Ayala', weight=32.2)
    G.add_edge('Jojutla', 'Ayala', weight=67.4)
    G.add_edge('Yecapixtla', 'Axochiapan', weight=61.90)
    G.add_edge('Axochiapan', 'Xochiltepec', weight=75.60)
    G.add_edge('Zacatepec', 'Jojutla', weight=7.80)
    G.add_edge('Yecapixtla', 'Puente de Ixtla', weight=108.00)
    G.add_edge('Puente de Ixtla', 'Ayala', weight=76.0)
    G.add_edge('Tetela del Volcan', 'Miacatlan', weight=127.18)
    G.add_edge('Yecapixtla', 'Miacatlan', weight=109.65)
    G.add_edge('Emiliano Zapata', 'Temixco', weight=30.7)
    G.add_edge('Atlatlahucan', 'Miacatlan', weight=86.3)
    G.add_edge('Tlaltizapan', 'Atlatlahucan', weight=49.7)
    G.add_edge('Axochiapan', 'Miacatlan', weight=94.8)
    G.add_edge('Tlaltizapan', 'Zacatepec', weight=10.3)
    G.add_edge('Zacatepec', 'Miacatlan', weight=30.3)
    G.add_edge('Cuernavaca', 'Axochiapan', weight=103.0)
    G.add_edge('Tetela del Volcan', 'Miacatlan', weight=127.5)
    G.add_edge('Tlaltizapan', 'Tetela del Volcan', weight=168.18)
    G.add_edge('Zacatepec', 'Tepalcingo', weight=49.5)
    G.add_edge('Tlaltizapan', 'Temixco', weight=32.6)
    G.add_edge('Axochiapan', 'Zacatepec', weight=65.4)
    G.add_edge('Tlaltizapan', 'Tepalcingo', weight=39.5)
    ################    dibujar el grafo
    elarge = [(u, v) for (u, v, d) in G.edges(data=True)]

    pos = {
        'Cuernavaca': [18.92, -99.22],
        'Jiutepec': [18.89, -99.17],
        'Cuautla': [18.81, -98.95],
        'Temixco': [18.85, -99.23],
        'Yautepec': [18.88, -99.06],
        'Emiliano Zapata': [18.84, -99.18],
        'Ayala': [18.76, -98.98],
        'Xochiltepec': [18.77, -99.23],
        'Puente de Ixtla': [18.61, -99.32],
        'Jojutla': [18.61, -99.17],
        'Tlaltizapan': [18.68, -99.12],
        'Yecapixtla': [18.88, -98.86],
        'Tepoztlan': [18.98, -99.09],
        'Zacatepec': [18.65, -99.19],
        'Axochiapan': [18.50, -98.75],
        'Tlaquiltenango': [18.63, -99.16],
        'Tepalcingo': [18.59, -98.84],
        'Miacatlan': [18.77, -99.35],
        'Tetela del Volcan': [18.89, -98.71],
        'Atlatlahucan': [18.93, -98.89]
    }

    datos = []
    for key, value in pos.items():
        datos.append(value)
    #drawing nodes
    nx.draw_networkx_nodes(G, pos, node_size=100, node_color='b')
    #drawing edges
    nx.draw_networkx_edges(G,
                           pos,
                           edgelist=elarge,
                           width=2,
                           alpha=0.5,
                           edge_color='r')

    #drawing labels
    labels = nx.get_edge_attributes(G, 'weight')
    nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)

    print(G.nodes())
    ####Origen-Destino
    origen = (input("Ingresa origen:")).title()
    if not (G.has_node(origen)):
        print("Origen no encontrado")
        sys.exit()
    destino = (input("Ingresa destino:")).title()
    if not (G.has_node(destino)):
        print("Origen no encontrado")
        sys.exit()

    ####rutas
    print(
        "*******************************************************************************"
    )
    print("#### Shortest Path Algorithm ####")
    start_time = time.time()
    print(nx.shortest_path(G, origen, destino,
                           weight='weight'))  #ruta mas corta
    print("--- SPA: %s seconds ---" % (time.time() - start_time))
    SPAA = nx.shortest_path_length(G, origen, destino, weight='weight')
    print("#### Distancia mas corta ####  %f Km ####" %
          (SPAA))  #distancia mas corta
    plt.axis('off')
    plt.show()
    print(
        "*******************************************************************************"
    )
    print("\n")
    print(
        "*******************************************************************************"
    )
    print("#### Minimum Spanning tree ####")
    start_time = time.time()
    T = nx.minimum_spanning_tree(G)
    print("--- MST: %s seconds ---" % (time.time() - start_time))
    print(sorted(T.edges(data=True)))
    plt.figure()
    elarge = [(u, v) for (u, v, d) in T.edges(data=True)]
    nx.draw_networkx_nodes(G, pos, node_size=100, node_color='b')
    nx.draw_networkx_edges(G,
                           pos,
                           edgelist=elarge,
                           width=2,
                           alpha=0.5,
                           edge_color='r')
    plt.axis('off')
    plt.show()
    print(
        "*******************************************************************************"
    )
    print("\n")

    nombres = ("Cuernavaca", "Jiutepec", "Cuautla", "Temixco", "Yautepec",
               "Emiliano Zapata", "Ayala", "Xochiltepec", "Puente de Ixtla",
               "Jojutla", "Tlaltizapan", "Yecapixtla", "Tepoztlan",
               "Zacatepec", "Axochiapan", "Tlaquiltenango", "Tepalcingo",
               "Miacatlan", "Tetela del Volcan", "Atlatlahucan")
    datos = [[18.92, -99.22], [18.89, -99.17], [18.81,
                                                -98.95], [18.85, -99.23],
             [18.88, -99.06], [18.84, -99.18], [18.76,
                                                -98.98], [18.77, -99.23],
             [18.61, -99.32], [18.61, -99.17], [18.68,
                                                -99.12], [18.88, -98.86],
             [18.98, -99.09], [18.65, -99.19], [18.50,
                                                -98.75], [18.63, -99.16],
             [18.59, -98.84], [18.77, -99.35], [18.89, -98.71],
             [18.93, -98.89]]
    points = datos
    #print(nombres)
    origen = (input("TSP - Ingresa ciudad:")).title()
    if origen.title() not in nombres:
        print("Ciudad no encontrada")
        sys.exit()
    ind = nombres.index(origen)
    start_time = time.time()
    resultado = sm.optimized_travelling_salesman(points, points[ind])
    print("--- TSP Optimizado SA(Simulated annealing): %s seconds ---" %
          (time.time() - start_time))
    #print(resultado)
    show = list()
    datos = [[18.92, -99.22], [18.89, -99.17], [18.81,
                                                -98.95], [18.85, -99.23],
             [18.88, -99.06], [18.84, -99.18], [18.76,
                                                -98.98], [18.77, -99.23],
             [18.61, -99.32], [18.61, -99.17], [18.68,
                                                -99.12], [18.88, -98.86],
             [18.98, -99.09], [18.65, -99.19], [18.50,
                                                -98.75], [18.63, -99.16],
             [18.59, -98.84], [18.77, -99.35], [18.89, -98.71],
             [18.93, -98.89]]

    for i in resultado:
        ind = datos.index(i)
        show.append(nombres[ind])
    #print("Ruta: ", show)
    print(
        "*******************************************************************************"
    )
    simulatedSA = sm.total_distance(resultado) * 111.325
    print("#### Distancia Optimizada SA(Simulated annealing) %f Km ####" %
          (simulatedSA))
    print(
        "*******************************************************************************"
    )
    print("\n")
    output = np.vstack(resultado)
    x = output[:, 0]
    y = output[:, 1]
    plt.figure()
    plt.plot(x, y, '-o')
    plt.plot(x[0], y[0], 'og')
    plt.axis('off')
    plt.show()

    start_time = time.time()
    init_state = list(pos.keys())
    random.shuffle(init_state)

    # create a distance matrix
    distance_matrix = {}
    for ka, va in pos.items():
        distance_matrix[ka] = {}
        for kb, vb in pos.items():
            if kb == ka:
                distance_matrix[ka][kb] = 0.0
            else:
                distance_matrix[ka][kb] = sa.distance(va, vb)

    tsp = sa.TravellingSalesmanProblem(init_state, distance_matrix)
    tsp.steps = 100
    # since our state is just a list, slice is the fastest way to copy
    tsp.copy_strategy = "slice"
    state, e = tsp.anneal()

    while state[0] != origen:
        state = state[1:] + state[:1]
    print(
        "*******************************************************************************"
    )
    print("--- TSP Dijkstra %s seconds ---" % (time.time() - start_time))
    print("#### Dijkstra Sin Optimizar %f Km ####" %
          (e * 1.60934))  #mile to km
    print(
        "*******************************************************************************"
    )
    print("\n")
    x = []
    y = []
    for i in state:
        dx, dy = pos[i]
        x.append(dx)
        y.append(dy)
    plt.figure()
    plt.plot(x, y, '-o')
    plt.plot(x[0], y[0], 'og')
    plt.axis('off')
    plt.show()
Exemple #18
0
    def random_move(self):
        queenToMove = random.randint(0, 7)
        newPosition = random.randint(0, 7)
        self.queens[queenToMove].move((queenToMove, newPosition))
        self.lastQueenMoved = self.queens[queenToMove]

    def revoke(self):
        self.lastQueenMoved.revoke()


if __name__ == "__main__":
    q0 = Queen((0, 4))
    q1 = Queen((1, 5))
    q2 = Queen((2, 6))
    q3 = Queen((3, 3))
    q4 = Queen((4, 4))
    q5 = Queen((5, 5))
    q6 = Queen((6, 6))
    q7 = Queen((7, 5))
    eq = EightQueens([q0, q1, q2, q3, q4, q5, q6, q7])

    eq.draw()

    eq.random_move()
    eq.draw()

    eq.revoke()
    eq.draw()

    SimulatedAnnealing.simulated_anneal(eq)
    eq.draw()
def defaultComparison(numOfRuns, numOfPackages, palletDims, minX, maxX, minY, maxY,
                      minWeight, maxWeight, minCapacity, maxCapacity, file):

    # write the method name and current date and time
    file.write("defaultComparison, " + datetime.datetime.now().strftime("%x %X") + "\n")
    # write the method arguments
    file.write(("numOfRuns={0}, numOfPackages={1}, palletDims={2}, minX={2}, maxX={3}, minY={4}, maxY={5}, "
                      + "minWeight={6}, maxWeight={7}, minCapacity={8}, maxCapacity={9}\n")
                .format(numOfRuns, numOfPackages, palletDims, minX, maxX, minY, maxY,
                        minWeight, maxWeight, minCapacity, maxCapacity))
    file.write("\n")

    babTimes = []

    genTimes = []
    genParams = inspect.signature(Genetic.runGeneticXTrials).parameters
    file.write("Genetic params: " + str(genParams) + "\n")
    genDefs = [ genParams["numOfTrials"].default,
                genParams["seed"].default,
                genParams["popSize"].default,
                genParams["generations"].default,
                genParams["numParentPairs"].default,
                genParams["mutationProb"].default ]

    annTimes = []
    annParams = inspect.signature(SimulatedAnnealing.annealXTrials).parameters
    file.write("Annealing params: " + str(annParams) + "\n")
    annDefs = [ annParams["numOfTrials"].default,
                annParams["seed"].default,
                annParams["iterations"].default,
                annParams["maxTries"].default,
                annParams["initialTemp"].default,
                annParams["k"].default ]

    file.write("\n")
    file.flush()

    for i in range(numOfRuns):

        print("\n\nRUN " + str(i))
        file.write("====== Run " + str(i) + " ======\n")
        coords, weightVars = initPackages(numOfPackages, minX, maxX, minY, maxY,
                                          minWeight, maxWeight, minCapacity, maxCapacity, i)
        file.write("coords=" + str(coords) + "\n")
        file.write("weightVars=" + str(weightVars) + "\n")
        file.write("\n")

        print(coords)
        print(weightVars)
        print()

        print("\n\nBRANCH AND BOUNDS " + str(i))
        file.write("Branch and Bounds " + str(i) + "\n")
        babTime = timeit.timeit(
                lambda: BranchandBound.completeBranchAndBoundF(file, coords, weightVars, palletDims), number=1)
        babTimes.append(babTime)
        file.write(str(babTime) + "\n")
        file.write("\n")

        print("\n\nGENETIC " + str(i))
        file.write("Genetic " + str(i) + "\n")
        genTime = timeit.timeit(
                lambda: Genetic.runGeneticXTrialsF(file, coords, weightVars, palletDims,
                                                   1, genDefs[1], genDefs[2],
                                                   genDefs[3], genDefs[4], genDefs[5]), number=1)
        genTimes.append(genTime)
        file.write(str(genTime) + "\n")
        file.write("\n")

        print("\nANNEALING " + str(i))
        file.write("Annealing " + str(i) + "\n")
        annTime = timeit.timeit(
                lambda: SimulatedAnnealing.annealXTrialsF(file, coords, weightVars, palletDims,
                                                          1, annDefs[1], annDefs[2],
                                                          annDefs[3], annDefs[4], annDefs[5]), number=1)
        annTimes.append(annTime)
        file.write(str(annTime) + "\n")
        file.write("\n")

        file.flush()

    babAvgTime = sum(babTimes) / len(babTimes)
    genAvgTime = sum(genTimes) / len(genTimes)
    annAvgTime = sum(annTimes) / len(annTimes)
    file.write("====== Results =======\n")
    file.write("Branch and bound average=" + str(babAvgTime) + "\n")
    file.write("Genetic average=" + str(genAvgTime) + "\n")
    file.write("Simulated annealing average=" + str(annAvgTime) + "\n")
        #list of first group
        fg = random.sample(self.graph, int(len(self.graph) / 2))
        #list of second group
        sg = list(set(self.graph.keys()) - set(fg))
        return (fg,sg)

    def neighbours(self, state):
        result = []
        for first_index,first_node in enumerate(state[0]):
            for second_index,second_node in enumerate(state[1]):
                result.append((
                    list(state[0][:first_index] + [second_node]+state[0][first_index+1:]),
                    list(state[1][:second_index] + [first_node] + state[1][second_index+1:])
                ))
        return result

    def heuristic(self, state):
        heuristic_result = 0
        for first_node in self.graph:
            for second_node in self.graph[first_node]:
                if (first_node in state[0] and second_node in state[1]) or (second_node in state[0] and first_node in state[1]):
                    heuristic_result += 1
        return heuristic_result



from SimulatedAnnealing import *
p = Problem()
a = SimulatedAnnealing(p)
a.solve()
Exemple #21
0
starting_guess = [5.0, 3.0, 1.0, -4.0]
upper_bound = [np.inf, np.inf, np.inf, np.inf]
lower_bound = [0.0, 0.0, 0.0, -np.inf]
'''
simulated annealing fit
'''

fit_result = SA.sim_anneal_fit(
    model=CRISPR.Pclv,
    xdata=training_sequences,
    ydata=training_values,
    yerr=no_chi_squared,
    Xstart=starting_guess,
    lwrbnd=lower_bound,
    upbnd=upper_bound,
    use_multiprocessing=True,
    nprocs=8,
    Tfinal=0.5,
    tol=0.001,
    Tstart=10,
    N_int=1000,
    cooling_rate=0.95,
    output_file_results='/home/mklein1/Training_Pclv/fit_4_1_2017_noise_%s.txt'
    % (noise_amplitude),
    output_file_monitor=
    '/home/mklein1/Training_Pclv/monitor_4_1_2017_noise_%s.txt' %
    (noise_amplitude))

print "input parameter set: ", starting_guess
print "fitted parameter set: ", fit_result
Exemple #22
0
test_problem.number_of_evaluation = 0
optimiser.plotAnimation(g_iterations, visualisationCallback)
EA_number_of_evaluation = test_problem.number_of_evaluation
EA_solution = optimiser.best_solution

# Optimisation and visualisation
test_problem.number_of_evaluation = 0
optimiser = PSO(test_problem, g_number_of_individuals)
optimiser.plotAnimation(g_iterations)
PSO_number_of_evaluation = test_problem.number_of_evaluation
PSO_solution = optimiser.best_solution

# Optimisation and visualisation
test_problem.number_of_evaluation = 0
optimiser = SimulatedAnnealing(test_problem, 5000, 0.04)
optimiser.plotAnimation(211)
SA_number_of_evaluation = test_problem.number_of_evaluation
SA_solution = optimiser.best_solution

for method, number_of_evaluation, solution in zip(methods,
                                                  number_of_evaluation_set,
                                                  solution_set):
    print(method, ".number_of_evaluation:\t", number_of_evaluation)
    print(method, " solution:\t", solution, "\tdistance:\t",
          test_problem.getDistanceToGlobalOptimum(solution))
    print()

print("EA.number_of_evaluation:\t", EA_number_of_evaluation)
print("EA solution:\t", EA_solution, "\tdistance:\t",
      test_problem.getDistanceToGlobalOptimum(EA_solution.genes))
#!/usr/bin/env python3

from SimulatedAnnealing import *;
from AckleyFunction import *

optimiser = SimulatedAnnealing(AckleyFunction(), 5000, 0.04);

# Optimisation and visualisation
optimiser.plotAnimation(200);

print("Solution:\t", optimiser.best_solution);
            datos.append([int(renglon[1]), int(renglon[2])])
            ciudades[int(renglon[0])] = (int(renglon[1]), int(renglon[2]))

print(ciudades)
# initial state, a randomly-ordered itinerary
init_state = list(ciudades.keys())
random.shuffle(init_state)

# create a distance matrix
distance_matrix = {}
for ka, va in ciudades.items():
    distance_matrix[ka] = {}
    for kb, vb in ciudades.items():
        if kb == ka:
            distance_matrix[ka][kb] = 0.0
        else:
            distance_matrix[ka][kb] = sa.distance(va, vb)

tsp = sa.TravellingSalesmanProblem(init_state, distance_matrix)
tsp.steps = 100000
# since our state is just a list, slice is the fastest way to copy
tsp.copy_strategy = "slice"
state, e = tsp.anneal()

while state[0] != 8:
    state = state[1:] + state[:1]  # rotate NYC to start

print()
print("%i mile route:" % e)
for city in state:
    print("\t", city)
 best_tourStat = []
 f_best = 0
 x_best = []
 num_call = 0
 num_try = 0
 calls_to_function = 1  # I initialized to 30 and took the best one
 #  in the following loop, we will call 30 times the SA with different random permutations and save the best solution
 for i in range(calls_to_function):
     perm_x = np.random.permutation(n)  # create permutation
     perm_f = computeTourLength(perm_x, G)  # compute it's length
     print("Length of starting route (first randomized permutation) :",
           perm_f)
     if i == 0:  # first time initialize f_best
         f_best = perm_f
     tourStat.append(perm_f)
     x_min, f_min, history, call = SA.basicSimulatedAnnealing(
         perm_x, G, NTrials)
     tourStat.extend(np.copy(
         history))  # appending to tourStat list the function results of SA
     history.clear()
     if f_min < f_best:  # if we got a better solution keep it and it's attributes
         f_best = f_min
         x_best = np.copy(x_min)
         num_call = call
         num_try = i + 1
         best_tourStat = np.copy(tourStat)
     tourStat.clear()
 print("Best Run : ", f_best)
 print("Best Route : ", x_best)
 print("Number Of Call to Function : ", num_call, "At call No' : ", num_try)
 plt.semilogy(best_tourStat)
 plt.savefig('data.png')
Exemple #26
0
def main():
    """
    This function is responsible for start the menu of the program to execute options that the user will
    choose to solve the problem of nurses allocation
    :return: void
    """

    option = 1

    while option != 0:
        print('Choose one option')
        print('1 - Simulated Annealing')
        print('2 - Genetic Algorithm')
        print('3 - Documentation')
        print('4 - About')
        print('5 - Exit')
        option = int(input())

        if option == 1:
            temperature = 350
            nurses_number = 10
            initial_state = None

            option_temperature_value = int(
                input(
                    'Do you want to define a value to temperature? (Default: 350)\n'
                    '1 - Yes\t\t2 - No\n'))
            if option_temperature_value == 1:
                temperature = int(
                    input('Enter with the value of the temperature:\n'))

            option_nurses_number = int(
                input(
                    'Do you want to define a number of nurses? (Default: 10)\n'
                    '1 - Yes\t\t2 - No\n'))
            if option_nurses_number == 1:
                nurses_number = int(input('Enter number of nurses:\n'))

            option_state = int(
                input('Do you want define the initial state?\n'
                      '1 - Yes\t\t2 - No\n'))
            if option_state == 1:
                iterator = 0
                print(
                    'Alert: An state consists of a string of bits (0 or 1).\n'
                    'Insert the bits of each position all together, without spaces \n'
                    'or any other character.The individual contains ',
                    21 * nurses_number, ' bits.\n')
                initial_state = input('Enter with the initial state :\n')
                while not Au.check_chromosome_composition(
                        chromosome=initial_state, nurses_number=nurses_number):
                    print('Invalid Input')
                    initial_state = input('Enter with the individual number ' +
                                          str(iterator + 1) + ':\n')

            Sa.simulated_annealing_solution(current_state=initial_state,
                                            nurses_number=nurses_number,
                                            temperature=temperature)

        elif option == 2:
            population_size = 40
            amount_of_generations = 1000
            mutation_probability = .05
            elitism_percentage = .01
            nurses_number = 10
            population = list()

            option_population_size = int(
                input('Do you want define population size? (Default: 40)\n'
                      '1 - Yes\t\t2 - No\n'))
            if option_population_size == 1:
                population_size = int(input('Enter population size:\n'))

            option_amount_of_generations = int(
                input(
                    'Do you want to define a amount of generations? (Default: 1000)\n'
                    '1 - Yes\t\t2 - No\n'))
            if option_amount_of_generations == 1:
                amount_of_generations = int(
                    input('Enter amount of generations:\n'))

            option_mutation_probability = int(
                input(
                    'Do you want to define a mutation probability? (Default: 5%)\n'
                    '1 - Yes\t\t2 - No\n'))
            if option_mutation_probability == 1:
                mutation_probability = float(
                    input('Enter mutation probability (Ex: 0.05 to 5%):\n'))

            option_elitism_percentage = int(
                input(
                    'Do you want to define a elitism percentage? (Default: 1%)\n'
                    '1 - Yes\t\t2 - No\n'))
            if option_elitism_percentage == 1:
                elitism_percentage = float(
                    input('Enter elitism percentage (Ex: 0.25 to 25%):\n'))

            option_nurses_number = int(
                input(
                    'Do you want to define a number of nurses? (Default: 10)\n'
                    '1 - Yes\t\t2 - No\n'))
            if option_nurses_number == 1:
                nurses_number = int(input('Enter number of nurses:\n'))

            option_population = int(
                input('Do you want define each individual?\n'
                      '1 - Yes\t\t2 - No\n'))
            if option_population == 1:
                iterator = 0
                print(
                    'Alert: Each individual consists of a string of bits (0 or 1).\n'
                    'Insert the bits of each chromosome all together, without spaces \n'
                    'or any other character.The individual contains ',
                    21 * nurses_number, ' bits.\n')
                while iterator < population_size:
                    individual = input('Enter with the individual number ' +
                                       str(iterator + 1) + ':\n')
                    if Au.check_chromosome_composition(
                            chromosome=individual,
                            nurses_number=nurses_number):
                        population.append(individual)
                        iterator += 1
                    else:
                        print('Invalid Input')

            Ga.generic_algorithm_solution(
                nurses_number=nurses_number,
                population=population,
                population_size=population_size,
                amount_of_generations=amount_of_generations,
                mutation_probability=mutation_probability,
                elitism_percentage=elitism_percentage)

        elif option == 3:
            print('Main Documentation')
            help(main)
            print('-------------------------------------------------------')
            print('Simulated Annealing Documentation')
            help(Sa.simulated_annealing_solution)
            print('-------------------------------------------------------')
            print('Genetic Algorithm Documentation')
            help(Ga.generic_algorithm_solution)
            print('-------------------------------------------------------')
            print('Auxiliary Documentation')
            help(Au.neighbors_generator)
            print('-------')
            help(Au.random_generator)
            print('-------')
            help(Au.fitness_function)
            print('-------')
            help(Au.selection)
            print('-------')
            help(Au.crossover)
            print('-------')
            help(Au.chromosome_mutation)
            print('-------')
            help(Au.check_chromosome_composition)
            print('-------')
            help(Au.calculate_weights)
            print('-------')
            help(Au.print_output_simulated_annealing)
            print('-------')
            help(Au.print_output_genetic_algorithm)
            print('-------------------------------------------------------')

        elif option == 4:
            print(
                '\n\nThis program was developed as a work proposal for the \n'
                'Artificial Intelligence discipline of the Computer Science course \n'
                'at the Federal University of Ceará, Quixadá campus.\n'
                'The authors of the program are the following students: \n'
                'Wallesson Cavalcante and Wesley Pedro. We intend to present \n'
                'solutions to the problem of nurse allocation in their respective \n'
                'shifts using the Simulated Annealing and Genetic Algorithm \n'
                'with some restrictions or extra add-ons.\n\n')

        elif option == 5:
            option = 0

        else:
            print('Invalid option')
Exemple #27
0
Time_To_Execute_Min = Config.Time_To_Execute_Min
Time_To_Execute_Sec = Time_To_Execute_Min * 60

TSP = TravellingSalesPerson.TravellingSalePerson()

with open(filename) as file:
    next(file)
    for line in file:
        city, lat, lon = line.strip('\n').split(',')
        TSP.AddCity(City.City(city, float(lat), float(lon)))

start_time = datetime.datetime.now()

if (Config.Algorithm == Config.Algorithm_Options[0]):
    tsp = SimpleHillClimbing.SimpleHillClimbingWithRestart(TSP, Restart_Count)
elif (Config.Algorithm == Config.Algorithm_Options[1]):
    tsp = SteepestAscendHillClimbing.SteepestAscendHillClimbingWithRestart(
        TSP, Restart_Count)
elif (Config.Algorithm == Config.Algorithm_Options[2]):
    tsp = SimulatedAnnealing.SimulatedAnnealing(TSP, Time_To_Execute_Sec)

stop_time = datetime.datetime.now()

print('Start Time: ' + str(start_time))
print('Stop Time: ' + str(stop_time))
print('Time Taken: ' + str(stop_time - start_time))

print('Orignal Cost : ' + str(TSP.get_hn()))
print('New Cost : ' + str(tsp.get_hn()))
tsp.PlotPath()
Exemple #28
0
import KatkovFunctions as kt
#import DeJong as dj


def toFixed(numObj, digits=0):
    return f"{numObj:.{digits}f}"


x, y, z = kt.makeDataKatkovNumpy()
#x,y,z = dj.makeDataDeJongNumpy()

fig = plt.figure()

x1grad, x2grad, zgrad = grad.gradient()
x1Sim, x2Sim, zSim = sim.SimulatedAnnealing()

#print(type(x1grad), type(x2grad), type(zgrad))

#print(type(x1Sim), type(x2Sim), type(zSim))

ax = fig.add_subplot(111, projection='3d')

fig1 = ax.scatter(float(x1grad), float(x2grad), float(zgrad), s=90.0, c="red")

fig2 = ax.scatter(float(x1Sim), float(x2Sim), float(zSim), s=90.0, c="blue")

fig3 = ax.plot_wireframe(x, y, z)

#приведение к float для окгругления
x1grad = float(x1grad)
Exemple #29
0
def main(args):
    if len(args) == 4:
        k = int(args[1])
        iterations = int(args[2])
        runs = int(args[3])
        numFile = int(args[4])

        f = []
        for (dirpath, dirnames, filenames) in walk("Data"):
            f.extend(filenames)
            break

        files = [dirpath + "/" + filename for filename in f]
        file = files[numFile]
        cities, capacity, dep, name = readProblemFile(file)
        outName = "out" + name + ".csv"
        with open(outName, "w+") as out:
            print name

            times = []
            results = []
            for run in xrange(runs):

                print "Run:", run
                firstGeneration = []
                secondGeneration = queue.Queue()
                inicio = time.time()
                for i in xrange(k):
                    solution = initSolution(capacity, cities, dep)
                    firstGeneration.append(solution)

                best = deepcopy(firstGeneration[0])
                for it in xrange(iterations):
                    print "   It:", it
                    print "      Genetic"
                    for i in xrange(k):
                        mother = firstGeneration[i]
                        aux = firstGeneration[:]
                        aux.remove(mother)
                        father = choice(aux)
                        ga = Genetic(mother, father)
                        ga.cross()

                    print "      SA"
                    for solution in firstGeneration:
                        SA = SimulatedAnnealing(solution, secondGeneration)
                        SA.start()

                    for i in xrange(k):
                        solution = secondGeneration.get()
                        if best == None or solution.getCost() < best.getCost():
                            best = deepcopy(solution)
                        firstGeneration[i] = (solution)

                print "   Best:", best.getCost()
                fim = time.time()
                duracao = fim - inicio
                times.append(duracao)
                results.append(best.getCost())

            writeOutFile(out, name, times, results)
Exemple #30
0
    Min_PairsSat = 0
    Max_PairsSat = 0
    for problem in ProblemInstances[ProblemStart:ProblemStart+incr]:
        run = 0
        runmax = 100
        success = 0
        TotalFalsePos = 0
        FalsePosBeforeSol = 0
        PairsSat = 0
        MinPairs = 0
        MaxPairs = 0
        TTGS = 0
        false_counter = 0
        while run<runmax:
            
            (solnflag,FalsePositives,ttgs)=sa.SA(problem,1,sweep,[0,3])
            
            solns_correct_faults = 0
            temporary_list = []
            for element in FalsePositives:
                if element[0]==faults:
                    solns_correct_faults+=1
                    temporary_list.append(element[1])
            if ttgs[-1][0]==faults:
                final_ttgs = ttgs[-1][1]

            success = success + solnflag
            numnonzero = solns_correct_faults
            
            if solnflag==1:
                FalsePosBeforeSol = FalsePosBeforeSol + numnonzero
Exemple #31
0
#Inititalize data collection and tuning parameters
data = []
shortestTour = []
# stores how the costs of the move decrease as time goes on
decreasingCosts = []
schedule = 'logarithmic'
T_init = 10000

# iterate over alpha and T_init to find best parameters.
while T_init > 1799:
    alpha = 0.99
    while alpha > 0.28:
        for i in range(10):
            startTime = time.time()
            # Collect results from the simulated annealing algorithm
            results = sa.simulatedAnnealing(cities, schedule, T_init, alpha,
                                            True)
            runtime = time.time() - startTime

            #store the data for the shortest path found
            if shortestTour == []:
                shortestTour = [
                    runtime, alpha, T_init, results[1], results[0].length,
                    results[0].path, 1
                ]
                decreasingCosts = results[2]
            if runtime < 300 and results[0].length <= shortestTour[4]:
                shortestTour.append([
                    runtime, alpha, T_init, results[1], results[0].length,
                    results[0].path, 1
                ])
                decreasingCosts.append(results[2])
Exemple #32
0
import SimulatedAnnealing as sim
import DeJong as dj

xs = np.arange(-20, 20, 0.1)
ys = np.arange(-20, 20, 0.1)


def toFixed(numObj, digits=0):
    return f"{numObj:.{digits}f}"


#X, Y, Z = ktk.makeDataKatkovNumpy()
X, Y, Z = dj.makeDataDeJongNumpy()

xGrad, yGrad, zGrad = grad.gradient()
xSim, ySim, zSim = sim.SimulatedAnnealing()

x_dot = np.array([0])
y_dot = np.array([0])
z_dot = np.array([0])
x_dot[0] = float(xSim)
y_dot[0] = float(ySim)
z_dot[0] = float(zSim)

# Блок для поверхности
surface = go.Surface(opacity=0.75, x=X, y=Y, z=Z)
# Блок для точки
dotSim = go.Scatter3d(x=x_dot,
                      y=y_dot,
                      z=z_dot,
                      name="dot from simulated",
Exemple #33
0
def run(test_problem,
        max_iterations: int,
        number_of_runs: int,
        file_prefix: str,
        tol=-1,
        visualisation=False,
        aPreCallback=None,
        aPostCallback=None):
    global g_test_problem
    global g_iterations

    g_test_problem = test_problem

    # Store the results for each optimisation method
    columns = ['Run', 'Methods']
    for i in range(test_problem.number_of_dimensions):
        columns.append("X_" + str(i))

    columns.append("Objective value")
    columns.append("Euclidean distance")
    columns.append("Evaluations")

    df = pd.DataFrame(columns=columns)

    for run_id in range(number_of_runs):

        print("Run #", run_id)

        # Create a random guess common to all the optimisation methods
        initial_guess = g_test_problem.initialRandomGuess()

        # Optimisation methods implemented in scipy.optimize
        methods = [
            'Nelder-Mead', 'Powell', 'CG', 'BFGS', 'L-BFGS-B', 'TNC', 'COBYLA',
            'SLSQP'
        ]

        for method in methods:
            g_test_problem.number_of_evaluation = 0

            optimiser = ScipyMinimize(g_test_problem,
                                      method,
                                      tol=tol,
                                      initial_guess=initial_guess)
            print("\tOptimiser:", optimiser.full_name)

            if not isinstance(aPreCallback, (str, type(None))):
                aPreCallback(optimiser, file_prefix, run_id)

            optimiser.setMaxIterations(max_iterations)

            if run_id == 0 and visualisation:
                optimiser.plotAnimation(
                    aNumberOfIterations=max_iterations,
                    aCallback=None,
                    aFileName=(file_prefix + "_" + optimiser.short_name +
                               "_%d.png"))
            else:
                optimiser.run()

            df = appendResultToDataFrame(run_id, optimiser, df, columns,
                                         file_prefix)

            if not isinstance(aPostCallback, (str, type(None))):
                aPostCallback(optimiser, file_prefix, run_id)

        # Parameters for EA
        g_iterations = int(max_iterations / g_number_of_individuals)

        # Optimisation and visualisation
        g_test_problem.number_of_evaluation = 0
        optimiser = EvolutionaryAlgorithm(g_test_problem,
                                          g_number_of_individuals,
                                          initial_guess=initial_guess)
        print("\tOptimiser:", optimiser.full_name)
        if not isinstance(aPreCallback, (str, type(None))):
            aPreCallback(optimiser, file_prefix, run_id)

        # Set the selection operator
        #optimiser.setSelectionOperator(TournamentSelection(3));
        #optimiser.setSelectionOperator(RouletteWheel());
        optimiser.setSelectionOperator(RankSelection())

        # Create the genetic operators
        gaussian_mutation = GaussianMutationOperator(0.1, 0.3)
        elitism = ElitismOperator(0.1)
        new_blood = NewBloodOperator(0.0)
        blend_cross_over = BlendCrossoverOperator(0.6, gaussian_mutation)

        # Add the genetic operators to the EA
        optimiser.addGeneticOperator(new_blood)
        optimiser.addGeneticOperator(gaussian_mutation)
        optimiser.addGeneticOperator(blend_cross_over)
        optimiser.addGeneticOperator(elitism)

        if run_id == 0 and visualisation:
            optimiser.plotAnimation(
                aNumberOfIterations=g_iterations,
                aCallback=visualisationCallback,
                aFileName=(file_prefix + "_" + optimiser.short_name +
                           "_%d.png"))

        else:
            for _ in range(1, g_iterations):
                optimiser.runIteration()
                visualisationCallback()

        df = appendResultToDataFrame(run_id, optimiser, df, columns,
                                     file_prefix)

        if not isinstance(aPostCallback, (str, type(None))):
            aPostCallback(optimiser, file_prefix, run_id)

        # Parameters for PSO

        # Optimisation and visualisation
        g_test_problem.number_of_evaluation = 0
        optimiser = PSO(g_test_problem,
                        g_number_of_individuals,
                        initial_guess=initial_guess)
        print("\tOptimiser:", optimiser.full_name)
        if not isinstance(aPreCallback, (str, type(None))):
            aPreCallback(optimiser, file_prefix, run_id)

        if run_id == 0 and visualisation:
            optimiser.plotAnimation(
                aNumberOfIterations=g_iterations,
                aCallback=visualisationCallback,
                aFileName=(file_prefix + "_" + optimiser.short_name +
                           "_%d.png"))

        else:
            for _ in range(1, g_iterations):
                optimiser.runIteration()
                visualisationCallback()

        df = appendResultToDataFrame(run_id, optimiser, df, columns,
                                     file_prefix)

        if not isinstance(aPostCallback, (str, type(None))):
            aPostCallback(optimiser, file_prefix, run_id)

        # Optimisation and visualisation
        optimiser = PureRandomSearch(g_test_problem,
                                     max_iterations,
                                     initial_guess=initial_guess)
        print("\tOptimiser:", optimiser.full_name)
        if not isinstance(aPreCallback, (str, type(None))):
            aPreCallback(optimiser, file_prefix, run_id)

        g_test_problem.number_of_evaluation = 0

        if run_id == 0 and visualisation:
            optimiser.plotAnimation(
                aNumberOfIterations=max_iterations,
                aCallback=None,
                aFileName=(file_prefix + "_" + optimiser.short_name +
                           "_%d.png"))
        else:
            for _ in range(max_iterations):
                optimiser.runIteration()

        df = appendResultToDataFrame(run_id, optimiser, df, columns,
                                     file_prefix)

        if not isinstance(aPostCallback, (str, type(None))):
            aPostCallback(optimiser, file_prefix, run_id)

        # Optimisation and visualisation
        g_test_problem.number_of_evaluation = 0

        optimiser = SimulatedAnnealing(g_test_problem,
                                       5000,
                                       0.04,
                                       initial_guess=initial_guess)
        print("\tOptimiser:", optimiser.full_name)
        optimiser.cooling_schedule = cooling
        if not isinstance(aPreCallback, (str, type(None))):
            aPreCallback(optimiser, file_prefix, run_id)

        if run_id == 0 and visualisation:
            optimiser.plotAnimation(
                aNumberOfIterations=max_iterations,
                aCallback=None,
                aFileName=(file_prefix + "_" + optimiser.short_name +
                           "_%d.png"))
        else:
            for _ in range(1, max_iterations):
                optimiser.runIteration()
            #print(optimiser.current_temperature)

        df = appendResultToDataFrame(run_id, optimiser, df, columns,
                                     file_prefix)

        if not isinstance(aPostCallback, (str, type(None))):
            aPostCallback(optimiser, file_prefix, run_id)

    title_prefix = ""

    if g_test_problem.name != "":
        if g_test_problem.flag == 1:
            title_prefix = "Minimisation of " + g_test_problem.name + "\n"
        else:
            title_prefix = "Maximisation of " + g_test_problem.name + "\n"

    boxplot(df, 'Evaluations', title_prefix + 'Number of evaluations',
            file_prefix + 'evaluations.pdf', False)

    boxplot(
        df, 'Euclidean distance',
        title_prefix + 'Euclidean distance between\nsolution and ground truth',
        file_prefix + 'distance.pdf', False)

    plt.show()
    optimizers = []
    exp = experiments.experiments()

    # First problem is the Knapsack
    weights = np.random.randint(1, 20, size=20)
    values = np.random.randint(1, 10, size=20)
    max_weight_pct = 0.65
    fitness = mlrose.Knapsack(weights, values, max_weight_pct)
    # Define optimization problem object
    problemFit = mlrose.DiscreteOpt(length=20, fitness_fn=fitness, maximize=True)
    # Create and run the Randomized Hill Climbing Optimizer class
    rhcOptimizer = rhc.RHC()
    optimizers.append(rhcOptimizer)
    exp.getComplexityCurve(optimizer=rhcOptimizer, problem=problemFit, problemName='Knapsack')
    # Create and run the Simulated Annealing Optimizer class
    saOptimizer = sa.SA()
    optimizers.append(saOptimizer)
    exp.getComplexityCurve(optimizer=saOptimizer, problem=problemFit, problemName='Knapsack')
    # Create and run the Genetic Algorithm Optimizer class
    gaOptimizer = ga.GA()
    optimizers.append(gaOptimizer)
    exp.getComplexityCurve(optimizer=gaOptimizer, problem=problemFit, problemName='Knapsack')
    # Create and run the MIMIC Optimizer class
    mimicOptimizer = mimic.MIMIC()
    optimizers.append(mimicOptimizer)
    exp.getComplexityCurve(optimizer=mimicOptimizer, problem=problemFit, problemName='Knapsack')
    exp.getComparisonCurve(optimizers, problem=problemFit, problemName='Knapsack')

    # Second problem is the One Max
    optimizers = []
    fitness = mlrose.OneMax()