Repository navigation
Expand file tree
/
Copy pathmutation.py
More file actions
883 lines (745 loc) · 44.1 KB
/
Copy pathmutation.py
File metadata and controls
883 lines (745 loc) · 44.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
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
"""
The pygad.utils.mutation module has all the built-in mutation operators.
"""
from itertools import chain, combinations
import numpy
import pygad
import warnings
class Mutation:
def __init__(self):
pass
def random_mutation(self, offspring):
"""
Dispatch to one of the four random-mutation backends depending
on whether the user passed ``mutation_probability`` and whether
``gene_space`` is set. The replacement value for each mutated
gene comes either from the gene space or from the
``random_mutation_min_val`` / ``random_mutation_max_val`` range.
Parameters
----------
offspring : numpy.ndarray
The offspring solutions to mutate (modified in place).
Returns
-------
offspring : numpy.ndarray
The mutated offspring.
"""
# If the mutation values are selected from the mutation space, the attribute 'gene_space' is not None. Otherwise, it is None.
# When the 'mutation_probability' parameter exists (i.e. not None), then it is used in the mutation. Otherwise, the 'mutation_num_genes' parameter is used.
if self.mutation_probability is None:
# When the 'mutation_probability' parameter does not exist (i.e. None), then the parameter 'mutation_num_genes' is used in the mutation.
if not (self.gene_space is None):
# When the attribute 'gene_space' exists (i.e. not None), the mutation values are selected randomly from the space of values of each gene.
offspring = self.mutation_by_space(offspring)
else:
offspring = self.mutation_randomly(offspring)
else:
# When the 'mutation_probability' parameter exists (i.e. not None), then it is used in the mutation.
if not (self.gene_space is None):
# When the attribute 'gene_space' exists (i.e. not None), the mutation values are selected from the space of values of each gene.
offspring = self.mutation_probs_by_space(offspring)
else:
offspring = self.mutation_probs_randomly(offspring)
return offspring
def mutation_by_space(self, offspring):
"""
Mutate ``self.mutation_num_genes`` genes per offspring by
sampling a replacement value from the ``gene_space`` of each
chosen gene.
Parameters
----------
offspring : numpy.ndarray
The offspring solutions to mutate (modified in place).
Returns
-------
offspring : numpy.ndarray
The mutated offspring.
"""
# For each offspring, a value from the gene space is selected randomly and assigned to the selected mutated gene.
for offspring_idx in range(offspring.shape[0]):
mutation_indices = numpy.array(self.python_random_generator.sample(range(0, self.num_genes), self.mutation_num_genes))
swapped_genes = set()
for gene_idx in mutation_indices:
if gene_idx in swapped_genes:
continue
value_from_space = self.mutation_process_gene_value(solution=offspring[offspring_idx],
gene_idx=gene_idx,
sample_size=self.sample_size)
if self.allow_duplicate_genes == False and value_from_space == offspring[offspring_idx, gene_idx]:
# No value of the gene space is free (e.g. a permutation): swap the gene with another one instead.
offspring[offspring_idx] = self.swap_gene_by_space(solution=offspring[offspring_idx],
gene_idx=gene_idx,
swapped_genes=swapped_genes)
continue
offspring[offspring_idx, gene_idx] = value_from_space
if self.allow_duplicate_genes == False:
offspring[offspring_idx], _, _ = self.solve_duplicate_genes(solution=offspring[offspring_idx])
return offspring
def mutation_probs_by_space(self, offspring):
"""
Per-gene mutation that uses the ``gene_space`` for replacement
values and ``self.mutation_probability`` to decide which genes
to mutate. A gene is mutated when a uniform random draw is
less than or equal to the probability threshold.
Parameters
----------
offspring : numpy.ndarray
The offspring solutions to mutate (modified in place).
Returns
-------
offspring : numpy.ndarray
The mutated offspring.
"""
# For each offspring, a value from the gene space is selected randomly and assigned to the selected mutated gene.
for offspring_idx in range(offspring.shape[0]):
probs = self.numpy_random_generator.random(size=offspring.shape[1])
swapped_genes = set()
for gene_idx in range(offspring.shape[1]):
if gene_idx in swapped_genes:
continue
if probs[gene_idx] < self.mutation_probability:
value_from_space = self.mutation_process_gene_value(solution=offspring[offspring_idx],
gene_idx=gene_idx,
sample_size=self.sample_size)
if self.allow_duplicate_genes == False and value_from_space == offspring[offspring_idx, gene_idx]:
# No value of the gene space is free (e.g. a permutation): swap the gene with another one instead.
offspring[offspring_idx] = self.swap_gene_by_space(solution=offspring[offspring_idx],
gene_idx=gene_idx,
swapped_genes=swapped_genes)
continue
# Assigning the selected value from the space to the gene.
offspring[offspring_idx, gene_idx] = value_from_space
if self.allow_duplicate_genes == False:
offspring[offspring_idx], _, _ = self.solve_duplicate_genes(solution=offspring[offspring_idx])
return offspring
def mutation_process_gene_value(self,
solution,
gene_idx,
range_min=None,
range_max=None,
sample_size=100):
"""
Pick a replacement value for a single gene. If the user passed a
``gene_constraint`` for that gene, the method draws up to
``sample_size`` candidate values, filters them through the
constraint, and picks one of the survivors at random; if no
candidate passes, the current value is kept.
When no constraint exists, a single value is sampled directly
from the gene space or the random-mutation range.
Parameters
----------
solution : numpy.ndarray
The solution that owns the gene.
gene_idx : int
Index of the gene inside ``solution``.
range_min : float, optional
Lower bound of the random range. Used only when the gene
has no ``gene_space``.
range_max : float, optional
Upper bound of the random range. Used only when the gene
has no ``gene_space``.
sample_size : int
Maximum number of candidate values to draw when a gene
constraint is in effect. The actual number can be smaller
if the generator runs out of distinct values.
Returns
-------
value_selected : numeric
The new value for the gene. May be the old value if no
candidate satisfied the constraint.
"""
# Check if the gene has a constraint.
if self.gene_constraint and self.gene_constraint[gene_idx] is not None:
# Generate values that meet the gene constraint. Select more than 1 value.
# This method: 1) generates or selects the values 2) filters the values according to the constraint.
values = self.get_valid_gene_constraint_values(range_min=range_min,
range_max=range_max,
gene_value=solution[gene_idx],
gene_idx=gene_idx,
mutation_by_replacement=self.mutation_by_replacement,
solution=solution,
sample_size=sample_size)
if values is None:
# No value found that satisfy the constraint.
# Keep the old value.
value_selected = solution[gene_idx]
else:
# Select a value randomly from the list of values satisfying the constraint.
# If size is used with self.numpy_random_generator.choice(), it returns an array even if it has a single value. To return a numeric value, not an array, then return index 0.
value_selected = self.numpy_random_generator.choice(values, size=1)[0]
else:
# The gene does not have a constraint. Just select a single value.
value_selected = self.generate_gene_value(range_min=range_min,
range_max=range_max,
gene_value=solution[gene_idx],
gene_idx=gene_idx,
solution=solution,
mutation_by_replacement=self.mutation_by_replacement,
sample_size=1)
# Candidate arrays use NumPy scalar types. Match the declared
# Python or NumPy scalar type before storing the selected value.
dtype = self.get_gene_dtype(gene_idx)[0]
return value_selected if dtype is object else dtype(value_selected)
def swap_gene_by_space(self,
solution,
gene_idx,
swapped_genes=None):
"""
With ``allow_duplicate_genes=False``, a gene cannot take a new
value from its space when all of them are used by other genes,
as in a permutation (``gene_space=range(num_genes)``). To still
change the solution, swap the gene's value with the value of
another compatible gene, picked at random. Both values are
cast and rounded for their destination genes. A swap is only
allowed if this preserves their numeric values and both gene
spaces, so it also preserves uniqueness. Genes with a
``gene_constraint`` are not swapped, and any constraints on
other genes must still hold after the swap. Each gene
participates in at most one fallback swap per mutation pass.
Parameters
----------
solution : numpy.ndarray
The solution that owns the gene (modified in place).
gene_idx : int
Index of the gene inside ``solution``.
swapped_genes : set, optional
Indices already swapped in this offspring's mutation
pass. Updated in place after a successful swap. Omit it
when calling this helper independently.
Returns
-------
solution : numpy.ndarray
The solution after the swap, unchanged if no gene qualifies.
"""
def has_constraint(idx):
return bool(self.gene_constraint and self.gene_constraint[idx] is not None)
if swapped_genes is None:
swapped_genes = set()
if gene_idx in swapped_genes or has_constraint(gene_idx):
return solution
gene_value = solution[gene_idx]
candidates = []
for other_idx, other_value in enumerate(solution):
if (other_idx in swapped_genes or other_value == gene_value
or has_constraint(other_idx)):
continue
try:
new_gene_value = self.change_gene_dtype_and_round(gene_idx, other_value)
new_other_value = self.change_gene_dtype_and_round(other_idx, gene_value)
except (OverflowError, ValueError, TypeError):
# A value that cannot be represented by the destination
# dtype cannot be part of a permutation-preserving swap.
continue
# Preserve the original set of numeric values. In particular,
# casting or rounding must not turn a value into a duplicate.
if (self._gene_value_key(new_gene_value) != self._gene_value_key(other_value)
or self._gene_value_key(new_other_value) != self._gene_value_key(gene_value)):
continue
if (not self.is_gene_value_in_space(gene_idx, new_gene_value, gene_value)
or not self.is_gene_value_in_space(other_idx, new_other_value, other_value)):
continue
# A constraint on a different gene may depend on either
# swapped position. Validate the complete candidate solution.
if self.gene_constraint:
candidate_solution = solution.copy()
candidate_solution[gene_idx] = new_gene_value
candidate_solution[other_idx] = new_other_value
if not self.solution_satisfies_gene_constraints(candidate_solution):
continue
candidates.append((other_idx, new_gene_value, new_other_value))
if len(candidates) > 0:
other_idx, new_gene_value, new_other_value = self.python_random_generator.choice(candidates)
solution[gene_idx] = new_gene_value
solution[other_idx] = new_other_value
swapped_genes.update((gene_idx, other_idx))
return solution
def mutation_randomly(self, offspring):
"""
Mutate ``self.mutation_num_genes`` genes per offspring by
drawing a new value from the random-mutation range for each
chosen gene.
Parameters
----------
offspring : numpy.ndarray
The offspring solutions to mutate (modified in place).
Returns
-------
offspring : numpy.ndarray
The mutated offspring.
"""
# Random mutation changes one or more genes in each offspring randomly.
for offspring_idx in range(offspring.shape[0]):
# Return the indices of the genes to mutate.
mutation_indices = numpy.array(self.python_random_generator.sample(range(0, self.num_genes),
self.mutation_num_genes))
for gene_idx in mutation_indices:
range_min, range_max = self.get_random_mutation_range(gene_idx)
# Generate a random value for mutation that meets the gene constraint, if one exists.
random_value = self.mutation_process_gene_value(range_min=range_min,
range_max=range_max,
solution=offspring[offspring_idx],
gene_idx=gene_idx,
sample_size=self.sample_size)
offspring[offspring_idx, gene_idx] = random_value
if self.allow_duplicate_genes == False:
offspring[offspring_idx], _, _ = self.solve_duplicate_genes(solution=offspring[offspring_idx])
return offspring
def mutation_probs_randomly(self, offspring):
"""
Per-gene mutation that uses the random-mutation range and
``self.mutation_probability`` to decide which genes to mutate.
A gene is mutated when a uniform random draw is less than or
equal to the probability threshold.
Parameters
----------
offspring : numpy.ndarray
The offspring solutions to mutate (modified in place).
Returns
-------
offspring : numpy.ndarray
The mutated offspring.
"""
# Random mutation changes one or more genes in each offspring randomly.
for offspring_idx in range(offspring.shape[0]):
# The mutation probabilities for the current offspring.
probs = self.numpy_random_generator.random(size=offspring.shape[1])
for gene_idx in range(offspring.shape[1]):
range_min, range_max = self.get_random_mutation_range(gene_idx)
# A gene is mutated only if its mutation probability is less than the threshold.
if probs[gene_idx] < self.mutation_probability:
# Generate a random value for mutation that meets the gene constraint, if one exists.
random_value = self.mutation_process_gene_value(range_min=range_min,
range_max=range_max,
solution=offspring[offspring_idx],
gene_idx=gene_idx,
sample_size=self.sample_size)
offspring[offspring_idx, gene_idx] = random_value
if self.allow_duplicate_genes == False:
offspring[offspring_idx], _, _ = self.solve_duplicate_genes(solution=offspring[offspring_idx])
return offspring
def polynomial_mutation(self, offspring):
"""
Apply polynomial mutation. Each gene is mutated with
probability ``self.mutation_probability`` (or with probability
``1/num_genes`` when ``mutation_probability`` is not set).
The size of the change is set by
``self.polynomial_mutation_eta`` (a higher value means a
smaller change). The per-gene bounds come from
``get_initial_population_range``.
Parameters
----------
offspring : numpy.ndarray
The offspring solutions to mutate (changed in place).
Returns
-------
offspring : numpy.ndarray
The mutated offspring.
"""
eta = float(self.polynomial_mutation_eta)
eta_plus_one = eta + 1.0
for solution_index, solution in enumerate(offspring):
original = solution.copy()
if self.mutation_probability is not None or not self.mutation_control_explicitly_set:
probability = self.mutation_probability if self.mutation_probability is not None else 1.0 / self.num_genes
gene_indices = (index for index in range(self.num_genes) if self.numpy_random_generator.random() < probability)
else:
gene_indices = self.select_mutation_gene_indices()
selected_any_gene = False
for gene_index in gene_indices:
selected_any_gene = True
lower, upper = map(float, self.get_bounded_operator_gene_range(gene_index))
if upper - lower < 1e-14:
solution[gene_index] = self.convert_bounded_operator_gene_value(gene_index, lower)
continue
value = float(numpy.clip(solution[gene_index], lower, upper))
delta_lower = (value - lower) / (upper - lower)
delta_upper = (upper - value) / (upper - lower)
quantile = self.numpy_random_generator.random()
if quantile <= 0.5:
distance = 1.0 - delta_lower
spread = 2.0 * quantile + (1.0 - 2.0 * quantile) * pow(distance, eta_plus_one)
change = pow(spread, 1.0 / eta_plus_one) - 1.0
else:
distance = 1.0 - delta_upper
spread = 2.0 * (1.0 - quantile) + 2.0 * (quantile - 0.5) * pow(distance, eta_plus_one)
change = 1.0 - pow(spread, 1.0 / eta_plus_one)
new_value = numpy.clip(value + change * (upper - lower), lower, upper)
solution[gene_index] = self.convert_bounded_operator_gene_value(gene_index, new_value)
if selected_any_gene:
offspring[solution_index] = self.prepare_bounded_operator_solution(original, solution)
return offspring
def select_mutation_gene_indices(self):
"""Select eligible genes using the active probability or gene count."""
if self.mutation_probability is not None:
return numpy.where(self.numpy_random_generator.random(self.num_genes) < self.mutation_probability)[0]
return numpy.asarray(self.python_random_generator.sample(range(self.num_genes), self.mutation_num_genes), dtype=int)
def swap_mutation(self, offspring):
"""Swap a compatible pair of eligible genes in each offspring.
Explicit mutation controls select eligible positions. With no explicit
control, all positions are eligible and a pair is selected uniformly.
"""
return self._apply_permutation_mutation(offspring, 'swap')
def inversion_mutation(self, offspring):
"""Reverse eligible genes, keeping changes that satisfy destination rules."""
return self._apply_permutation_mutation(offspring, 'inversion')
def scramble_mutation(self, offspring):
"""Shuffle eligible genes, keeping changes that satisfy destination rules."""
return self._apply_permutation_mutation(offspring, 'scramble')
def _apply_permutation_mutation(self, offspring, mutation_type):
"""Share gene selection and complete-solution validation for permutations.
Inversion and scramble retain their historical half-length segment when
no control is explicitly set. Swap checks alternative pairs and
inversion checks shorter eligible intervals when the first proposal
fails. Scramble and swaps of multiple pairs try sample_size proposals.
"""
if self.num_genes < 2:
return offspring
for solution_index, solution in enumerate(offspring):
if self.mutation_control_explicitly_set:
eligible = numpy.sort(self.select_mutation_gene_indices())
elif mutation_type == 'swap':
eligible = numpy.arange(self.num_genes)
else:
start = self.numpy_random_generator.randint(low=0, high=int(numpy.ceil(self.num_genes / 2 + 1)), size=1)[0]
eligible = numpy.arange(start, start + self.num_genes // 2)
if len(eligible) < 2:
continue
original = solution.copy()
grouped_swap = mutation_type == 'swap' and self.mutation_control_explicitly_set and len(eligible) > 2
if mutation_type == 'swap' and not grouped_swap:
first, second = self.numpy_random_generator.choice(eligible, size=2, replace=False)
candidate_pairs = [(first, second)]
# Iterate remaining pairs lazily only if the initial swap
# fails, rather than allocating a quadratic pair array.
candidates = chain(candidate_pairs, combinations(eligible.tolist(), 2))
elif mutation_type == 'inversion':
candidates = chain([(0, len(eligible) - 1)], combinations(range(len(eligible)), 2))
else:
candidates = range(self.sample_size)
for candidate in candidates:
proposed = original.copy()
if grouped_swap:
positions = eligible.copy()
self.numpy_random_generator.shuffle(positions)
for first, second in zip(positions[::2], positions[1::2]):
proposed[first], proposed[second] = original[second], original[first]
elif mutation_type == 'swap':
first, second = candidate
proposed[first], proposed[second] = original[second], original[first]
elif mutation_type == 'inversion':
first, last = candidate
selected = eligible[first:last + 1]
proposed[selected] = original[selected][::-1]
else:
values = original[eligible].copy()
self.numpy_random_generator.shuffle(values)
proposed[eligible] = values
prepared = self.prepare_changed_operator_solution(original, proposed)
if prepared is not None:
offspring[solution_index] = prepared
break
return offspring
def adaptive_mutation_population_fitness(self, offspring):
"""Evaluate the kept solutions and actual offspring before mutation."""
if self.keep_elitism > 0:
parents_to_keep, kept_indices = self.steady_state_selection(
self.last_generation_fitness, num_parents=self.keep_elitism)
elif self.keep_parents == -1:
parents_to_keep = self.last_generation_parents.copy()
kept_indices = self.last_generation_parents_indices
elif self.keep_parents > 0:
parents_to_keep, kept_indices = self.steady_state_selection(
self.last_generation_fitness, num_parents=self.keep_parents)
else:
parents_to_keep = []
kept_indices = []
num_kept = len(parents_to_keep)
temp_population = numpy.empty_like(self.population)
if num_kept:
temp_population[:num_kept] = parents_to_keep
temp_population[num_kept:] = offspring
offspring_indices = list(range(num_kept, len(temp_population)))
offspring_fitness = self._evaluate_fitness(
temp_population, offspring_indices, adaptive=True)
# Offspring can have fractional fitness even when the previous
# population's values were integers. Let NumPy infer the new dtype.
fitness = numpy.array(list(self.last_generation_fitness[kept_indices])
+ offspring_fitness)
return numpy.mean(fitness, axis=0), fitness[num_kept:]
def adaptive_mutation(self, offspring):
"""
Dispatch to one of the four adaptive-mutation backends based on
whether ``mutation_probability`` is set and whether
``gene_space`` is provided. With adaptive mutation, the
per-solution mutation rate is high for below-average solutions
and low for above-average solutions.
Parameters
----------
offspring : numpy.ndarray
The offspring solutions to mutate (modified in place).
Returns
-------
offspring : numpy.ndarray
The mutated offspring.
"""
if self.mutation_probability is not None and not any(self.mutation_probability):
return offspring
# If the attribute 'gene_space' exists (i.e. not None), then the mutation values are selected from the 'gene_space' parameter according to the space of values of each gene. Otherwise, it is selected randomly based on the 2 parameters 'random_mutation_min_val' and 'random_mutation_max_val'.
# When the 'mutation_probability' parameter exists (i.e. not None), then it is used in the mutation. Otherwise, the 'mutation_num_genes' parameter is used.
if self.mutation_probability is None:
# When the 'mutation_probability' parameter does not exist (i.e. None), then the parameter 'mutation_num_genes' is used in the mutation.
if not (self.gene_space is None):
# When the attribute 'gene_space' exists (i.e. not None), the mutation values are selected randomly from the space of values of each gene.
offspring = self.adaptive_mutation_by_space(offspring)
else:
# When the attribute 'gene_space' does not exist (i.e. None), the mutation values are selected randomly based on the continuous range specified by the 2 attributes 'random_mutation_min_val' and 'random_mutation_max_val'.
offspring = self.adaptive_mutation_randomly(offspring)
else:
# When the 'mutation_probability' parameter exists (i.e. not None), then it is used in the mutation.
if not (self.gene_space is None):
# When the attribute 'gene_space' exists (i.e. not None), the mutation values are selected randomly from the space of values of each gene.
offspring = self.adaptive_mutation_probs_by_space(offspring)
else:
# When the attribute 'gene_space' does not exist (i.e. None), the mutation values are selected randomly based on the continuous range specified by the 2 attributes 'random_mutation_min_val' and 'random_mutation_max_val'.
offspring = self.adaptive_mutation_probs_randomly(offspring)
return offspring
def adaptive_mutation_by_space(self, offspring):
"""
Adaptive mutation that uses ``mutation_num_genes`` and
``gene_space``. The number of mutated genes per offspring is
the first element of ``mutation_num_genes`` for below-average
solutions and the second element for above-average ones. New
values come from the ``gene_space``.
Parameters
----------
offspring : numpy.ndarray
The offspring solutions to mutate (modified in place).
Returns
-------
offspring : numpy.ndarray
The mutated offspring.
"""
# For each offspring, a value from the gene space is selected randomly and assigned to the selected gene for mutation.
average_fitness, offspring_fitness = self.adaptive_mutation_population_fitness(offspring)
# Adaptive mutation changes one or more genes in each offspring randomly.
# The number of genes to mutate depends on the solution's fitness value.
for offspring_idx in range(offspring.shape[0]):
## TODO Make edits to work with multi-objective optimization.
# Compare the fitness of each offspring to the average fitness of each objective function.
fitness_comparison = offspring_fitness[offspring_idx] < average_fitness
# Check if the problem is single or multi-objective optimization.
if type(fitness_comparison) in [bool, numpy.bool_]:
# Single-objective optimization problem.
if offspring_fitness[offspring_idx] < average_fitness:
adaptive_mutation_num_genes = self.mutation_num_genes[0]
else:
adaptive_mutation_num_genes = self.mutation_num_genes[1]
else:
# Multi-objective optimization problem.
# Get the sum of the pool array (result of comparison).
# True is considered 1 and False is 0.
fitness_comparison_sum = sum(fitness_comparison)
# Check if more than or equal to 50% of the objectives have fitness greater than the average.
# If True, then use the first percentage.
# If False, use the second percentage.
if fitness_comparison_sum >= len(fitness_comparison)/2:
adaptive_mutation_num_genes = self.mutation_num_genes[0]
else:
adaptive_mutation_num_genes = self.mutation_num_genes[1]
mutation_indices = numpy.array(self.python_random_generator.sample(range(0, self.num_genes), adaptive_mutation_num_genes))
swapped_genes = set()
for gene_idx in mutation_indices:
if gene_idx in swapped_genes:
continue
value_from_space = self.mutation_process_gene_value(solution=offspring[offspring_idx],
gene_idx=gene_idx,
sample_size=self.sample_size)
if self.allow_duplicate_genes == False and value_from_space == offspring[offspring_idx, gene_idx]:
# No value of the gene space is free (e.g. a permutation): swap the gene with another one instead.
offspring[offspring_idx] = self.swap_gene_by_space(solution=offspring[offspring_idx],
gene_idx=gene_idx,
swapped_genes=swapped_genes)
continue
# Assigning the selected value from the space to the gene.
offspring[offspring_idx, gene_idx] = value_from_space
if self.allow_duplicate_genes == False:
offspring[offspring_idx], _, _ = self.solve_duplicate_genes(solution=offspring[offspring_idx])
return offspring
def adaptive_mutation_randomly(self, offspring):
"""
Adaptive mutation that uses ``mutation_num_genes`` and the
random-mutation range. The number of mutated genes per
offspring is the first element of ``mutation_num_genes`` for
below-average solutions and the second element for
above-average ones. New values are sampled uniformly from the
random-mutation range.
Parameters
----------
offspring : numpy.ndarray
The offspring solutions to mutate (modified in place).
Returns
-------
offspring : numpy.ndarray
The mutated offspring.
"""
average_fitness, offspring_fitness = self.adaptive_mutation_population_fitness(offspring)
# Adaptive random mutation changes one or more genes in each offspring randomly.
# The number of genes to mutate depends on the solution's fitness value.
for offspring_idx in range(offspring.shape[0]):
## TODO Make edits to work with multi-objective optimization.
# Compare the fitness of each offspring to the average fitness of each objective function.
fitness_comparison = offspring_fitness[offspring_idx] < average_fitness
# Check if the problem is single or multi-objective optimization.
if type(fitness_comparison) in [bool, numpy.bool_]:
# Single-objective optimization problem.
if fitness_comparison:
adaptive_mutation_num_genes = self.mutation_num_genes[0]
else:
adaptive_mutation_num_genes = self.mutation_num_genes[1]
else:
# Multi-objective optimization problem.
# Get the sum of the pool array (result of comparison).
# True is considered 1 and False is 0.
fitness_comparison_sum = sum(fitness_comparison)
# Check if more than or equal to 50% of the objectives have fitness greater than the average.
# If True, then use the first percentage.
# If False, use the second percentage.
if fitness_comparison_sum >= len(fitness_comparison)/2:
adaptive_mutation_num_genes = self.mutation_num_genes[0]
else:
adaptive_mutation_num_genes = self.mutation_num_genes[1]
mutation_indices = numpy.array(self.python_random_generator.sample(range(0, self.num_genes), adaptive_mutation_num_genes))
for gene_idx in mutation_indices:
range_min, range_max = self.get_random_mutation_range(gene_idx)
# Generate a random value fpr mutation that meet the gene constraint if exists.
random_value = self.mutation_process_gene_value(range_min=range_min,
range_max=range_max,
solution=offspring[offspring_idx],
gene_idx=gene_idx,
sample_size=self.sample_size)
offspring[offspring_idx, gene_idx] = random_value
if self.allow_duplicate_genes == False:
offspring[offspring_idx], _, _ = self.solve_duplicate_genes(solution=offspring[offspring_idx])
return offspring
def adaptive_mutation_probs_by_space(self, offspring):
"""
Adaptive mutation that uses ``mutation_probability`` and
``gene_space``. The probability threshold per offspring is the
first element of ``mutation_probability`` for below-average
solutions and the second element for above-average ones. Each
gene is replaced with a value from its ``gene_space`` when its
random draw falls below the chosen threshold.
Parameters
----------
offspring : numpy.ndarray
The offspring solutions to mutate (modified in place).
Returns
-------
offspring : numpy.ndarray
The mutated offspring.
"""
# For each offspring, a value from the gene space is selected randomly and assigned to the selected gene for mutation.
average_fitness, offspring_fitness = self.adaptive_mutation_population_fitness(offspring)
# Adaptive random mutation changes one or more genes in each offspring randomly.
# The probability of mutating a gene depends on the solution's fitness value.
for offspring_idx in range(offspring.shape[0]):
## TODO Make edits to work with multi-objective optimization.
# Compare the fitness of each offspring to the average fitness of each objective function.
fitness_comparison = offspring_fitness[offspring_idx] < average_fitness
# Check if the problem is single or multi-objective optimization.
if type(fitness_comparison) in [bool, numpy.bool_]:
# Single-objective optimization problem.
if offspring_fitness[offspring_idx] < average_fitness:
adaptive_mutation_probability = self.mutation_probability[0]
else:
adaptive_mutation_probability = self.mutation_probability[1]
else:
# Multi-objective optimization problem.
# Get the sum of the pool array (result of comparison).
# True is considered 1 and False is 0.
fitness_comparison_sum = sum(fitness_comparison)
# Check if more than or equal to 50% of the objectives have fitness greater than the average.
# If True, then use the first percentage.
# If False, use the second percentage.
if fitness_comparison_sum >= len(fitness_comparison)/2:
adaptive_mutation_probability = self.mutation_probability[0]
else:
adaptive_mutation_probability = self.mutation_probability[1]
probs = self.numpy_random_generator.random(size=offspring.shape[1])
swapped_genes = set()
for gene_idx in range(offspring.shape[1]):
if gene_idx in swapped_genes:
continue
if probs[gene_idx] < adaptive_mutation_probability:
value_from_space = self.mutation_process_gene_value(solution=offspring[offspring_idx],
gene_idx=gene_idx,
sample_size=self.sample_size)
if self.allow_duplicate_genes == False and value_from_space == offspring[offspring_idx, gene_idx]:
# No value of the gene space is free (e.g. a permutation): swap the gene with another one instead.
offspring[offspring_idx] = self.swap_gene_by_space(solution=offspring[offspring_idx],
gene_idx=gene_idx,
swapped_genes=swapped_genes)
continue
# Assigning the selected value from the space to the gene.
offspring[offspring_idx, gene_idx] = value_from_space
if self.allow_duplicate_genes == False:
offspring[offspring_idx], _, _ = self.solve_duplicate_genes(solution=offspring[offspring_idx])
return offspring
def adaptive_mutation_probs_randomly(self, offspring):
"""
Adaptive mutation that uses ``mutation_probability`` and the
random-mutation range. The probability threshold per offspring
is the first element of ``mutation_probability`` for
below-average solutions and the second element for
above-average ones. Each gene is replaced with a value sampled
uniformly from the random-mutation range when its random draw
falls below the chosen threshold.
Parameters
----------
offspring : numpy.ndarray
The offspring solutions to mutate (modified in place).
Returns
-------
offspring : numpy.ndarray
The mutated offspring.
"""
average_fitness, offspring_fitness = self.adaptive_mutation_population_fitness(offspring)
# Adaptive random mutation changes one or more genes in each offspring randomly.
# The probability of mutating a gene depends on the solution's fitness value.
for offspring_idx in range(offspring.shape[0]):
## TODO Make edits to work with multi-objective optimization.
# Compare the fitness of each offspring to the average fitness of each objective function.
fitness_comparison = offspring_fitness[offspring_idx] < average_fitness
# Check if the problem is single or multi-objective optimization.
if type(fitness_comparison) in [bool, numpy.bool_]:
# Single-objective optimization problem.
if offspring_fitness[offspring_idx] < average_fitness:
adaptive_mutation_probability = self.mutation_probability[0]
else:
adaptive_mutation_probability = self.mutation_probability[1]
else:
# Multi-objective optimization problem.
# Get the sum of the pool array (result of comparison).
# True is considered 1 and False is 0.
fitness_comparison_sum = sum(fitness_comparison)
# Check if more than or equal to 50% of the objectives have fitness greater than the average.
# If True, then use the first percentage.
# If False, use the second percentage.
if fitness_comparison_sum >= len(fitness_comparison)/2:
adaptive_mutation_probability = self.mutation_probability[0]
else:
adaptive_mutation_probability = self.mutation_probability[1]
probs = self.numpy_random_generator.random(size=offspring.shape[1])
for gene_idx in range(offspring.shape[1]):
range_min, range_max = self.get_random_mutation_range(gene_idx)
if probs[gene_idx] < adaptive_mutation_probability:
# Generate a random value for mutation that meets the gene constraint, if one exists.
random_value = self.mutation_process_gene_value(range_min=range_min,
range_max=range_max,
solution=offspring[offspring_idx],
gene_idx=gene_idx,
sample_size=self.sample_size)
offspring[offspring_idx, gene_idx] = random_value
if self.allow_duplicate_genes == False:
offspring[offspring_idx], _, _ = self.solve_duplicate_genes(solution=offspring[offspring_idx])
return offspring