-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgenetic_algorithm.py
More file actions
289 lines (241 loc) · 9.43 KB
/
genetic_algorithm.py
File metadata and controls
289 lines (241 loc) · 9.43 KB
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
Item = namedtuple("Item", ['id', 'size'])
Candidate = namedtuple("Candidate", ['items', 'fitness'])
#------------BIN-------------
def cost(bins):
return len(bins)
class Bin(object):
count = itertools.count()
def __init__(self, capacity):
self.id = next(Bin.count)
self.capacity = capacity
self.free_space = capacity
self.items = []
self.used_space = 0
def add_item(self, item):
self.items.append(item)
self.free_space -= item.size
self.used_space += item.size
def remove_item(self, item_index):
item_to_remove = self.items[item_index]
del self.items[item_index]
self.free_space += item_to_remove.size
self.used_space -= item_to_remove.size
def fits(self, item):
return self.free_space >= item.size
def __str__(self):
items = [str(it) for it in self.items]
items_string = '[' + ' '.join(items) + ']'
return "Bin n° " + str(self.id) + " containing the " + \
str(len(self.items)) + " following items : " + items_string + \
" with " + str(self.free_space) + " free space."
def __copy__(self):
new_bin = Bin(self.capacity)
new_bin.free_space = self.free_space
new_bin.used_space = self.used_space
new_bin.items = self.items[:]
return new_bin
#-----------GA HEUR-----------
def nextfit(items, current_bins, capacity):
bins = [copy.copy(b) for b in current_bins]
if not bins:
bin = Bin(capacity)
bins.append(bin)
for item in items:
if item.size > capacity:
continue
if bin.fits(item):
bin.add_item(item)
else:
bin = Bin(capacity)
bin.add_item(item)
bins.append(bin)
return bins
def bestfit(items, current_bins, capacity):
bins = [copy.copy(b) for b in current_bins]
if not bins:
bins = [Bin(capacity)]
for item in items:
if item.size > capacity:
continue
possible_bins = [bin for bin in bins if bin.fits(item)]
if not possible_bins:
bin = Bin(capacity)
bin.add_item(item)
bins.append(bin)
else:
index, free_space = min(enumerate(possible_bins), key=lambda it: it[1].free_space)
possible_bins[index].add_item(item)
return bins
def firstfit(items, current_bins, capacity):
bins = [copy.copy(b) for b in current_bins]
if not bins:
bins = [Bin(capacity)]
for item in items:
if item.size > capacity:
continue
first_bin = next((bin for bin in bins if bin.free_space >= item.size), None)
if first_bin is None:
bin = Bin(capacity)
bin.add_item(item)
bins.append(bin)
else:
first_bin.add_item(item)
return bins
def worstfit(items, current_bins, capacity):
bins = [copy.copy(b) for b in current_bins]
if not bins:
bins = [Bin(capacity)]
for item in items:
if item.size > capacity:
continue
possible_bins = [bin for bin in bins if bin.fits(item)]
if not possible_bins:
bin = Bin(capacity)
bin.add_item(item)
bins.append(bin)
else:
index, free_space = max(enumerate(possible_bins), key=lambda it: it[1].free_space)
possible_bins[index].add_item(item)
return bins
#-----------GA------------
def population_generator(items, capacity, population_size, greedy_solver):
candidate = Candidate(items[:], fitness(items, capacity, greedy_solver))
population = [candidate]
new_items = items[:]
for i in range(population_size - 1):
shuffle(new_items)
candidate = Candidate(new_items[:], fitness(new_items, capacity, greedy_solver))
if candidate not in population:
population.append(candidate)
return population
def fitness(candidate, capacity, greedy_solver):
if greedy_solver == 'FF':
return firstfit(candidate,[], capacity)
elif greedy_solver == 'BF':
return bestfit(candidate,[], capacity)
return nextfit(candidate,[], capacity)
def tournament_selection(population, tournament_selection_probability, k):
candidates = [population[(randint(0, len(population) - 1))]]
while len(candidates) < k:
new_indiv = population[(randint(0, len(population) - 1))]
if new_indiv not in candidates:
candidates.append(new_indiv)
ind = int(np.random.geometric(tournament_selection_probability, 1))
while ind >= k:
ind = int(np.random.geometric(tournament_selection_probability, 1))
return candidates[ind]
def crossover(parent1, parent2):
taken = [False] * len(parent1)
child = []
i = 0
while i < len(parent1):
element = parent1[i]
if not taken[element.id]:
child.append(element)
taken[element.id] = True
element = parent2[i]
if not taken[element.id]:
child.append(element)
taken[element.id] = True
i += 1
return child
def roulette_wheel_selection(population):
max = sum([len(e.fitness) for e in population])
pick = uniform(0, max)
current = max
for item in population:
current -= len(item.fitness)
if current < pick:
return item
def SUS(population, n):
selected = []
pointers = []
max = sum([len(e.fitness) for e in population])
distance = max / n
start = uniform(0, distance)
for i in range(n):
pointers.append(start + i * distance)
for pointer in pointers:
current = 0
for item in population:
current += len(item.fitness)
if current > pointer:
selected.append(item)
return selected
def rank_selection(population):
length = len(population)
rank_sum = length * (length + 1) / 2
pick = uniform(0, rank_sum)
current = 0
i = length
for item in population:
current += i
if current > pick:
return item
i -= 1
def mutation(member, capacity, greedy_solver):
member_items = member.items
a = randint(0, len(member_items) - 1)
b = randint(0, len(member_items) - 1)
while a == b:
b = randint(0, len(member_items) - 1)
c = member_items[a]
member_items[a] = member_items[b]
member_items[b] = c
member = Candidate(member_items, fitness(member_items, capacity, greedy_solver))
return member
def genetic_algorithm(weights, capacity, population_size, generations, k, tournament_selection_probability, crossover_probability, mutation_probability, greedy_solver, allow_duplicate_parents, selection_method):
items = [Item]
items = [ Item(i,weights[i]) for i in range(len(weights))]
population = population_generator(items, capacity, population_size, greedy_solver)
best_solution = fitness(items, capacity, greedy_solver)
i = 0
while i < generations:
new_generation = []
best_child = best_solution
for j in range(population_size):
if selection_method == 'SUS':
first_parent = SUS(population, 1)[0].items
second_parent = SUS(population, 1)[0].items
if not allow_duplicate_parents:
while first_parent == second_parent:
second_parent = SUS(population, 1)[0].items
elif selection_method == 'TS':
first_parent = tournament_selection(population, tournament_selection_probability, k).items
second_parent = tournament_selection(population, tournament_selection_probability, k).items
if not allow_duplicate_parents:
while first_parent == second_parent:
second_parent = tournament_selection(population, tournament_selection_probability, k).items
elif selection_method == 'RW':
first_parent = roulette_wheel_selection(population).items
second_parent = roulette_wheel_selection(population).items
if not allow_duplicate_parents:
while first_parent == second_parent:
second_parent = roulette_wheel_selection(population).items
elif selection_method == 'RS':
first_parent = rank_selection(population).items
second_parent = rank_selection(population).items
if not allow_duplicate_parents:
while first_parent == second_parent:
second_parent = rank_selection(population).items
else:
return
child = crossover(first_parent, second_parent)
child = Candidate(child[:], fitness(child, capacity, greedy_solver))
prob = random()
if prob <= mutation_probability:
child = mutation(child, capacity, greedy_solver)
if len(child.fitness) < len(best_child):
best_child = child.fitness
new_generation.append(child)
if len(best_child) < len(best_solution):
best_solution = best_child
population = [Candidate(p.items[:], p.fitness) for p in new_generation]
population.sort(key=lambda candidate: len(candidate.fitness), reverse=True)
i += 1
return len(best_solution)
w = [49, 41, 34, 33, 29, 26, 26, 22, 20, 19, 40, 21, 45, 15, 18, 23, 43, 30]
c = 100
n = len(w)
solution = genetic_algorithm(w, c, 50, 50, 2, 0.7, 0.3, 0.4, 'FF',False, 'TS')
#print(solution)