Repository navigation
Expand file tree
/
Copy pathrandom_mutator.py
More file actions
52 lines (40 loc) · 1.59 KB
/
Copy pathrandom_mutator.py
File metadata and controls
52 lines (40 loc) · 1.59 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
""" Random mutator module. """
# Custom code imports.
from pygenalgo.genome.chromosome import Chromosome
from pygenalgo.operators.mutation.mutate_operator import MutationOperator
class RandomMutator(MutationOperator):
"""
Description:
Random mutator, mutates the chromosome by selecting randomly
a position and replace the Gene with a new one that has been
generated randomly (uniform probability).
"""
def __init__(self, mutate_probability: float = 0.1) -> None:
"""
Construct a 'RandomMutator' 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 randomly replacing
a gene with a new one that has been generated randomly.
: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 an index at random.
idx: int = self.rng.integers(n_genes, dtype=int)
# Replace the old gene with a random one.
individual[idx].random()
# Finalize the mutation.
self._finalize_mutation(individual)
# _end_def_
# _end_class_