Repository navigation
Expand file tree
/
Copy pathsimulated_binary_crossover.py
More file actions
172 lines (127 loc) · 6.25 KB
/
Copy pathsimulated_binary_crossover.py
File metadata and controls
172 lines (127 loc) · 6.25 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
""" Simulated binary crossover (SBX) operator module. """
from math import fabs, isclose
# Third party imports.
from numpy.typing import ArrayLike, NDArray
# Custom code imports.
from pygenalgo.genome.gene import Gene
from pygenalgo.genome.chromosome import Chromosome
from pygenalgo.operators.crossover.crossover_operator import (CrossoverOperator, Offspring)
class SimulatedBinaryCrossover(CrossoverOperator):
"""
Description:
Simulate binary crossover (SBX) creates two children chromosomes (offsprings)
by replicating the search behavior of a single-point crossover operator used
in binary-coded Genetic Algorithms onto real-coded variables.
It uses a probability distribution centered around the parents' locations to
calculate a spread factor, ensuring that the average distance of the offspring
from the parents is proportional to the distance between the parents themselves.
NB: Used only for real coded genomes.
"""
def __init__(self, crossover_probability: float = 0.9, eta: float = 20.0,
lower_lim: ArrayLike = None, upper_lim: ArrayLike = None) -> None:
"""
Construct a 'SimulatedBinaryCrossover' object with a given probability value.
:param crossover_probability: (float).
:param eta: (float) distribution index. Typically, between 5 - 50.
Higher values produce children closer to their parents.
:param lower_lim: (ArrayLike) lower limit values for the genes.
:param upper_lim: (ArrayLike) upper limit values for the genes.
"""
# Call the super constructor with the provided initial value.
super().__init__(crossover_probability=crossover_probability)
# Validate the bounds.
lower_lim, upper_lim = self.validate_bounds(lower_lim,
upper_lim)
# Assign variables to the _items placeholder.
self._items: tuple[float, NDArray, NDArray] = (
max(5, min(float(eta), 50)), lower_lim, upper_lim
)
# _end_def_
def crossover(self, parent1: Chromosome, parent2: Chromosome) -> Offspring:
"""
Perform the crossover operation on the two input parent chromosomes.
:param parent1: (Chromosome).
:param parent2: (Chromosome).
:return: child1 and child2 (as Chromosomes).
"""
# If the crossover probability is higher than a uniformly
# random value and the parents aren't identical apply the
# changes.
if self.is_operator_applicable() and (parent1 != parent2):
# Extract the values from the placeholder.
eta, x_lower, x_upper = self._items
# Create the 1st offspring genome list.
child_1: list[Gene] = parent1.clone_genome()
# Create the 2nd offspring genome list.
child_2: list[Gene] = parent2.clone_genome()
# Find the minimum length of the two chromosomes.
min_length: int = min(len(child_1), len(child_2))
for i in range(min_length):
# Extract gene values from both parents.
x1: float = child_1[i].value
x2: float = child_2[i].value
# Skip if genes are (almost) identical.
if isclose(x1, x2, rel_tol=1.0e-9, abs_tol=1.0e-15):
continue
# _end_if_
# Initialize boolean flag.
swapped: bool = False
# Ensure x1 <= x2 for consistency.
if x1 > x2:
# Swap in place.
x1, x2 = x2, x1
# Swap the flag.
swapped = True
# _end_if_
# Compute the difference between the
# two gene values.
denominator: float = x2 - x1
# Make the condition scale aware.
scale = max(1.0, abs(x1), abs(x2))
if fabs(denominator) <= 1.0e-15 * scale:
continue
# Local bounds lookups.
xl: float = x_lower[i]
xu: float = x_upper[i]
# Compute both distance factors to lower and upper bounds.
beta1: float = 1.0 + (2.0 * (x1 - xl) / denominator)
beta2: float = 1.0 + (2.0 * (xu - x2) / denominator)
# Precompute repeated variables once.
eta_1: float = eta + 1.0
inv_eta_1: float = 1.0 / eta_1
# Compute separate alpha values for balancing distributions.
alpha1: float = 2.0 - (beta1 ** -eta_1)
alpha2: float = 2.0 - (beta2 ** -eta_1)
# Draw one random number to generate BOTH children.
rand: float = self.rng.random()
# Sample beta_q1 based on lower bound proximity.
if rand <= (1.0 / alpha1):
beta_q1: float = (rand * alpha1) ** inv_eta_1
else:
beta_q1: float = (1.0 / (2.0 - rand * alpha1)) ** inv_eta_1
# Sample beta_q2 based on upper bound proximity.
if rand <= (1.0 / alpha2):
beta_q2: float = (rand * alpha2) ** inv_eta_1
else:
beta_q2: float = (1.0 / (2.0 - rand * alpha2)) ** inv_eta_1
# Precompute repeated variable once.
x1_plus_x2: float = x1 + x2
# Apply the correct distinct scaling factors to each child.
c1: float = 0.5 * (x1_plus_x2 - beta_q1 * denominator)
c2: float = 0.5 * (x1_plus_x2 + beta_q2 * denominator)
# Safe clipping.
c1 = max(xl, min(c1, xu))
c2 = max(xl, min(c2, xu))
# Update children's genomes.
child_1[i].value = c2 if swapped else c1
child_2[i].value = c1 if swapped else c2
# _end_for_
# Increase the crossover counter.
self.inc_counter()
# Return two new offsprings.
return Chromosome(child_1), Chromosome(child_2)
# _end_if_
# Return two cloned offsprings.
return parent1.clone(), parent2.clone()
# _end_def_
# _end_class_