Repository navigation
Expand file tree
/
Copy pathtest_crossover_mutation.py
More file actions
385 lines (299 loc) · 15.9 KB
/
Copy pathtest_crossover_mutation.py
File metadata and controls
385 lines (299 loc) · 15.9 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
375
376
377
378
379
380
381
382
383
384
385
import pygad
import random
import numpy
num_generations = 1
initial_population = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
def output_crossover_mutation(gene_space=None,
gene_type=float,
num_genes=10,
mutation_by_replacement=False,
random_mutation_min_val=-1,
random_mutation_max_val=1,
init_range_low=-4,
init_range_high=4,
initial_population=None,
crossover_probability=None,
mutation_probability=None,
crossover_type=None,
mutation_type=None,
parent_selection_type='sss',
multi_objective=False):
def fitness_func_no_batch_single(ga, solution, idx):
return random.random()
def fitness_func_no_batch_multi(ga, solution, idx):
return [random.random(), random.random()]
if multi_objective == True:
fitness_func = fitness_func_no_batch_multi
else:
fitness_func = fitness_func_no_batch_single
ga_instance = pygad.GA(num_generations=num_generations,
num_parents_mating=5,
fitness_func=fitness_func,
sol_per_pop=10,
num_genes=num_genes,
gene_space=gene_space,
gene_type=gene_type,
parent_selection_type=parent_selection_type,
initial_population=initial_population,
init_range_low=init_range_low,
init_range_high=init_range_high,
random_mutation_min_val=random_mutation_min_val,
random_mutation_max_val=random_mutation_max_val,
allow_duplicate_genes=True,
mutation_by_replacement=mutation_by_replacement,
save_solutions=True,
crossover_probability=crossover_probability,
mutation_probability=mutation_probability,
crossover_type=crossover_type,
mutation_type=mutation_type,
suppress_warnings=True,
random_seed=1)
ga_instance.run()
comparison_result = []
for solution_idx, solution in enumerate(ga_instance.population):
if list(solution) in ga_instance.initial_population.tolist():
comparison_result.append(True)
else:
comparison_result.append(False)
comparison_result = numpy.array(comparison_result)
result = numpy.all(comparison_result == True)
print(f"Comparison result is {result}")
return result, ga_instance
def test_no_crossover_no_mutation():
result, ga_instance = output_crossover_mutation()
assert result == True
def test_no_crossover_no_mutation_gene_space():
result, ga_instance = output_crossover_mutation(gene_space=range(10))
assert result == True
def test_no_crossover_no_mutation_int_gene_type():
result, ga_instance = output_crossover_mutation(gene_type=int)
assert result == True
def test_no_crossover_no_mutation_gene_space_gene_type():
result, ga_instance = output_crossover_mutation(gene_space={"low": 0, "high": 10},
gene_type=[float, 2])
assert result == True
def test_no_crossover_no_mutation_nested_gene_space():
result, ga_instance = output_crossover_mutation(gene_space=[[0, 1, 2, 3, 4],
numpy.arange(5, 10),
range(10, 15),
{"low": 15, "high": 20},
{"low": 20, "high": 30, "step": 2},
None,
numpy.arange(30, 35),
numpy.arange(35, 40),
numpy.arange(40, 45),
[45, 46, 47, 48, 49]])
assert result == True
def test_no_crossover_no_mutation_nested_gene_type():
result, ga_instance = output_crossover_mutation(gene_type=[int, float, numpy.float64, [float, 3], [float, 4], numpy.int16, [numpy.float32, 1], int, float, [float, 3]])
assert result == True
def test_no_crossover_no_mutation_nested_gene_space_nested_gene_type():
result, ga_instance = output_crossover_mutation(gene_space=[[0, 1, 2, 3, 4],
numpy.arange(5, 10),
range(10, 15),
{"low": 15, "high": 20},
{"low": 20, "high": 30, "step": 2},
None,
numpy.arange(30, 35),
numpy.arange(35, 40),
numpy.arange(40, 45),
[45, 46, 47, 48, 49]],
gene_type=[int, float, numpy.float64, [float, 3], [float, 4], numpy.int16, [numpy.float32, 1], int, float, [float, 3]])
assert result == True
def test_no_crossover_no_mutation_initial_population():
global initial_population
result, ga_instance = output_crossover_mutation(initial_population=initial_population)
assert result == True
def test_no_crossover_no_mutation_initial_population_nested_gene_type():
global initial_population
result, ga_instance = output_crossover_mutation(initial_population=initial_population,
gene_type=[int, float, numpy.float64, [float, 3], [float, 4], numpy.int16, [numpy.float32, 1], int, float, [float, 3]])
assert result == True
def test_crossover_no_mutation_zero_crossover_probability():
global initial_population
result, ga_instance = output_crossover_mutation(crossover_type="single_point",
crossover_probability=0.0)
assert result == True
def test_zero_crossover_probability_zero_mutation_probability():
global initial_population
result, ga_instance = output_crossover_mutation(crossover_type="single_point",
crossover_probability=0.0,
mutation_type="random",
mutation_probability=0.0)
assert result == True
def test_random_mutation_manual_call():
result, ga_instance = output_crossover_mutation(mutation_type="random",
random_mutation_min_val=888,
random_mutation_max_val=999)
ga_instance.mutation_num_genes = 9
temp_offspring = numpy.array(initial_population[0:1])
offspring = ga_instance.random_mutation(offspring=temp_offspring.copy())
comp = offspring - temp_offspring
comp_sorted = sorted(comp.copy())
comp_sorted = numpy.abs(numpy.unique(comp_sorted))
# The other 1 added to include the last value in the range.
assert len(comp_sorted) in range(1, 1 + 1 + ga_instance.mutation_num_genes)
assert comp_sorted[0] == 0
def test_random_mutation_manual_call2():
result, ga_instance = output_crossover_mutation(mutation_type="random",
random_mutation_min_val=888,
random_mutation_max_val=999)
ga_instance.mutation_num_genes = 10
temp_offspring = numpy.array(initial_population[0:1])
offspring = ga_instance.random_mutation(offspring=temp_offspring.copy())
comp = offspring - temp_offspring
comp_sorted = sorted(comp.copy())
comp_sorted = numpy.abs(numpy.unique(comp_sorted))
# The other 1 added to include the last value in the range.
assert len(comp_sorted) in range(1, 1 + 1 + ga_instance.mutation_num_genes)
# assert comp_sorted[0] == 0
def test_random_mutation_manual_call3():
# Use random_mutation_min_val & random_mutation_max_val as numbers.
random_mutation_min_val = 888
random_mutation_max_val = 999
result, ga_instance = output_crossover_mutation(mutation_type="random",
random_mutation_min_val=random_mutation_min_val,
random_mutation_max_val=random_mutation_max_val,
mutation_by_replacement=True)
ga_instance.mutation_num_genes = 10
temp_offspring = numpy.array(initial_population[0:1])
offspring = ga_instance.random_mutation(offspring=temp_offspring.copy())
comp = offspring
comp_sorted = sorted(comp.copy())
comp_sorted = numpy.abs(numpy.unique(comp))
value_space = list(range(random_mutation_min_val, random_mutation_max_val))
for value in comp_sorted:
assert value in value_space
def test_random_mutation_manual_call4():
# Use random_mutation_min_val & random_mutation_max_val as lists.
random_mutation_min_val = [888]*10
random_mutation_max_val = [999]*10
result, ga_instance = output_crossover_mutation(mutation_type="random",
random_mutation_min_val=random_mutation_min_val,
random_mutation_max_val=random_mutation_max_val,
mutation_by_replacement=True)
ga_instance.mutation_num_genes = 10
temp_offspring = numpy.array(initial_population[0:1])
offspring = ga_instance.random_mutation(offspring=temp_offspring.copy())
comp = offspring
comp_sorted = sorted(comp.copy())
comp_sorted = numpy.abs(numpy.unique(comp))
value_space = list(range(random_mutation_min_val[0], random_mutation_max_val[0]))
for value in comp_sorted:
assert value in value_space
def random_mutation_permutation(gene_space, mutation_probability=None):
# Each solution is a permutation of range(num_genes): no value of the gene space is free.
num_genes = 8
ga_instance = pygad.GA(num_generations=num_generations,
num_parents_mating=2,
fitness_func=lambda ga, solution, idx: random.random(),
sol_per_pop=4,
num_genes=num_genes,
gene_space=gene_space,
gene_type=int,
allow_duplicate_genes=False,
mutation_type="random",
mutation_probability=mutation_probability,
suppress_warnings=True,
random_seed=1)
temp_offspring = numpy.array([numpy.random.permutation(num_genes) for _ in range(100)])
offspring = ga_instance.random_mutation(offspring=temp_offspring.copy())
for solution in offspring:
# The mutation keeps the permutation.
assert sorted(solution) == list(range(num_genes))
# The mutation changes the solutions.
assert numpy.all(numpy.any(offspring != temp_offspring, axis=1))
def test_random_mutation_permutation():
random_mutation_permutation(gene_space=list(range(8)))
def test_random_mutation_permutation_probability():
random_mutation_permutation(gene_space=list(range(8)),
mutation_probability=1.0)
def test_random_mutation_permutation_nested_gene_space():
random_mutation_permutation(gene_space=[list(range(8))] * 8)
def test_two_points_crossover_manual_call():
# Both points are random: the genes between them form 1 segment of any length from 1 to num_genes.
num_genes = 10
num_offspring = 1000
result, ga_instance = output_crossover_mutation(gene_type=int,
crossover_type="two_points")
parents = numpy.array([[0] * num_genes,
[1] * num_genes])
offspring = ga_instance.two_points_crossover(parents=parents,
offspring_size=(num_offspring, num_genes))
# Without crossover_probability, the first parent of offspring k is parents[k % 2].
# Mark the genes that come from the second parent with 1.
from_second_parent = numpy.array([child if k % 2 == 0 else 1 - child for k, child in enumerate(offspring)])
segment_lengths = set()
for child in from_second_parent:
segment = numpy.flatnonzero(child)
# The genes from the second parent are consecutive.
assert len(segment) > 0
assert segment[-1] - segment[0] + 1 == len(segment)
segment_lengths.add(len(segment))
assert segment_lengths == set(range(1, num_genes + 1))
def test_swap_mutation_manual_call():
# Any 2 different genes can be swapped.
num_genes = 6
result, ga_instance = output_crossover_mutation(gene_type=int,
num_genes=num_genes,
mutation_type="swap")
temp_offspring = numpy.array([list(range(num_genes))] * 1000)
offspring = ga_instance.swap_mutation(offspring=temp_offspring.copy())
swapped_pairs = set()
for solution in offspring:
changed = numpy.flatnonzero(solution != numpy.arange(num_genes))
# Exactly 2 genes exchange their values.
assert len(changed) == 2
assert solution[changed[0]] == changed[1] and solution[changed[1]] == changed[0]
swapped_pairs.add(tuple(changed))
assert len(swapped_pairs) == num_genes * (num_genes - 1) // 2
if __name__ == "__main__":
#### Single-objective
print()
test_no_crossover_no_mutation()
print()
test_no_crossover_no_mutation_int_gene_type()
print()
test_no_crossover_no_mutation_gene_space()
print()
test_no_crossover_no_mutation_gene_space_gene_type()
print()
test_no_crossover_no_mutation_nested_gene_space()
print()
test_no_crossover_no_mutation_nested_gene_type()
print()
test_no_crossover_no_mutation_initial_population()
print()
test_no_crossover_no_mutation_initial_population_nested_gene_type()
print()
test_crossover_no_mutation_zero_crossover_probability()
print()
test_zero_crossover_probability_zero_mutation_probability()
print()
test_random_mutation_manual_call()
print()
test_random_mutation_manual_call2()
print()
test_random_mutation_manual_call3()
print()
test_random_mutation_manual_call4()
print()
test_random_mutation_permutation()
print()
test_random_mutation_permutation_probability()
print()
test_random_mutation_permutation_nested_gene_space()
print()
test_two_points_crossover_manual_call()
print()
test_swap_mutation_manual_call()
print()