-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathshuffle_mutator.py
More file actions
62 lines (46 loc) · 1.92 KB
/
Copy pathshuffle_mutator.py
File metadata and controls
62 lines (46 loc) · 1.92 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
""" Shuffle mutator module. """
# Custom code imports.
from pygenalgo.genome.chromosome import Chromosome
from pygenalgo.utils.utilities import two_indices_fast
from pygenalgo.operators.mutation.mutate_operator import MutationOperator
class ShuffleMutator(MutationOperator):
"""
Description:
Shuffle mutator mutates the chromosome by shuffling the gene
values between two randomly selected gene end-positions.
"""
def __init__(self, mutate_probability: float = 0.1) -> None:
"""
Construct a 'ShuffleMutator' object with a given probability value.
:param mutate_probability: (float).
"""
# Call the super constructor with the provided initial value.
super().__init__(mutation_probability=mutate_probability)
# _end_def_
def mutate(self, individual: Chromosome) -> None:
"""
Perform the mutation operation by shuffling the genes
between at two random positions.
:param individual: (Chromosome).
:return: None.
"""
# If the mutation probability is higher than
# a uniformly random value, make the changes.
if self.is_operator_applicable():
# Get the size of the chromosome.
n_genes: int = len(individual)
# Select two random (distinct) values in ascending order.
i, j = two_indices_fast(self.rng, n_genes, in_order=True)
# Make a slice list of the genes
# we want to shuffle: i -> j.
sliced_chromosome = individual.genome[i:j]
# Shuffle the copied slice in place.
self.rng.shuffle(sliced_chromosome)
# Put back the shuffled items.
individual.genome[i:j] = sliced_chromosome
# Set the fitness to None.
individual.invalidate_fitness()
# Increase the mutator counter.
self.inc_counter()
# _end_def_
# _end_class_