@File : selection.py
@Time : 2023/11/03 10:33:26
@Author : Alejandro Marrero
@Version : 1.0
@Contact : amarrerd@ull.edu.es
@License : (C)Copyright 2023, Alejandro Marrero
@Desc : None
binary_tournament_selection(population)
Binary Tournament Selection Operator
Parameters: |
-
population
(Sequence )
–
Population of individuals to select a parent from
|
Raises: |
-
RuntimeError
–
If the population is empty
|
Returns: |
-
IndType
–
Instance or Solution: New parent
|
Source code in digneapy/operators/_selection.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 | def binary_tournament_selection(population: Sequence[IndType]) -> IndType:
"""Binary Tournament Selection Operator
Args:
population (Sequence): Population of individuals to select a parent from
Raises:
RuntimeError: If the population is empty
Returns:
Instance or Solution: New parent
"""
if population is None or len(population) == 0:
msg = "Trying to selection individuals in an empty population."
raise ValueError(msg)
if len(population) == 1:
return population[0]
else:
idx1, idx2 = np.random.default_rng().integers(
low=0, high=len(population), size=2
)
return max(population[idx1], population[idx2], key=attrgetter("fitness"))
|