-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbpp_code.py
192 lines (140 loc) · 8.15 KB
/
bpp_code.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# -*- coding: utf-8 -*-
"""BPP_CODE.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1yfW20mZoXc26chgKDc2Zz4CJtKF5jZ53
"""
import random
import matplotlib.pyplot as plt
# Constants
POPULATION_SIZE = 10
MAX_EVALUATIONS = 10000
def generate_random_solution(num_items, num_bins):
return [random.randint(1, num_bins) for _ in range(num_items)]
def evaluate_fitness(solution, item_weights, num_bins):
bin_weights = [0] * num_bins
for i in range(len(solution)):
bin_weights[solution[i] - 1] += item_weights[i]
return max(bin_weights) - min(bin_weights)
def binary_tournament_selection(population, item_weights, num_bins):
parent_a = random.choice(population)
parent_b = random.choice(population)
return parent_a if evaluate_fitness(parent_a, item_weights, num_bins) < evaluate_fitness(parent_b, item_weights, num_bins) else parent_b
def single_point_crossover(parent_a, parent_b):
crossover_point = random.randint(1, len(parent_a) - 1)
child_c = parent_a[:crossover_point] + parent_b[crossover_point:]
child_d = parent_b[:crossover_point] + parent_a[crossover_point:]
return child_c, child_d
def multi_gene_mutation(solution, num_bins, num_mutations):
for _ in range(num_mutations):
gene_index = random.randint(0, len(solution) - 1)
solution[gene_index] = random.randint(1, num_bins)
def weakest_replacement(new_solution, population, item_weights, num_bins):
worst_solution = max(population, key=lambda s: evaluate_fitness(s, item_weights, num_bins))
if evaluate_fitness(new_solution, item_weights, num_bins) < evaluate_fitness(worst_solution, item_weights, num_bins):
population.remove(worst_solution)
population.append(new_solution)
def evolutionary_algorithm(num_items, num_bins, item_weights, crossover_operator, mutation_operator, population_size):
population = []
for _ in range(population_size):
solution = generate_random_solution(num_items, num_bins)
population.append(solution)
evaluations = population_size
best_fitness = float('inf')
best_solution = None
while evaluations < MAX_EVALUATIONS:
parent_a = binary_tournament_selection(population, item_weights, num_bins)
parent_b = binary_tournament_selection(population, item_weights, num_bins)
child_c, child_d = crossover_operator(parent_a, parent_b)
mutation_operator(child_c, num_bins, 1)
mutation_operator(child_d, num_bins, 1)
weakest_replacement(child_c, population, item_weights, num_bins)
weakest_replacement(child_d, population, item_weights, num_bins)
evaluations += 2
# Update best fitness and solution
current_fitness = evaluate_fitness(population[0], item_weights, num_bins)
if current_fitness < best_fitness:
best_fitness = current_fitness
best_solution = population[0]
return best_solution, best_fitness
def analyze_experiment(experiment_name, best_fitness_list):
best_fitness_exp6 = []
print(f"Experiment: {experiment_name}")
print("===============================================")
print("Best Fitness for Each Trial:")
for i, fitness in enumerate(best_fitness_list):
print(f"Trial {i+1}: {fitness}")
best_fitness_exp6.append(fitness)
print("===============================================")
experiment_labels = ['Trail 1', 'Trail 2', 'Trail 3', 'Trail 4', 'Trail 5', 'Trail 6']
plt.figure(figsize=(10, 6))
plt.bar(experiment_labels[:5], best_fitness_exp6, color='blue')
plt.title('Best Fitness - Experiment 1')
plt.xlabel('Experiment')
plt.ylabel('Fitness')
plt.show()
if __name__ == "__main__":
item_weights_bpp1 = [2 * i for i in range(1, 501)]
item_weights_bpp2 = [i**2 for i in range(1, 501)]
num_bins_bpp1 = 20
num_bins_bpp2 = 100
# Experiment 1: Run five trials of the EA with crossover & operator M1 and population size 10.
best_fitness_exp1 = []
for _ in range(5):
best_solution, best_fitness = evolutionary_algorithm(num_items=500, num_bins=num_bins_bpp1,
item_weights=item_weights_bpp1,
crossover_operator=single_point_crossover,
mutation_operator=multi_gene_mutation,
population_size=10)
best_fitness_exp1.append(best_fitness)
analyze_experiment("Experiment 1", best_fitness_exp1)
# Experiment 2: Run five trials of the EA with crossover & operator M1 and population size 100.
best_fitness_exp2 = []
for _ in range(5):
best_solution, best_fitness = evolutionary_algorithm(num_items=500, num_bins=num_bins_bpp1,
item_weights=item_weights_bpp1,
crossover_operator=single_point_crossover,
mutation_operator=multi_gene_mutation,
population_size=100)
best_fitness_exp2.append(best_fitness)
analyze_experiment("Experiment 2", best_fitness_exp2)
# Experiment 3: Run five trials of the EA with crossover & operator M5 and population size 10.
best_fitness_exp3 = []
for _ in range(5):
best_solution, best_fitness = evolutionary_algorithm(num_items=500, num_bins=num_bins_bpp1,
item_weights=item_weights_bpp1,
crossover_operator=single_point_crossover,
mutation_operator=multi_gene_mutation,
population_size=10)
best_fitness_exp3.append(best_fitness)
analyze_experiment("Experiment 3", best_fitness_exp3)
# Experiment 4: Run five trials of the EA with crossover & operator M5 and population size 100.
best_fitness_exp4 = []
for _ in range(5):
best_solution, best_fitness = evolutionary_algorithm(num_items=500, num_bins=num_bins_bpp1,
item_weights=item_weights_bpp1,
crossover_operator=single_point_crossover,
mutation_operator=multi_gene_mutation,
population_size=100)
best_fitness_exp4.append(best_fitness)
analyze_experiment("Experiment 4", best_fitness_exp4)
# Experiment 5: Run five trials of the EA with only operator M5 and population size 10.
best_fitness_exp5 = []
for _ in range(5):
best_solution, best_fitness = evolutionary_algorithm(num_items=500, num_bins=num_bins_bpp1,
item_weights=item_weights_bpp1,
crossover_operator=lambda x, y: (x, y),
mutation_operator=multi_gene_mutation,
population_size=10)
best_fitness_exp5.append(best_fitness)
analyze_experiment("Experiment 5", best_fitness_exp5)
# Experiment 6: Run five trials of the EA with only crossover and population size 10.
best_fitness_exp6 = []
for _ in range(5):
best_solution, best_fitness = evolutionary_algorithm(num_items=500, num_bins=num_bins_bpp1,
item_weights=item_weights_bpp1,
crossover_operator=single_point_crossover,
mutation_operator=lambda x, y, z: None,
population_size=10)
best_fitness_exp6.append(best_fitness)
analyze_experiment("Experiment 6", best_fitness_exp6)