-
Notifications
You must be signed in to change notification settings - Fork 0
/
crossover.py
445 lines (362 loc) · 17.1 KB
/
crossover.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
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
import random
import warnings
from collections import Sequence
from itertools import repeat
######################################
# GA Crossovers #
######################################
def cxOnePoint(ind1, ind2):
"""Executes a one point crossover on the input :term:`sequence` individuals.
The two individuals are modified in place. The resulting individuals will
respectively have the length of the other.
:param ind1: The first individual participating in the crossover.
:param ind2: The second individual participating in the crossover.
:returns: A tuple of two individuals.
This function uses the :func:`~random.randint` function from the
python base :mod:`random` module.
"""
size = min(len(ind1), len(ind2))
cxpoint = random.randint(1, size - 1)
ind1[cxpoint:], ind2[cxpoint:] = ind2[cxpoint:], ind1[cxpoint:]
return ind1, ind2
def cxTwoPoint(ind1, ind2):
"""Executes a two-point crossover on the input :term:`sequence`
individuals. The two individuals are modified in place and both keep
their original length.
:param ind1: The first individual participating in the crossover.
:param ind2: The second individual participating in the crossover.
:returns: A tuple of two individuals.
This function uses the :func:`~random.randint` function from the Python
base :mod:`random` module.
"""
size = min(len(ind1), len(ind2))
cxpoint1 = random.randint(1, size)
cxpoint2 = random.randint(1, size - 1)
if cxpoint2 >= cxpoint1:
cxpoint2 += 1
else: # Swap the two cx points
cxpoint1, cxpoint2 = cxpoint2, cxpoint1
ind1[cxpoint1:cxpoint2], ind2[cxpoint1:cxpoint2] \
= ind2[cxpoint1:cxpoint2], ind1[cxpoint1:cxpoint2]
return ind1, ind2
def cxTwoPoints(ind1, ind2):
"""
.. deprecated:: 1.0
The function has been renamed. Use :func:`~deap.tools.cxTwoPoint` instead.
"""
warnings.warn("tools.cxTwoPoints has been renamed. Use cxTwoPoint instead.",
FutureWarning)
return cxTwoPoint(ind1, ind2)
def cxUniform(ind1, ind2, indpb):
"""Executes a uniform crossover that modify in place the two
:term:`sequence` individuals. The attributes are swapped accordingto the
*indpb* probability.
:param ind1: The first individual participating in the crossover.
:param ind2: The second individual participating in the crossover.
:param indpb: Independent probabily for each attribute to be exchanged.
:returns: A tuple of two individuals.
This function uses the :func:`~random.random` function from the python base
:mod:`random` module.
"""
size = min(len(ind1), len(ind2))
for i in range(size):
if random.random() < indpb:
ind1[i], ind2[i] = ind2[i], ind1[i]
return ind1, ind2
def cxPartialyMatched(ind1, ind2):
"""Executes a partially matched crossover (PMX) on the input individuals.
The two individuals are modified in place. This crossover expects
:term:`sequence` individuals of indices, the result for any other type of
individuals is unpredictable.
:param ind1: The first individual participating in the crossover.
:param ind2: The second individual participating in the crossover.
:returns: A tuple of two individuals.
Moreover, this crossover generates two children by matching
pairs of values in a certain range of the two parents and swapping the values
of those indexes. For more details see [Goldberg1985]_.
This function uses the :func:`~random.randint` function from the python base
:mod:`random` module.
.. [Goldberg1985] Goldberg and Lingel, "Alleles, loci, and the traveling
salesman problem", 1985.
"""
size = min(len(ind1), len(ind2))
p1, p2 = [0]*size, [0]*size
# Initialize the position of each indices in the individuals
for i in range(size):
p1[ind1[i]] = i
p2[ind2[i]] = i
# Choose crossover points
cxpoint1 = random.randint(0, size)
cxpoint2 = random.randint(0, size - 1)
if cxpoint2 >= cxpoint1:
cxpoint2 += 1
else: # Swap the two cx points
cxpoint1, cxpoint2 = cxpoint2, cxpoint1
# Apply crossover between cx points
for i in range(cxpoint1, cxpoint2):
# Keep track of the selected values
temp1 = ind1[i]
temp2 = ind2[i]
# Swap the matched value
ind1[i], ind1[p1[temp2]] = temp2, temp1
ind2[i], ind2[p2[temp1]] = temp1, temp2
# Position bookkeeping
p1[temp1], p1[temp2] = p1[temp2], p1[temp1]
p2[temp1], p2[temp2] = p2[temp2], p2[temp1]
return ind1, ind2
def cxUniformPartialyMatched(ind1, ind2, indpb):
"""Executes a uniform partially matched crossover (UPMX) on the input
individuals. The two individuals are modified in place. This crossover
expects :term:`sequence` individuals of indices, the result for any other
type of individuals is unpredictable.
:param ind1: The first individual participating in the crossover.
:param ind2: The second individual participating in the crossover.
:returns: A tuple of two individuals.
Moreover, this crossover generates two children by matching
pairs of values chosen at random with a probability of *indpb* in the two
parents and swapping the values of those indexes. For more details see
[Cicirello2000]_.
This function uses the :func:`~random.random` and :func:`~random.randint`
functions from the python base :mod:`random` module.
.. [Cicirello2000] Cicirello and Smith, "Modeling GA performance for
control parameter optimization", 2000.
"""
size = min(len(ind1), len(ind2))
p1, p2 = [0]*size, [0]*size
# Initialize the position of each indices in the individuals
for i in range(size):
p1[ind1[i]] = i
p2[ind2[i]] = i
for i in range(size):
if random.random() < indpb:
# Keep track of the selected values
temp1 = ind1[i]
temp2 = ind2[i]
# Swap the matched value
ind1[i], ind1[p1[temp2]] = temp2, temp1
ind2[i], ind2[p2[temp1]] = temp1, temp2
# Position bookkeeping
p1[temp1], p1[temp2] = p1[temp2], p1[temp1]
p2[temp1], p2[temp2] = p2[temp2], p2[temp1]
return ind1, ind2
def cxOrdered(ind1, ind2):
"""Executes an ordered crossover (OX) on the input
individuals. The two individuals are modified in place. This crossover
expects :term:`sequence` individuals of indices, the result for any other
type of individuals is unpredictable.
:param ind1: The first individual participating in the crossover.
:param ind2: The second individual participating in the crossover.
:returns: A tuple of two individuals.
Moreover, this crossover generates holes in the input
individuals. A hole is created when an attribute of an individual is
between the two crossover points of the other individual. Then it rotates
the element so that all holes are between the crossover points and fills
them with the removed elements in order. For more details see
[Goldberg1989]_.
This function uses the :func:`~random.sample` function from the python base
:mod:`random` module.
.. [Goldberg1989] Goldberg. Genetic algorithms in search,
optimization and machine learning. Addison Wesley, 1989
"""
size = min(len(ind1), len(ind2))
a, b = random.sample(range(size), 2)
if a > b:
a, b = b, a
holes1, holes2 = [True]*size, [True]*size
for i in range(size):
if i < a or i > b:
holes1[ind2[i]] = False
holes2[ind1[i]] = False
# We must keep the original values somewhere before scrambling everything
temp1, temp2 = ind1, ind2
k1 , k2 = b + 1, b + 1
for i in range(size):
if not holes1[temp1[(i + b + 1) % size]]:
ind1[k1 % size] = temp1[(i + b + 1) % size]
k1 += 1
if not holes2[temp2[(i + b + 1) % size]]:
ind2[k2 % size] = temp2[(i + b + 1) % size]
k2 += 1
# Swap the content between a and b (included)
for i in range(a, b + 1):
ind1[i], ind2[i] = ind2[i], ind1[i]
return ind1, ind2
def cxBlend(ind1, ind2, alpha):
"""Executes a blend crossover that modify in-place the input individuals.
The blend crossover expects :term:`sequence` individuals of floating point
numbers.
:param ind1: The first individual participating in the crossover.
:param ind2: The second individual participating in the crossover.
:param alpha: Extent of the interval in which the new values can be drawn
for each attribute on both side of the parents' attributes.
:returns: A tuple of two individuals.
This function uses the :func:`~random.random` function from the python base
:mod:`random` module.
"""
for i, (x1, x2) in enumerate(zip(ind1, ind2)):
gamma = (1. + 2. * alpha) * random.random() - alpha
ind1[i] = (1. - gamma) * x1 + gamma * x2
ind2[i] = gamma * x1 + (1. - gamma) * x2
return ind1, ind2
def cxSimulatedBinary(ind1, ind2, eta):
"""Executes a simulated binary crossover that modify in-place the input
individuals. The simulated binary crossover expects :term:`sequence`
individuals of floating point numbers.
:param ind1: The first individual participating in the crossover.
:param ind2: The second individual participating in the crossover.
:param eta: Crowding degree of the crossover. A high eta will produce
children resembling to their parents, while a small eta will
produce solutions much more different.
:returns: A tuple of two individuals.
This function uses the :func:`~random.random` function from the python base
:mod:`random` module.
"""
for i, (x1, x2) in enumerate(zip(ind1, ind2)):
rand = random.random()
if rand <= 0.5:
beta = 2. * rand
else:
beta = 1. / (2. * (1. - rand))
beta **= 1. / (eta + 1.)
ind1[i] = 0.5 * (((1 + beta) * x1) + ((1 - beta) * x2))
ind2[i] = 0.5 * (((1 - beta) * x1) + ((1 + beta) * x2))
return ind1, ind2
def cxSimulatedBinaryBounded(ind1, ind2, eta, low, up):
"""Executes a simulated binary crossover that modify in-place the input
individuals. The simulated binary crossover expects :term:`sequence`
individuals of floating point numbers.
:param ind1: The first individual participating in the crossover.
:param ind2: The second individual participating in the crossover.
:param eta: Crowding degree of the crossover. A high eta will produce
children resembling to their parents, while a small eta will
produce solutions much more different.
:param low: A value or a :term:`python:sequence` of values that is the lower
bound of the search space.
:param up: A value or a :term:`python:sequence` of values that is the upper
bound of the search space.
:returns: A tuple of two individuals.
This function uses the :func:`~random.random` function from the python base
:mod:`random` module.
.. note::
This implementation is similar to the one implemented in the
original NSGA-II C code presented by Deb.
"""
size = min(len(ind1), len(ind2))
if not isinstance(low, Sequence):
low = repeat(low, size)
elif len(low) < size:
raise IndexError("low must be at least the size of the shorter individual: %d < %d" % (len(low), size))
if not isinstance(up, Sequence):
up = repeat(up, size)
elif len(up) < size:
raise IndexError("up must be at least the size of the shorter individual: %d < %d" % (len(up), size))
for i, xl, xu in zip(range(size), low, up):
if random.random() <= 0.5:
# This epsilon should probably be changed for 0 since
# floating point arithmetic in Python is safer
if abs(ind1[i] - ind2[i]) > 1e-14:
x1 = min(ind1[i], ind2[i])
x2 = max(ind1[i], ind2[i])
rand = random.random()
beta = 1.0 + (2.0 * (x1 - xl) / (x2 - x1))
alpha = 2.0 - beta**-(eta + 1)
if rand <= 1.0 / alpha:
beta_q = (rand * alpha)**(1.0 / (eta + 1))
else:
beta_q = (1.0 / (2.0 - rand * alpha))**(1.0 / (eta + 1))
c1 = 0.5 * (x1 + x2 - beta_q * (x2 - x1))
beta = 1.0 + (2.0 * (xu - x2) / (x2 - x1))
alpha = 2.0 - beta**-(eta + 1)
if rand <= 1.0 / alpha:
beta_q = (rand * alpha)**(1.0 / (eta + 1))
else:
beta_q = (1.0 / (2.0 - rand * alpha))**(1.0 / (eta + 1))
c2 = 0.5 * (x1 + x2 + beta_q * (x2 - x1))
c1 = min(max(c1, xl), xu)
c2 = min(max(c2, xl), xu)
if random.random() <= 0.5:
ind1[i] = c2
ind2[i] = c1
else:
ind1[i] = c1
ind2[i] = c2
return ind1, ind2
######################################
# Messy Crossovers #
######################################
def cxMessyOnePoint(ind1, ind2):
"""Executes a one point crossover on :term:`sequence` individual.
The crossover will in most cases change the individuals size. The two
individuals are modified in place.
:param ind1: The first individual participating in the crossover.
:param ind2: The second individual participating in the crossover.
:returns: A tuple of two individuals.
This function uses the :func:`~random.randint` function from the python base
:mod:`random` module.
"""
cxpoint1 = random.randint(0, len(ind1))
cxpoint2 = random.randint(0, len(ind2))
ind1[cxpoint1:], ind2[cxpoint2:] = ind2[cxpoint2:], ind1[cxpoint1:]
return ind1, ind2
######################################
# ES Crossovers #
######################################
def cxESBlend(ind1, ind2, alpha):
"""Executes a blend crossover on both, the individual and the strategy. The
individuals shall be a :term:`sequence` and must have a :term:`sequence`
:attr:`strategy` attribute. Adjustement of the minimal strategy shall be done
after the call to this function, consider using a decorator.
:param ind1: The first evolution strategy participating in the crossover.
:param ind2: The second evolution strategy participating in the crossover.
:param alpha: Extent of the interval in which the new values can be drawn
for each attribute on both side of the parents' attributes.
:returns: A tuple of two evolution strategies.
This function uses the :func:`~random.random` function from the python base
:mod:`random` module.
"""
for i, (x1, s1, x2, s2) in enumerate(zip(ind1, ind1.strategy,
ind2, ind2.strategy)):
# Blend the values
gamma = (1. + 2. * alpha) * random.random() - alpha
ind1[i] = (1. - gamma) * x1 + gamma * x2
ind2[i] = gamma * x1 + (1. - gamma) * x2
# Blend the strategies
gamma = (1. + 2. * alpha) * random.random() - alpha
ind1.strategy[i] = (1. - gamma) * s1 + gamma * s2
ind2.strategy[i] = gamma * s1 + (1. - gamma) * s2
return ind1, ind2
def cxESTwoPoint(ind1, ind2):
"""Executes a classical two points crossover on both the individuals and their
strategy. The individuals shall be a :term:`sequence` and must have a
:term:`sequence` :attr:`strategy` attribute. The crossover points for the
individual and the strategy are the same.
:param ind1: The first evolution strategy participating in the crossover.
:param ind2: The second evolution strategy participating in the crossover.
:returns: A tuple of two evolution strategies.
This function uses the :func:`~random.randint` function from the python base
:mod:`random` module.
"""
size = min(len(ind1), len(ind2))
pt1 = random.randint(1, size)
pt2 = random.randint(1, size - 1)
if pt2 >= pt1:
pt2 += 1
else: # Swap the two cx points
pt1, pt2 = pt2, pt1
ind1[pt1:pt2], ind2[pt1:pt2] = ind2[pt1:pt2], ind1[pt1:pt2]
ind1.strategy[pt1:pt2], ind2.strategy[pt1:pt2] = \
ind2.strategy[pt1:pt2], ind1.strategy[pt1:pt2]
return ind1, ind2
def cxESTwoPoints(ind1, ind2):
"""
.. deprecated:: 1.0
The function has been renamed. Use :func:`cxESTwoPoint` instead.
"""
return cxESTwoPoints(ind1, ind2)
# List of exported function names.
__all__ = ['cxOnePoint', 'cxTwoPoint', 'cxUniform', 'cxPartialyMatched',
'cxUniformPartialyMatched', 'cxOrdered', 'cxBlend',
'cxSimulatedBinary','cxSimulatedBinaryBounded', 'cxMessyOnePoint',
'cxESBlend', 'cxESTwoPoint']
# Deprecated functions
__all__.extend(['cxTwoPoints', 'cxESTwoPoints'])