Repository navigation
Expand file tree
/
Copy pathcrossover.py
More file actions
366 lines (310 loc) · 16.7 KB
/
Copy pathcrossover.py
File metadata and controls
366 lines (310 loc) · 16.7 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
"""
The pygad.utils.crossover module has all the built-in crossover operators.
"""
import numpy
class Crossover:
def __init__():
pass
def single_point_crossover(self, parents, offspring_size):
"""
Apply single-point crossover between pairs of parents. One
random split point is picked per offspring; the genes before
the point come from the first parent and the genes from the
point onward come from the second parent.
Parameters
----------
parents : numpy.ndarray
A 2D array of parent solutions, one row per parent.
offspring_size : tuple
``(num_offspring, num_genes)``. Shape of the offspring
array to return.
Returns
-------
offspring : numpy.ndarray
A 2D array of the produced offspring with shape
``offspring_size``.
"""
offspring = self.initialize_parents_array(offspring_size)
# 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 self.numpy_random_generator.randint() function only once.
crossover_points = self.numpy_random_generator.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 = self.numpy_random_generator.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 = self.python_random_generator.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 first half of the offspring's genes comes from the first parent.
offspring[k, 0:crossover_points[k]] = parents[parent1_idx, 0:crossover_points[k]]
# The second half of the offspring's genes comes from the second parent.
offspring[k, crossover_points[k]:] = parents[parent2_idx, crossover_points[k]:]
if self.allow_duplicate_genes == False:
offspring[k], _, _ = self.solve_duplicate_genes(solution=offspring[k])
return offspring
def two_points_crossover(self, parents, offspring_size):
"""
Apply two-points crossover. Two split points are picked per
offspring; the genes outside ``[point1, point2)`` come from the
first parent and the genes inside come from the second parent.
Parameters
----------
parents : numpy.ndarray
A 2D array of parent solutions, one row per parent.
offspring_size : tuple
``(num_offspring, num_genes)``. Shape of the offspring
array to return.
Returns
-------
offspring : numpy.ndarray
A 2D array of the produced offspring with shape
``offspring_size``.
"""
offspring = self.initialize_parents_array(offspring_size)
# Randomly generate all the K pairs of points at which crossover takes place between each two parents.
# This saves time by calling the self.numpy_random_generator.randint() function only twice.
# The 2 points of a pair are different values in [0, num_genes], and every such pair is equally likely.
# If the chromosome has only a single gene, the points are 0 and 1: the gene is copied from the second parent.
points_a = self.numpy_random_generator.randint(low=0,
high=parents.shape[1] + 1,
size=offspring_size[0])
points_b = self.numpy_random_generator.randint(low=0,
high=parents.shape[1],
size=offspring_size[0])
# Skip the value of the first point so that the 2 points differ.
points_b[points_b >= points_a] += 1
# The second point must always be greater than the first point.
crossover_points_1 = numpy.minimum(points_a, points_b)
crossover_points_2 = numpy.maximum(points_a, points_b)
for k in range(offspring_size[0]):
if not (self.crossover_probability is None):
probs = self.numpy_random_generator.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 = self.python_random_generator.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:
offspring[k], _, _ = self.solve_duplicate_genes(solution=offspring[k])
return offspring
def uniform_crossover(self, parents, offspring_size):
"""
Apply uniform crossover. For each gene independently, the value
is copied from one of the two mating parents picked at random.
Parameters
----------
parents : numpy.ndarray
A 2D array of parent solutions, one row per parent.
offspring_size : tuple
``(num_offspring, num_genes)``. Shape of the offspring
array to return.
Returns
-------
offspring : numpy.ndarray
A 2D array of the produced offspring with shape
``offspring_size``.
"""
offspring = self.initialize_parents_array(offspring_size)
# Randomly generate all the genes sources at which crossover takes place between each two parents.
# This saves time by calling the self.numpy_random_generator.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 = self.numpy_random_generator.randint(low=0,
high=2,
size=offspring_size)
for k in range(offspring_size[0]):
if not (self.crossover_probability is None):
probs = self.numpy_random_generator.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 = self.python_random_generator.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 gene will be copied from the first parent if the current gene index is 0.
# The gene will be copied from the second parent if the current gene index is 1.
offspring[k, :] = numpy.where(genes_sources[k] == 0,
parents[parent1_idx, :],
parents[parent2_idx, :])
if self.allow_duplicate_genes == False:
offspring[k], _, _ = self.solve_duplicate_genes(solution=offspring[k])
return offspring
def sbx_crossover(self, parents, offspring_size):
"""
Apply Simulated Binary Crossover (SBX). For each gene, the
offspring value is drawn from a distribution centered on the
parents. The spread of this distribution is set by
``self.sbx_crossover_eta`` (a higher value means the child
stays closer to the parents).
The bounded form is used. The per-gene bounds come from
``get_initial_population_range``.
Parameters
----------
parents : numpy.ndarray
A 2D array of parent solutions, one row per parent.
offspring_size : tuple
(num_offspring, num_genes). Shape of the offspring array
to return.
Returns
-------
offspring : numpy.ndarray
A 2D array of offspring with shape offspring_size.
"""
offspring = self.initialize_parents_array(offspring_size)
eta = float(self.sbx_crossover_eta)
near_zero = 1e-14
for k in range(offspring_size[0]):
if not (self.crossover_probability is None):
probs = self.numpy_random_generator.random(size=parents.shape[0])
indices = list(set(numpy.where(probs < self.crossover_probability)[0]))
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 = self.python_random_generator.sample(indices, 2)
parent1_idx = indices[0]
parent2_idx = indices[1]
else:
parent1_idx = k % parents.shape[0]
parent2_idx = (k + 1) % parents.shape[0]
for gene_idx in range(offspring_size[1]):
if self.is_categorical_gene(gene_idx):
# Blending two categories has no meaning, so the child
# takes the value of one parent, each with equal chance.
if self.numpy_random_generator.random() < 0.5:
offspring[k, gene_idx] = parents[parent1_idx, gene_idx]
else:
offspring[k, gene_idx] = parents[parent2_idx, gene_idx]
continue
range_min, range_max = self.get_bounded_operator_gene_range(gene_idx)
lower, upper = float(range_min), float(range_max)
p1 = float(numpy.clip(parents[parent1_idx, gene_idx], lower, upper))
p2 = float(numpy.clip(parents[parent2_idx, gene_idx], lower, upper))
y1 = min(p1, p2)
y2 = max(p1, p2)
if y2 - y1 < near_zero:
# The two parents have the same value on this gene.
offspring[k, gene_idx] = self.convert_bounded_operator_gene_value(gene_idx, p1)
continue
# Beta is the spread factor that controls how far the
# child can move away from the parents.
beta = 1.0 + 2.0 * min(y1 - lower, upper - y2) / (y2 - y1)
alpha = 2.0 - pow(beta, -(eta + 1.0))
rand_u = self.numpy_random_generator.random()
if rand_u <= 1.0 / alpha:
beta_q = pow(rand_u * alpha, 1.0 / (eta + 1.0))
else:
beta_q = pow(1.0 / (2.0 - rand_u * alpha), 1.0 / (eta + 1.0))
# SBX makes 2 children, symmetric around the parents' mean.
# Pick one of them at random so that the child is not always below the mean.
if self.numpy_random_generator.random() < 0.5:
child = 0.5 * ((y1 + y2) - beta_q * (y2 - y1))
else:
child = 0.5 * ((y1 + y2) + beta_q * (y2 - y1))
child = numpy.clip(child, lower, upper)
offspring[k, gene_idx] = self.convert_bounded_operator_gene_value(gene_idx, child)
offspring[k] = self.prepare_bounded_operator_solution(parents[parent1_idx], offspring[k])
return offspring
def scattered_crossover(self, parents, offspring_size):
"""
Apply scattered crossover. For each gene independently, the
value is copied from one of the two mating parents picked at
random. (Same mechanic as ``uniform_crossover`` but kept as a
separate operator for backwards compatibility.)
Parameters
----------
parents : numpy.ndarray
A 2D array of parent solutions, one row per parent.
offspring_size : tuple
``(num_offspring, num_genes)``. Shape of the offspring
array to return.
Returns
-------
offspring : numpy.ndarray
A 2D array of the produced offspring with shape
``offspring_size``.
"""
offspring = self.initialize_parents_array(offspring_size)
# Randomly generate all the genes sources at which crossover takes place between each two parents.
# This saves time by calling the self.numpy_random_generator.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 = self.numpy_random_generator.randint(low=0,
high=2,
size=offspring_size)
for k in range(offspring_size[0]):
if not (self.crossover_probability is None):
probs = self.numpy_random_generator.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 = self.python_random_generator.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 gene will be copied from the first parent if the current gene index is 0.
# The gene will be copied from the second parent if the current gene index is 1.
offspring[k, :] = numpy.where(genes_sources[k] == 0,
parents[parent1_idx, :],
parents[parent2_idx, :])
if self.allow_duplicate_genes == False:
offspring[k], _, _ = self.solve_duplicate_genes(solution=offspring[k])
return offspring