forked from ahmedfgad/GeneticAlgorithmPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrossover.py
More file actions
282 lines (240 loc) · 15.1 KB
/
crossover.py
File metadata and controls
282 lines (240 loc) · 15.1 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
"""
The pygad.utils.crossover module has all the built-in crossover operators.
"""
import numpy
import random
class Crossover:
def __init__():
pass
def single_point_crossover(self, parents, offspring_size):
"""
Applies single-point crossover between pairs of parents.
This function selects a random point at which crossover occurs between the parents, generating offspring.
Parameters:
parents (array-like): The parents to mate for producing the offspring.
offspring_size (int): The number of offspring to produce.
Returns:
array-like: An array containing the produced offspring.
"""
if self.gene_type_single == True:
offspring = numpy.empty(offspring_size, dtype=self.gene_type[0])
else:
offspring = numpy.empty(offspring_size, dtype=object)
# Randomly generate all the K points at which crossover takes place between each two parents. The point does not have to be always at the center of the solutions.
# This saves time by calling the numpy.random.randint() function only once.
crossover_points = numpy.random.randint(low=0,
high=parents.shape[1],
size=offspring_size[0])
for k in range(offspring_size[0]):
# Check if the crossover_probability parameter is used.
if not (self.crossover_probability is None):
probs = numpy.random.random(size=parents.shape[0])
indices = list(set(numpy.where(probs <= self.crossover_probability)[0]))
# If no parent satisfied the probability, no crossover is applied and a parent is selected as is.
if len(indices) == 0:
offspring[k, :] = parents[k % parents.shape[0], :]
continue
elif len(indices) == 1:
parent1_idx = indices[0]
parent2_idx = parent1_idx
else:
indices = random.sample(indices, 2)
parent1_idx = indices[0]
parent2_idx = indices[1]
else:
# Index of the first parent to mate.
parent1_idx = k % parents.shape[0]
# Index of the second parent to mate.
parent2_idx = (k+1) % parents.shape[0]
# The new offspring has its first half of its genes from the first parent.
offspring[k, 0:crossover_points[k]] = parents[parent1_idx, 0:crossover_points[k]]
# The new offspring has its second half of its genes from the second parent.
offspring[k, crossover_points[k]:] = parents[parent2_idx, crossover_points[k]:]
if self.allow_duplicate_genes == False:
if self.gene_space is None:
offspring[k], _, _ = self.solve_duplicate_genes_randomly(solution=offspring[k],
min_val=self.random_mutation_min_val,
max_val=self.random_mutation_max_val,
mutation_by_replacement=self.mutation_by_replacement,
gene_type=self.gene_type,
num_trials=10)
else:
offspring[k], _, _ = self.solve_duplicate_genes_by_space(solution=offspring[k],
gene_type=self.gene_type,
num_trials=10)
return offspring
def two_points_crossover(self, parents, offspring_size):
"""
Applies the 2 points crossover. It selects the 2 points randomly at which crossover takes place between the pairs of parents.
It accepts 2 parameters:
-parents: The parents to mate for producing the offspring.
-offspring_size: The size of the offspring to produce.
It returns an array the produced offspring.
"""
if self.gene_type_single == True:
offspring = numpy.empty(offspring_size, dtype=self.gene_type[0])
else:
offspring = numpy.empty(offspring_size, dtype=object)
# Randomly generate all the first K points at which crossover takes place between each two parents.
# This saves time by calling the numpy.random.randint() function only once.
if (parents.shape[1] == 1): # If the chromosome has only a single gene. In this case, this gene is copied from the second parent.
crossover_points_1 = numpy.zeros(offspring_size[0])
else:
crossover_points_1 = numpy.random.randint(low=0,
high=numpy.ceil(parents.shape[1]/2 + 1),
size=offspring_size[0])
# The second point must always be greater than the first point.
crossover_points_2 = crossover_points_1 + int(parents.shape[1]/2)
for k in range(offspring_size[0]):
if not (self.crossover_probability is None):
probs = numpy.random.random(size=parents.shape[0])
indices = list(set(numpy.where(probs <= self.crossover_probability)[0]))
# If no parent satisfied the probability, no crossover is applied and a parent is selected.
if len(indices) == 0:
offspring[k, :] = parents[k % parents.shape[0], :]
continue
elif len(indices) == 1:
parent1_idx = indices[0]
parent2_idx = parent1_idx
else:
indices = random.sample(indices, 2)
parent1_idx = indices[0]
parent2_idx = indices[1]
else:
# Index of the first parent to mate.
parent1_idx = k % parents.shape[0]
# Index of the second parent to mate.
parent2_idx = (k+1) % parents.shape[0]
# The genes from the beginning of the chromosome up to the first point are copied from the first parent.
offspring[k, 0:crossover_points_1[k]] = parents[parent1_idx, 0:crossover_points_1[k]]
# The genes from the second point up to the end of the chromosome are copied from the first parent.
offspring[k, crossover_points_2[k]:] = parents[parent1_idx, crossover_points_2[k]:]
# The genes between the 2 points are copied from the second parent.
offspring[k, crossover_points_1[k]:crossover_points_2[k]] = parents[parent2_idx, crossover_points_1[k]:crossover_points_2[k]]
if self.allow_duplicate_genes == False:
if self.gene_space is None:
offspring[k], _, _ = self.solve_duplicate_genes_randomly(solution=offspring[k],
min_val=self.random_mutation_min_val,
max_val=self.random_mutation_max_val,
mutation_by_replacement=self.mutation_by_replacement,
gene_type=self.gene_type,
num_trials=10)
else:
offspring[k], _, _ = self.solve_duplicate_genes_by_space(solution=offspring[k],
gene_type=self.gene_type,
num_trials=10)
return offspring
def uniform_crossover(self, parents, offspring_size):
"""
Applies the uniform crossover. For each gene, a parent out of the 2 mating parents is selected randomly and the gene is copied from it.
It accepts 2 parameters:
-parents: The parents to mate for producing the offspring.
-offspring_size: The size of the offspring to produce.
It returns an array the produced offspring.
"""
if self.gene_type_single == True:
offspring = numpy.empty(offspring_size, dtype=self.gene_type[0])
else:
offspring = numpy.empty(offspring_size, dtype=object)
# Randomly generate all the genes sources at which crossover takes place between each two parents.
# This saves time by calling the numpy.random.randint() function only once.
# There is a list of 0 and 1 for each offspring.
# [0, 1, 0, 0, 1, 1]: If the value is 0, then take the gene from the first parent. If 1, take it from the second parent.
genes_sources = numpy.random.randint(low=0,
high=2,
size=offspring_size)
for k in range(offspring_size[0]):
if not (self.crossover_probability is None):
probs = numpy.random.random(size=parents.shape[0])
indices = list(set(numpy.where(probs <= self.crossover_probability)[0]))
# If no parent satisfied the probability, no crossover is applied and a parent is selected.
if len(indices) == 0:
offspring[k, :] = parents[k % parents.shape[0], :]
continue
elif len(indices) == 1:
parent1_idx = indices[0]
parent2_idx = parent1_idx
else:
indices = random.sample(indices, 2)
parent1_idx = indices[0]
parent2_idx = indices[1]
else:
# Index of the first parent to mate.
parent1_idx = k % parents.shape[0]
# Index of the second parent to mate.
parent2_idx = (k+1) % parents.shape[0]
for gene_idx in range(offspring_size[1]):
if (genes_sources[k, gene_idx] == 0):
# The gene will be copied from the first parent if the current gene index is 0.
offspring[k, gene_idx] = parents[parent1_idx, gene_idx]
elif (genes_sources[k, gene_idx] == 1):
# The gene will be copied from the second parent if the current gene index is 1.
offspring[k, gene_idx] = parents[parent2_idx, gene_idx]
if self.allow_duplicate_genes == False:
if self.gene_space is None:
offspring[k], _, _ = self.solve_duplicate_genes_randomly(solution=offspring[k],
min_val=self.random_mutation_min_val,
max_val=self.random_mutation_max_val,
mutation_by_replacement=self.mutation_by_replacement,
gene_type=self.gene_type,
num_trials=10)
else:
offspring[k], _, _ = self.solve_duplicate_genes_by_space(solution=offspring[k],
gene_type=self.gene_type,
num_trials=10)
return offspring
def scattered_crossover(self, parents, offspring_size):
"""
Applies the scattered crossover. It randomly selects the gene from one of the 2 parents.
It accepts 2 parameters:
-parents: The parents to mate for producing the offspring.
-offspring_size: The size of the offspring to produce.
It returns an array the produced offspring.
"""
if self.gene_type_single == True:
offspring = numpy.empty(offspring_size, dtype=self.gene_type[0])
else:
offspring = numpy.empty(offspring_size, dtype=object)
# Randomly generate all the genes sources at which crossover takes place between each two parents.
# This saves time by calling the numpy.random.randint() function only once.
# There is a list of 0 and 1 for each offspring.
# [0, 1, 0, 0, 1, 1]: If the value is 0, then take the gene from the first parent. If 1, take it from the second parent.
genes_sources = numpy.random.randint(low=0,
high=2,
size=offspring_size)
for k in range(offspring_size[0]):
if not (self.crossover_probability is None):
probs = numpy.random.random(size=parents.shape[0])
indices = list(set(numpy.where(probs <= self.crossover_probability)[0]))
# If no parent satisfied the probability, no crossover is applied and a parent is selected.
if len(indices) == 0:
offspring[k, :] = parents[k % parents.shape[0], :]
continue
elif len(indices) == 1:
parent1_idx = indices[0]
parent2_idx = parent1_idx
else:
indices = random.sample(indices, 2)
parent1_idx = indices[0]
parent2_idx = indices[1]
else:
# Index of the first parent to mate.
parent1_idx = k % parents.shape[0]
# Index of the second parent to mate.
parent2_idx = (k+1) % parents.shape[0]
offspring[k, :] = numpy.where(genes_sources[k] == 0,
parents[parent1_idx, :],
parents[parent2_idx, :])
if self.allow_duplicate_genes == False:
if self.gene_space is None:
offspring[k], _, _ = self.solve_duplicate_genes_randomly(solution=offspring[k],
min_val=self.random_mutation_min_val,
max_val=self.random_mutation_max_val,
mutation_by_replacement=self.mutation_by_replacement,
gene_type=self.gene_type,
num_trials=10)
else:
offspring[k], _, _ = self.solve_duplicate_genes_by_space(solution=offspring[k],
gene_type=self.gene_type,
num_trials=10)
return offspring