-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenetic_algorithm.py
More file actions
374 lines (231 loc) · 9.18 KB
/
genetic_algorithm.py
File metadata and controls
374 lines (231 loc) · 9.18 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
from termcolor import colored
import random
import math
######################################################################################
# #
# CONSTANT VARIABLES THAT WILL BE USED AND WON'T CHANGE WHILE THE PROGRAM IS RUNNING #
# #
# 1. MAX WEIGHT OF THE BACKPACK #
# 2. MAX NUMBER OF GENERATIONS #
# 3. POPULATION SIZE #
######################################################################################
MAX_WEIGHT = 250
MAX_GENERATION = 50
POPULATION_SIZE = 20
#######################################################################
# #
# CLASS THAT REPRESENTS A BOX #
# #
#######################################################################
class Box():
def __init__(self, weight, value, status):
self.weight = weight
self.value = value
self.status = status
#############################################################################
# #
# FUNCTIONS TO IMPLEMENT THE ALGORITHM #
# #
#############################################################################
'''
Parameters: chromosome: list of boxes
'''
def mutation(chromosome):
# randomly select a box to change its status
index = random.randint(0, len(chromosome) - 1)
if chromosome[index].status == 0:
chromosome[index].status = 1
else:
chromosome[index].status = 0
return chromosome
'''
Parameters:
population : list of chromosomes
Returns:
shorter population which is 1/2 of original list
'''
def select_fittest(population):
# sort the population in ascending order based on fitness
population = sorted(population, key=lambda x: fitness(x), reverse=True)
length = len(population)
# remove half of population with lowest fitness
for i in range(length // 2):
population.pop()
# return updated population
return population
'''
Parameters:
2 chromosomes to crossover
Returns:
a new chromsome
'''
def crossover(parent_1, parent_2):
# randomly select a pivot to crossover from
pivot = random.randint(1,len(parent_1) - 1)
new_chromosome = list()
# get the first part of the new_chromosome from parent_1
for i in range(pivot):
new_chromosome.append(parent_1[i])
# second part will come from parent_2
for i in range(pivot, len(parent_1)):
new_chromosome.append(parent_2[i])
# return the new generated chromosome: list of boxes that can possibly be a solution
return new_chromosome
'''
Parameters:
1. chromosome: list of boxes
2. max_weight: int representing maximum limit of container
Returns: it returns positive value representing fitness of the chromosome
otherwise it returns 0 if weight is greater than max_weight.
Formula : fitness of a chromosome if the sum of v_i * status_i
'''
def fitness(chromosome):
sum_weights = 0
sum_values = 0
for box in chromosome:
sum_weights += box.status * box.weight
sum_values += box.status * box.value
if sum_weights > MAX_WEIGHT:
# the chromosome is oversized, thus cannot be a solution
return 0
else:
# valid size which is below the maximum capacity of the holder
return sum_values
'''
Parameters:
1. Population
2. int value representing which generation we are currently processing
3. filename to write result to
Does : writes generation information on a file provided
'''
def pretty_print(population, generation, filename):
filename.write("Generation #" + str(generation) + "\n")
filename.write("[ \n")
for item in population:
filename.write("[")
count = 0
for index in item:
if count < len(item) - 1:
filename.write(str(index.status) + ", ")
else:
filename.write(str(index.status))
count += 1
filename.write("] \n")
filename.write("] \n")
'''
Parameters:
individual : a chromosome or list of boxes
Does : prints the results in a preferred format on the terminal
'''
def print_solution(individual):
print(colored("FINAL SOLUTION", "blue"))
print(colored("Boxes to pack identified by index (1 -> n)", "blue"))
print(colored("NUMBER WEIGHT VALUE", "blue"))
print(colored("==========================", "blue"))
index = 0
total_weight = 0
for item in individual:
if item.status == 1:
print(colored(" {} ".format(index + 1),"blue"), end = " ")
print(colored(" {} ".format(item.weight), "blue"), end= " ")
print(colored(" {}".format(item.value), "blue"))
total_weight += item.weight
index += 1
print(colored("Fitness is {}".format(fitness(individual)), "blue"))
print(colored("Total Weight is {}".format(total_weight), "blue"))
'''
Parameters:
Population which is half size of original population
Returns: Population of same size as original which is generated using crossover
operation
'''
def next_generation(population):
length = len(population) - 1
for i in range (POPULATION_SIZE // 2):
parent_1 = population[random.randint(0, length)]
parent_2 = population[random.randint(0, length)]
new_chromosome = crossover(parent_1, parent_2)
# probability whether child should be mutated or not
mutate = random.randint(0,3)
if mutate == 1:
new_chromosome = mutation(new_chromosome)
population.append(new_chromosome)
return population
'''
Parameters:
Population to be processed
Returns: nothing
Does : Implements genetic algorithm
'''
def genetic_algorithm(population):
filename = open("generations.txt", "w+")
for g in range(MAX_GENERATION):
pretty_print(population, g + 1,filename)
# select the fittest from a population will return 1/2 of original population
population = select_fittest(population)
# create next generation using crossover to fill the next 1/2 of population
population = next_generation(population)
solution = sorted(population, key=lambda x: fitness(x), reverse=True)[0]
# in case there is no solution
if fitness(solution) == 0:
print(colored("Sorry! NO SOLUTION FOUND","red"))
return
print_solution(solution)
filename.close()
'''
Parameters:
boxes: list of box objects
Returns : a population: list of chromosomes
'''
def init_population(boxes):
population = []
# initializes population
# each chromosome is a list of length num_boxes with each element assigned to status of 0 or 1
for i in range (POPULATION_SIZE):
chromosome = []
for j in range (len(boxes)):
value = boxes[j].value
weight = boxes[j].weight
chromosome.append(Box(weight, value, random.randint(0,1)))
population.append(chromosome)
return population
'''
Parameters: None
Does : it is used when user wants to provide box values instead of
using randomly generated values
'''
def provided():
num_boxes = int(input(colored("how many boxes do you want to pack? ", "green")))
set_boxes = []
# read in box info from the terminal
for i in range(num_boxes):
data = input(colored ("Enter the size of the box and value separated by a space: ", "green")).split()
box = Box(int(data[0]), int(data[1]), 0)
set_boxes.append(box)
# generate initial population
population = init_population(set_boxes)
# implement the algorithm provided the generated population
genetic_algorithm(population)
'''
Parameters: None
Does : is used when user chooses the program to randomly generate box information
'''
def randomised():
num_boxes = random.randint(3, 10) #number of boxes we want to pack
set_boxes = []
# generate boxes with their corresponidng weight and value
for i in range(num_boxes):
box = Box(random.randint(30, 100), random.randint(1,250), 0)
set_boxes.append(box)
# generate initial population
population = init_population(set_boxes)
#implement the algorithm
genetic_algorithm(population)
if __name__ == "__main__":
choice = input(colored("Do you want to provide boxes and values? (y/n): ","green"))
if choice.upper() == "Y":
provided()
elif choice.upper() == "N":
randomised()
else:
print(colored("Error: Invalid input {}".format(choice),"red"))