Esempio n. 1
0
 def solve(self, filename):
     """implements the Simulated Annealing algorithm for VRPTW"""
     self.problem_file = filename
     if self.trace:
         global fig
         plt.ion()
         fig = plt.figure()
         fig.canvas.set_window_title('Simulated Annealing')
     else:
         self.histograms = False
     self.problem = Problem()
     self.problem.load_problem(filename)
     #problem.eliminate_time_windows()
     start_time = time.time()
     self.current = random_solution(self.problem)
     #current = insertion1_vrptw(problem)
     self.run()
     self.best.endtime = time.time()
     self.best.starttime = start_time
     if self.trace:
         self.best.plot(True)
         self.present_statistics()
         plt.pause(0.0001)
         input("Push <ENTER> to finish")
         plt.ioff()
def solve_vrptw(problem, heuristic, max_iter, display=True):
    """implements the Stochastic Hill Climbing algorithm for VRPTW"""
    start_time = time.time()
    current = random_solution(problem)
    #current = insertion1_vrptw(problem)
    ini_sol = current
    if display:
        current.plot()
        fig.canvas.draw()
    last_improved = 0
    print("heuristic:", heuristic.name)
    advance = max_iter // 10
    it = 0
    for i in range(max_iter):
        it += 1
        candidate = create_neighbor(current, heuristic, current.cost())
        if candidate.cost() < current.cost():
            current = candidate
            last_improved = i+1
            if display:
                current.plot()
                fig.canvas.draw()
        if display:
            print(" > iteration=%d, curr= %g" % (i+1, current.cost()))
        elif it == advance:
            it = 0
            print("%d%%" % (int(((i+1) / max_iter) * 100)))
    current.endtime = time.time()
    current.starttime = start_time
    if display:
        current.plot(True)
        fig.canvas.draw()
        perturbative_statistics()
        PerturbativeHeuristic.plot()
    return ini_sol, current, last_improved
def simulated_annealing(filename, max_temp, min_temp, eq_iter, temp_change,
                        trace=True, histograms=False):
    """implements the Simulated Annealing algorithm for VRPTW"""
    if trace:
        global fig
        plt.ion()
        fig = plt.figure()
        fig.canvas.set_window_title('Simulated Annealing')
    else: histograms = False
    problem = Problem()
    problem.load_problem(filename)
    #problem.eliminate_time_windows()
    start_time = time.time()
    current = random_solution(problem)
    #current = insertion1_vrptw(problem)
    temp = max_temp
    best = copy.copy(current)
    if trace:
        best.plot()
        fig.canvas.draw()
        plt.pause(0.0001)
    i = 0
    perturbative_heuristics()
    while temp > min_temp:
        eiter = 0
        while eiter < eq_iter:
            i += 1
            candidate = create_neighbor(current, best.cost(), histograms)
            if should_accept(candidate, current, temp): current = candidate
            if candidate.cost() < best.cost():
                best = copy.copy(candidate)
                if trace:
                    best.plot()
                    fig.canvas.draw()
                    plt.pause(0.0001)
            if trace: print(" > iteration=%d, temp=%g, curr= %g, best=%g" %
                            (i,temp,candidate.cost(), best.cost()))
            eiter += 1
        temp *= temp_change
    best.endtime = time.time()
    best.starttime = start_time
    if trace:
        best.plot(True)
        plt.pause(0.0001)
        perturbative_statistics()
    if histograms: 
        PerturbativeHeuristic.plot()
        plt.pause(0.001)
    if trace:
        input("Push <ENTER> to finish") 
        plt.ioff()
    return best
def tabu_search(filename, max_iter, tabu_tenure, max_candidates, trace=True):
    """implements the Tabu Search algorithm"""
    if trace:
        global fig
        plt.ion()
        fig = plt.figure()
        fig.canvas.set_window_title('Tabu Search')
    problem = Problem()
    problem.load_problem(filename)
    #problem.eliminate_time_windows()
    start_time = time.time()
    current = random_solution(problem)
    #current = insertion1_vrptw(problem)
    current_cost = current.cost()
    if trace:
        current.plot()
        fig.canvas.draw()
        plt.pause(0.0001)
    tabu_list = {}
    for niter in range(max_iter):
        candidates = []
        for _ in range(max_candidates):
            candidates.append(
                generate_candidate(current, list(tabu_list.keys())))
        best_candidate, best_edges = min(candidates, key=lambda c: c[0].cost())
        best_candidate_cost = best_candidate.cost()
        if best_candidate_cost < current_cost:
            current = best_candidate
            current_cost = best_candidate_cost
            if trace:
                current.plot()
                fig.canvas.draw()
                plt.pause(0.0001)
            tabu_list[best_edges] = tabu_tenure
        for k in list(tabu_list.keys()):
            tabu_list[k] -= 1
            if tabu_list[k] == 0: del tabu_list[k]
        if trace: print(" > iteration=%d, best=%g" % (niter + 1, current_cost))
    current.endtime = time.time()
    current.starttime = start_time
    if trace:
        current.plot(True)
        plt.pause(0.001)
        input("press <ENTER> to finish")
        plt.ioff()
    return current
Esempio n. 5
0
def ant_colony_system(filename, max_iter, num_ants, decay, c_hist, c_heur,
                      c_local_phero, c_greed, trace=True):
    """implements an Ant Colony System for VRPTW"""
    if trace:
        global fig
        plt.ion()
        fig = plt.figure()
        fig.canvas.set_window_title('Ant Colony System')
    problem = Problem()
    problem.load_problem(filename)
    #problem.eliminate_time_windows()
    start_time = time.time()
    best = random_solution(problem)
    #best = parallel_savings_vrptw(problem)
    init_pheromone = 1.0 / ((problem.ncustomers-1) * best.cost())
    pheromone = initialise_pheromone_matrix(problem.ncustomers, init_pheromone)
    if trace:
        best.plot()
        fig.canvas.draw()
        plt.pause(0.0001)
    for i in range(max_iter):
        for ant in range(num_ants):
            candidate = ant_solution(problem, pheromone, c_hist, c_heur, c_greed)
            if trace: print(" ant=%d, cost=%g" % (ant+1, candidate.cost()))
            if candidate.cost() < best.cost():
                best = candidate
                if trace:
                    best.plot()
                    fig.canvas.draw()
                    plt.pause(0.0001)
            local_update_pheromone(pheromone, candidate, c_local_phero,
                                   init_pheromone)
        global_update_pheromone(pheromone, best, decay)
        if trace: print(" > iteration=%d, best=%g" % (i+1, best.cost()))
    best.endtime = time.time()
    best.starttime = start_time
    if trace:
        best.plot(True)
        plt.pause(0.0001)
        input("press <ENTER> to finish")
        plt.ioff()
    return best
Esempio n. 6
0
def genetic_algorithm(filename, max_gens, pop_size, p_crossover, p_mutation,
                      trace=True, histograms=False):
    """implements a Genetic Algorithm for VRPTW"""
    if trace:
        global fig
        plt.ion()
        fig = plt.figure(figsize=(14,5.5))
        fig.canvas.set_window_title('Genetic Algorithm')
    else: histograms = False
    problem = Problem()
    problem.load_problem(filename)
    #problem.eliminate_time_windows()
    start_time = time.time()
    population = []
    # creates the initial population
    best = None
    for _ in range(pop_size):
        individual = random_solution(problem)
        if not best or fitness(individual) < fitness(best):
            best = copy.copy(individual)
        population.append(individual)
    # repeats for max_gens generations
    perturbative_heuristics()

    if trace:
        fig
        plt.subplot(121)
        best.plot()
        # trace fitness evolution
        gen_update = max(int(max_gens / 100),1)
        best_fit, avg_fit, worst_fit = [], [], []
        plt.subplot(122)
        trace_fitness(population, best_fit, avg_fit, worst_fit, gen_update, pop_size)
        fig.canvas.draw()
        plt.pause(0.0001)
    
    for gen in range(max_gens):
        selected = []
        for _ in range(pop_size): selected.append(binary_tournament(population))
        children = reproduce(selected, pop_size, p_crossover, p_mutation,
                             best.cost(), histograms)
        children.sort(key=lambda i: fitness(i))
        if fitness(children[0]) < fitness(best):
            best = copy.copy(children[0])
            if trace:
                fig
                plt.subplot(121)
                best.plot()
                fig.canvas.draw()
                plt.pause(0.0001)
        population = children

        if trace and gen % gen_update == 0:
            # update trace of fitness evolution
            fig
            plt.subplot(122)
            trace_fitness(population, best_fit, avg_fit, worst_fit,
                          gen_update, pop_size)
            fig.canvas.draw()
            plt.pause(0.0001)
        
        if trace: print(" > gen %d, best: %g" % (gen+1, best.cost()))
    best.endtime = time.time()
    best.starttime = start_time
    if trace:
        fig
        plt.subplot(121)
        best.plot(True)
        plt.pause(0.001)
        perturbative_statistics()
    if histograms: 
        PerturbativeHeuristic.plot()
        plt.pause(0.001)
    if trace: 
        input("press <ENTER> to finish")
        plt.ioff()
    return best