コード例 #1
0
def main():
    problema = ProblemaMochila()
    #hill_climbing = HillClimbing(max_iteracoes=100, max_iteracoes_sem_melhora=100)
    #hill_climbing.executa(problema)

    tabu_search = TabuSearch(max_iteracoes=100, max_iteracoes_sem_melhora=100, tamanho_tabu_search=100000)
    tabu_search.executa(problema)
コード例 #2
0
ファイル: HRH.py プロジェクト: kaouthardjezzar/BinPacking
    def run(self):
        result1 = GeneticAlgorithm(self.bin_capacity, self.items,self.POPULATION_SIZE,self.MAX_GENERATIONS,self.MAX_NO_CHANGE,self.TOURNAMENT_SIZE,self.MUTATION_RATE,self.CROSSOVER_RATE)
        total_iterationsAG, stagnationAG = result1.run()

        result2 = TabuSearch(self.bin_capacity, self.items,self.MAX_COMBINATION_LENGTH,self.MAX_ITERATIONS,self.MAX_NO_CHANGE2)
        total_iterationsTB, stagnationTB, combinationTB = result2.run2(result1)

        return result1,result2,total_iterationsAG, stagnationAG, total_iterationsTB, stagnationTB, combinationTB
コード例 #3
0
ファイル: LTH2.py プロジェクト: kaouthardjezzar/BinPacking
    def rl(self, chromosome): 
        """
        solution = chromosome.generate_solution(self.items)
        sa = SA(0.9,chromosome.capacity,[],100,10,10)
        sa.run_for_lth(solution)
        """
        result = TabuSearch(chromosome.bin_capacity, self.items,self.MAX_COMBINATION_LENGTH,self.MAX_ITERATIONS,self.MAX_NO_CHANGE2)
        total_iterationsTB, stagnationTB, combinationTB = result.run3(chromosome)

        return Chromosome(chromosome.bin_capacity,combinationTB)
コード例 #4
0
def main():
    # Definicao do problema
    p = ProblemaRaiz()

    pm = ProblemaMochila()

    #hc = HillClimbing(max_alt=100, max_sem_alt=10)
    #hc.executa(pm)

    tb = TabuSearch(max_alt=1000, max_sem_alt=10)
    tb.executa(pm)
コード例 #5
0
def main():
    # Definicao do problema
    p = ProblemaRaiz()

    hc = HillClimbing(max_alt=1000, max_sem_alt=10)
    hc.executa(p)

    tb = TabuSearch(max_alt=1000, max_sem_alt=10)
    tb.executa(p)

    tbg = TabuSearchGrasp(max_alt=1000, max_sem_alt=10)
    tbg.executa(p)
コード例 #6
0
def run_tabu_search(seconds, initial_cadence, critical_event):
    print('Running Tabu Search for ' + str(seconds) + ' seconds...')
    print()

    ts = TabuSearch(states, seconds, initial_cadence, critical_event,
                    inc_support, dec_support)
    ts.run()
    print('Found optimal route with value of ' + str(ts.best_solution.value) +
          '.')
    print(
        str(ts.best_solution.calculate_real_value()) +
        ' electoral votes were collected.')
    ts.best_solution.print()
    print()
コード例 #7
0
ファイル: test.py プロジェクト: powerllamas/MiOIB
 def setUp(self):
     self.flow = [
             [0, 1, 2],
             [4, 0, 5],
             [7, 2, 0]]
     self.distance = [
             [0, 5, 2],
             [1, 0, 1],
             [6, 2, 0]]
     self.i = Instance(None, self.distance, self.flow)
     self.e = E(self.i)
     self.ts = TabuSearch()
     self.startpoint = Solution((0, 1, 2))
コード例 #8
0
    # Loop through each data set.
    for dataset in datasets:
        # Read the data into memory
        with open('datasets/{}'.format(dataset["name"]), 'r') as file:
            data = file.read().splitlines()
            num_items, capacity, items = int(data[0]), int(data[1]), data[2:]
            log("\n\nDATASET {}: num_items {} capacity {} items_read {}".
                format(dataset["name"], num_items, capacity, len(items)))
        items = [Item(size=int(i)) for i in items]
        log("  Iteration", end=" ")
        # Perform 30 independent iterations.
        for iteration in range(30):
            log(iteration + 1, end=" ")
            # Randomize the order of the items in the item list.
            shuffle(items)
            thing = TabuSearch(capacity, items)

            start_time = datetime.now()
            total_iterations, stagnation, combination = thing.run()
            execution_time = datetime.now() - start_time

            # Record the relevant data for analysis
            summary = {
                "execution_time": str(execution_time),
                "num_bins": len(thing.bins),
                "fitness":
                sum(b.fitness() for b in thing.bins) / len(thing.bins),
                "iterations": total_iterations,
                "stagnation": stagnation,
                "combination": combination,
                "tabu_list": list(thing.tabu_list)
コード例 #9
0
def execute_algo(name, capacity, items):
    if (name == 'SA'):
        sa = SA(0.7, capacity, items, 500, 10, 8)
        start_time = datetime.now()
        sa.run()
        execution_time = datetime.now() - start_time
        bins_algo = len(sa.bins)
        time_algo = execution_time.total_seconds()
    elif (name == 'RT'):
        thing = TabuSearch(capacity, items)
        start_time = datetime.now()
        total_iterations, stagnation, combination = thing.run()
        execution_time = datetime.now() - start_time
        bins_algo = len(thing.bins)
        time_algo = execution_time.total_seconds()
    elif (name == 'GA'):
        thing = GeneticAlgorithm(capacity, items)
        start_time = datetime.now()
        total_iterations, stagnation = thing.run()
        execution_time = datetime.now() - start_time
        time_algo = execution_time.total_seconds()
        bins_algo = thing.best_solution.num_bins
    elif (name == 'HRH'):
        thing = HRH(capacity, items)
        start_time = datetime.now()
        result1, result2, total_iterationsAG, stagnationAG, total_iterationsTB, stagnationTB, combinationTB = thing.run(
        )
        execution_time = datetime.now() - start_time
        time_algo = execution_time.total_seconds()
        bins_algo = len(result2.bins)
    elif (name == 'HRH_RS'):
        thing = HRH_RS(capacity, items)
        start_time = datetime.now()
        sa = thing.run()
        execution_time = datetime.now() - start_time
        time_algo = execution_time.total_seconds()
        bins_algo = len(sa.bins)
    elif (name == 'LTH'):
        thing = LTH(capacity, items)
        start_time = datetime.now()
        total_iterations, stagnation = thing.run()
        execution_time = datetime.now() - start_time
        time_algo = execution_time.total_seconds()
        bins_algo = thing.best_solution.num_bins
    elif (name == 'LTH2'):
        thing = LTH2(capacity, items)
        start_time = datetime.now()
        total_iterations, stagnation = thing.run()
        execution_time = datetime.now() - start_time
        time_algo = execution_time.total_seconds()
        bins_algo = thing.best_solution.num_bins
    # elif(name == 'HTH'):
    #     thing = HTH(capacity, items)
    #     start_time = datetime.now()
    #     sa = thing.run()
    #     execution_time = datetime.now() - start_time
    #     time_algo = execution_time.total_seconds()
    #     bins_algo = [len(a) for a in sa]

    elif (name == 'FirstFit'):
        start_time = datetime.now()
        bins = [Bin(capacity=capacity)]
        for item in items:
            bins = FirstFit.apply(item, bins)
        execution_time = datetime.now() - start_time
        time_algo = execution_time.total_seconds()
        bins_algo = len(bins)

    elif (name == 'NextFit'):
        start_time = datetime.now()
        bins = [Bin(capacity=capacity)]
        for item in items:
            bins = NextFit.apply(item, bins)
        execution_time = datetime.now() - start_time
        time_algo = execution_time.total_seconds()
        bins_algo = len(bins)

    elif (name == 'BestFit'):
        start_time = datetime.now()
        bins = [Bin(capacity=capacity)]
        for item in items:
            bins = BestFit.apply(item, bins)
        execution_time = datetime.now() - start_time
        time_algo = execution_time.total_seconds()
        bins_algo = len(bins)

    elif (name == 'WorstFit'):
        start_time = datetime.now()
        bins = [Bin(capacity=capacity)]
        for item in items:
            bins = WorstFit.apply(item, bins)
        execution_time = datetime.now() - start_time
        time_algo = execution_time.total_seconds()
        bins_algo = len(bins)

    elif (name == 'FirstFitDec'):
        start_time = datetime.now()
        bins = [Bin(capacity=capacity)]
        item_sort = sorted(items, key=lambda x: x.size, reverse=True)
        for item in item_sort:
            bins = FirstFitDec.apply(item, bins)
        execution_time = datetime.now() - start_time
        time_algo = execution_time.total_seconds()
        bins_algo = len(bins)

    return bins_algo, time_algo
コード例 #10
0
def benchmark():
    REPEATS = 10
    SECONDS = [5, 10, 30, 60, 300, 1200]

    for seconds in SECONDS:
        v = 0
        time_s = datetime.now()
        for k in range(REPEATS):
            rs = RandomSearch(states, seconds, inc_support, dec_support)
            rs.run()
            v += rs.best_solution.value
        time_e = datetime.now()
        tt = (time_e - time_s).total_seconds()
        print_csv('Random Search', str(seconds), str(v / REPEATS),
                  str(tt / REPEATS))

    for seconds in SECONDS:
        v = 0
        time_s = datetime.now()
        for k in range(REPEATS):
            ls = LocalSearch(states, seconds, inc_support, dec_support)
            ls.run()
            v += ls.best_solution.value
        time_e = datetime.now()
        tt = (time_e - time_s).total_seconds()
        print_csv('Local Search', str(seconds), str(v / REPEATS),
                  str(tt / REPEATS))

    for seconds in SECONDS:
        for initial_cadence in [10, 25, 50]:
            for critical_event in [10, 25, 50]:
                v = 0
                time_s = datetime.now()
                for k in range(REPEATS):
                    ts = TabuSearch(states, seconds, initial_cadence,
                                    critical_event, inc_support, dec_support)
                    ts.run()
                    v += ts.best_solution.value
                time_e = datetime.now()
                tt = (time_e - time_s).total_seconds()
                print_csv('Tabu Search', str(seconds), str(initial_cadence),
                          str(critical_event), str(v / REPEATS),
                          str(tt / REPEATS))

    for crossover in ['pmx', 'ox']:
        for mutate in ['transposition', 'insertion', 'inversion']:
            for seconds in SECONDS:
                for population_size in [10, 25, 50]:
                    v = 0
                    time_s = datetime.now()
                    for k in range(REPEATS):
                        ga = GeneticAlgorithm(states, seconds, population_size,
                                              crossover, mutate, inc_support,
                                              dec_support)
                        ga.run()
                        v += ga.best_solution.value
                    time_e = datetime.now()
                    tt = (time_e - time_s).total_seconds()
                    print_csv('Genetic Algorithm ' + crossover + ' ' + mutate,
                              str(seconds), str(population_size),
                              str(v / REPEATS), str(tt / REPEATS))

    for initial_temperature in [100, 500, 1000]:
        for cooling_coefficient in [0.9, 0.99, 0.999, 0.9999]:
            for minimal_temperature in [
                    initial_temperature * 0.25, initial_temperature * 0.5,
                    initial_temperature * 0.75
            ]:
                v = 0
                time_s = datetime.now()
                for k in range(REPEATS):
                    sa = SimulatedAnnealing(states, initial_temperature,
                                            cooling_coefficient,
                                            minimal_temperature, inc_support,
                                            dec_support)
                    sa.run()
                    v += sa.best_solution.value
                time_e = datetime.now()
                tt = (time_e - time_s).total_seconds()
                print_csv('Simulated Annealing', str(initial_temperature),
                          str(cooling_coefficient), str(minimal_temperature),
                          str(v / REPEATS), str(tt / REPEATS))
コード例 #11
0
    def optimize(self, tree, alternative, task_duration, release_dates,
                 due_dates, no_iter):
        """
        A method that starts ant colony optimization algorithm for generating schedule from unordered list of methods.

        :param tree: TaemsTree with hierarchical task structure
        :param alternative: an unordered list of actions to schedule
        :param task_duration: dictionary, key: action id, value: action duration
        :param release_dates: dictionary, key: action id, value: action due date
        :param due_dates: dictionary, key: action id, value: action release date
        :param no_iter: number of iterations of the algorithm
        :return: [(Solution) best found solution, (int) iteration at which the solution was found]
        """
        sim = simulator.LightSimulator(tree)
        t = deepcopy(alternative)
        # tasks.extend(nonLocalTasks)
        sim.execute_alternative(t, t)
        tasks_to_complete = sim.completedTasks

        start = time.time()

        tabu = TabuSearch(5)
        self.tasks = [x for x in alternative]
        self.pheromone = np.full((len(self.tasks), len(self.tasks)),
                                 self.init_pheromone)

        iteration = 0
        best_solution_iter = 0
        while iteration < no_iter:
            solutions = []
            ratings = []
            for i in range(self.ant_number):
                solution = self.generate_solution(tree, alternative,
                                                  tasks_to_complete,
                                                  task_duration, due_dates)
                solution.evaluate(due_dates, release_dates)

                [optimized,
                 _] = tabu.optimize(tree, alternative, task_duration,
                                    release_dates, due_dates, 10, False)

                solutions.append(optimized)
                ratings.append(optimized.total_tardiness)

            if self.best_solution is None:
                self.best_solution = solutions[ratings.index(min(ratings))]
                best_solution_iter = iteration

            elif min(ratings) < self.best_solution.total_tardiness:
                self.best_solution = solutions[ratings.index(min(ratings))]
                best_solution_iter = iteration

            self.evaporate_pheromones()
            for item in solutions:
                self.add_pheromone(item)
            iteration += 1

        print(time.time() - start)
        print("best solution: " + str(self.best_solution.total_tardiness))
        self.best_solution.print_schedule()

        return [self.best_solution, best_solution_iter]
コード例 #12
0
            planes = []
            for idx in range(num_planes):
                params = file.readline().split()
                params = [int(x) for x in params[:-2]] + [float(params[-2]), float(params[-1])]
                separation_times = [int(x) for x in file.readline().split()]
                arrival_time, earliest_time, target_time, latest_time, early_penalty, late_penalty = params
                planes.append(Airplane(idx, arrival_time, earliest_time, target_time, latest_time, separation_times, early_penalty, late_penalty))
            log("\n\nDATASET {}: num_planes {} freeze_time {} items_read {}".format(dataset["name"], num_planes, freeze_time, len(planes)))
        planes = sorted(planes, key=attrgetter('arrival_time', 'earliest_time', 'latest_time'))
        for idx, p in enumerate(planes):
            log((p.plane_id, p.arrival_time, p.earliest_time, p.target_time, p.latest_time))
        log("  Iteration", end=" ")
        # Perform 30 independent iterations.
        for iteration in range(30):
            log(iteration+1, end=" ")
            thing = TabuSearch(copy.deepcopy(planes))

            initial_fitness = thing.fitness
            start_time = datetime.now()
            total_iterations, stagnation, combination = thing.run()
            execution_time = datetime.now() - start_time

            # Record the relevant data for analysis
            summary = {
                "execution_time": str(execution_time),
                "initial_fitness": initial_fitness,
                "fitness": thing.fitness,
                "iterations": total_iterations,
                "stagnation": stagnation,
                "combination": combination,
                "landing_times": ["{}: {}".format(p.plane_id, p.landing_time) for p in thing.planes],
コード例 #13
0
    # Parse parameters

    with open(instance, 'r') as file:
        data = file.read().splitlines()
        num_items, capacity, items = int(data[0]), int(data[1]), data[2:]
    items = [Item(size=int(i)) for i in items]

    while cand_params:
        # Get and remove first and second elements.
        strr = cand_params.pop(0)
        strr = strr.split("=", 1)
        param = strr[0]
        value = strr[1]
        if param == "--MAX_COMBINATION_LENGTH":
            MAX_COMBINATION_LENGTH = int(value)
        if param == "--MAX_ITERATIONS":
            MAX_ITERATIONS = int(value)
        if param == "--MAX_NO_CHANGE":
            MAX_NO_CHANGE = int(value)

    shuffle(items)
    thing = TabuSearch(capacity, items, MAX_COMBINATION_LENGTH, MAX_ITERATIONS,
                       MAX_NO_CHANGE)

    start_time = datetime.now()
    total_iterations, stagnation, combination = thing.run()
    execution_time = datetime.now() - start_time

    print(str(len(thing.bins)) + "\n")  # retourner le cost vers Irace

    sys.exit(0)
コード例 #14
0
ファイル: test.py プロジェクト: powerllamas/MiOIB
class TestTabuSearch(unittest.TestCase):

    def setUp(self):
        self.flow = [
                [0, 1, 2],
                [4, 0, 5],
                [7, 2, 0]]
        self.distance = [
                [0, 5, 2],
                [1, 0, 1],
                [6, 2, 0]]
        self.i = Instance(None, self.distance, self.flow)
        self.e = E(self.i)
        self.ts = TabuSearch()
        self.startpoint = Solution((0, 1, 2))

    def test_filter_moves(self):
        moves = [(1, 2),
                (1, 3),
                (2, 3)]
        tabu = defaultdict(int, {(1, 2): 1, (2, 3): 1})
        expected = [(1, 3)]
        actual = list(self.ts._get_filtered_moves(moves, tabu=tabu))
        self.assertEqual(expected, actual)

    def test_filter_moves_with_aspiration(self):
        self.i = Instance(None, self.distance, self.flow)
        self.e = E(self.i)
        self.startpoint = Solution((2, 1, 0))

        moves = [(0, 1),
                (0, 2),
                (1, 2)]
        tabu = defaultdict(int, {(0, 1): 1, (1, 2): 2, (0, 2): 3})
        expected = [(0, 1),
                (0, 2),
                (1, 2)]
        actual = list(self.ts._get_filtered_moves(moves, e=self.e,
            current=(self.startpoint, self.e.evaluate(self.startpoint)),
            tabu=tabu))
        self.assertEqual(expected, actual)

    def test_decrease_tabu_penalty(self):
        tabu = defaultdict(int, {(1, 2): 2, (2, 3): 1})
        expected = [(1, 2)]
        self.ts._decrease_tabu_penalty(tabu)
        actual = tabu.keys()
        self.assertEqual(expected, actual)

    def test_select_best_move(self):
        current = self.startpoint
        moves = [(0, 1),
                (0, 2),
                (1, 2)]
        expected = (0, 2)
        actual = self.ts._select_best_move(current, moves, self.e)
        self.assertEqual(expected, actual)

    def test_select_best_moves(self):
        current = self.startpoint
        moves = [(0, 1),
                (0, 2),
                (1, 2)]
        expected = [(0, 2),
                (1, 2)]
        actual = self.ts._select_best_moves(current, moves, self.e, 2)
        self.assertEqual(expected, actual)

    def test_with_startpoint(self):
        expected = (2, 1, 0)
        actual = self.ts.solve(self.i, self.startpoint).sequence
        self.assertEqual(expected, actual)