Repository navigation
Expand file tree
/
Copy pathselect_operator.py
More file actions
211 lines (166 loc) · 7.01 KB
/
Copy pathselect_operator.py
File metadata and controls
211 lines (166 loc) · 7.01 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
""" Selection operator module. """
from functools import wraps
from math import fabs, isclose
# Custom code imports.
from pygenalgo.genome.chromosome import Chromosome
from pygenalgo.operators.genetic_operator import GeneticOperator
# Public interface.
__all__ = ["SelectionOperator", "ensure_positive_fitness"]
def _shift_up_values(population: list[Chromosome]) -> list[float]:
"""
Ensures that the fitness value of each chromosome is a positive
number. This is useful because some selection methods require a
positive fitness to operate.
:param population: (list) of chromosomes.
:return: (list) of positive fitness values.
"""
# Extract all the fitness values.
all_fitness: list[float] = [
p.fitness for p in population
]
# Sanity check.
if not all_fitness:
return []
# If there are negative values we perform a shift
# transformation where all the values are shifted
# so that the minimum fitness is going to be one.
if any(fit_value <= 0.0 for fit_value in all_fitness):
# Compute the shift value.
shift_value: float = fabs(min(all_fitness)) + 1.0
# Shift all fitness values so that the minimum is '1'.
all_fitness = [f + shift_value for f in all_fitness]
# _end_if_
return all_fitness
# _end_def_
def _linear_scaled_values(population: list[Chromosome]) -> list[float]:
"""
Ensures fitness values are positive for maximization selection methods.
The worst individual is assigned a baseline fitness of 1.0, and others
are scaled relative to it.
:param population: (list) of chromosomes.
:return: (list) of positive fitness values.
"""
# Extract all the fitness values.
all_fitness: list[float] = [
p.fitness for p in population
]
# Sanity check.
if not all_fitness:
return []
# Extract min/max values.
min_fitness = min(all_fitness)
max_fitness = max(all_fitness)
# If all individuals have the exact same
# fitness, give them equal weight.
if isclose(min_fitness, max_fitness):
return [1.0] * len(population)
# Shift everything so the worst individual is always 1.0.
# This works whether values are positive, negative, zero.
return [
f - min_fitness + 1.0 for f in all_fitness
]
# _end_def_
def ensure_positive_fitness(population: list[Chromosome],
mode: str = "shift_up") -> list[float]:
"""
Ensures fitness values are positive, using a predefined
selected method.
:param population: (list) of chromosomes.
:param mode: (str) method of calculating fitness.
:return: (list) of fitness values.
"""
if mode == "shift_up":
return _shift_up_values(population)
if mode == "linear_scaled":
return _linear_scaled_values(population)
raise ValueError(f"{mode} is not implemented.")
# _end_if_
class SelectionOperator(GeneticOperator):
"""
Description:
Provides the base class (interface) for a Selection Operator.
Note that even though the operator accepts a probability value,
for the moment this operator is applied with 100% 'probability'.
"""
def __init__(self, selection_probability: float) -> None:
"""
Construct a 'SelectionOperator' object with a
given probability value.
:param selection_probability: (float).
"""
# Call the super constructor with the provided initial value.
super().__init__(probability=selection_probability)
# _end_def_
def __init_subclass__(cls, *args, **kwargs) -> None:
"""
This is used when a new subclass of SelectionOperator is implemented.
It wraps the selection implementation method and validates its input
so that if the population is empty, raises an error.
:param args: (tuple) of positional arguments.
:param kwargs: (dict) of keyword arguments.
"""
# Call the subclass initialization.
super().__init_subclass__(*args, **kwargs)
# Make sure the select method is part of the subclass.
if "select" in cls.__dict__:
# Get a reference of the original method.
original_select = cls.__dict__["select"]
@wraps(original_select)
def validated_select(self, population: list[Chromosome],
*args, **kwargs) -> list[Chromosome]:
# Check the population.
if not population:
raise ValueError(f"{self.__class__.__name__}: "
f"Input population cannot be empty.")
# Call the original select method.
return original_select(self, population, *args, **kwargs)
# _end_def_
# Set the validated method in the class.
setattr(cls, "select", validated_select)
# _end_def_
def select(self, population: list[Chromosome]) -> list[Chromosome]:
"""
Abstract method that "reminds" the user that if they want to
create a Selection Class that inherits from here they should
implement a select method.
:param population: is a list, with the chromosomes, to select
the parents for the next generation
:return: Nothing but raising an error.
"""
raise NotImplementedError(f"{self.__class__.__name__}: "
f"You should implement this method!")
# _end_def_
def __call__(self, population: list[Chromosome]) -> list[Chromosome]:
"""
This is only a wrapper of the "select" method.
"""
return self.select(population)
# _end_def_
def _safety_option(self, population: list[Chromosome],
pop_size: int | None = None) -> list[Chromosome]:
"""
Select randomly the individuals, from the input population,
that will be passed on to the variation step (crossover and
mutation).
It provides the main operation of the RandomSelector and the
"safety option" for other Selection operators, such as:
i) RouletteWheel, ii) Boltzmann, and iii) Stochastic Universal
Sampling. It will always return a list of chromosomes since there
is no usage of the fitness values.
:param population: a list of chromosomes to select the parents.
:param pop_size: (int) the population size to select. Defaults
is set to None. This means the whole population
size is returned.
:return: the selected list of chromosomes.
"""
# Check if pop_size is not provided.
if pop_size is None:
pop_size = len(population)
# _end_def_
# Select all individual indices with equal probability.
random_index = self.rng.choice(pop_size, size=pop_size,
replace=True, shuffle=False)
# Return the new parents.
return [population[i] for i in random_index]
# _end_def_
# _end_class_