Skip to content

Commit 57feaea

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent 796d80b commit 57feaea

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

genetic_algorithm/genetic_algorithm_optimization.py

+16-8
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
from collections.abc import Callable # Sorted import
22
import numpy as np # Sorted import
33

4+
45
class GeneticAlgorithmOptimizer:
56
def __init__(
67
self,
7-
objective_function: Callable[..., float],
8-
variable_bounds: list[tuple[float, float]],
8+
objective_function: Callable[..., float],
9+
variable_bounds: list[tuple[float, float]],
910
population_size: int = 100,
1011
max_generations: int = 500,
1112
crossover_probability: float = 0.9,
@@ -58,8 +59,12 @@ def perform_crossover(
5859

5960
if self.rng.random() < self.crossover_probability:
6061
crossover_point = self.rng.integers(1, self.num_variables)
61-
child1 = np.concatenate((parent1[:crossover_point], parent2[crossover_point:]))
62-
child2 = np.concatenate((parent2[:crossover_point], parent1[crossover_point:]))
62+
child1 = np.concatenate(
63+
(parent1[:crossover_point], parent2[crossover_point:])
64+
)
65+
child2 = np.concatenate(
66+
(parent2[:crossover_point], parent1[crossover_point:])
67+
)
6368
return child1, child2
6469
return parent1, parent2
6570

@@ -71,7 +76,7 @@ def apply_mutation(self, individual: np.ndarray) -> np.ndarray:
7176
mutation_index = self.rng.integers(0, self.num_variables)
7277
individual[mutation_index] = self.rng.uniform(
7378
self.variable_bounds[mutation_index, 0],
74-
self.variable_bounds[mutation_index, 1]
79+
self.variable_bounds[mutation_index, 1],
7580
)
7681
return individual
7782

@@ -105,11 +110,15 @@ def optimize(self) -> tuple[np.ndarray, float]:
105110
best_fitness_value = fitness_values[min_fitness_index]
106111
best_solution = population[min_fitness_index]
107112

108-
print(f"Generation {generation + 1}, Best Fitness Value: {best_fitness_value}")
113+
print(
114+
f"Generation {generation + 1}, Best Fitness Value: {best_fitness_value}"
115+
)
109116

110117
return best_solution, best_fitness_value
111118

119+
112120
if __name__ == "__main__":
121+
113122
def objective_function(x: float, y: float) -> float:
114123
"""
115124
Example objective function to minimize x^2 + y^2
@@ -119,8 +128,7 @@ def objective_function(x: float, y: float) -> float:
119128
variable_bounds: list[tuple[float, float]] = [(-10, 10), (-10, 10)]
120129

121130
optimizer = GeneticAlgorithmOptimizer(
122-
objective_function=objective_function,
123-
variable_bounds=variable_bounds
131+
objective_function=objective_function, variable_bounds=variable_bounds
124132
)
125133
best_solution, best_fitness_value = optimizer.optimize()
126134

0 commit comments

Comments
 (0)