Skip to content

Commit 0b06dae

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent 5ff30a6 commit 0b06dae

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

genetic_algorithm/genetic_algorithm_optimization.py

+17-9
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
from collections.abc import Callable # Fixes the UP035 warning
22
import numpy as np
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,
@@ -61,8 +62,12 @@ def perform_crossover(
6162

6263
if self.rng.random() < self.crossover_probability:
6364
crossover_point = self.rng.integers(1, self.num_variables)
64-
child1 = np.concatenate((parent1[:crossover_point], parent2[crossover_point:]))
65-
child2 = np.concatenate((parent2[:crossover_point], parent1[crossover_point:]))
65+
child1 = np.concatenate(
66+
(parent1[:crossover_point], parent2[crossover_point:])
67+
)
68+
child2 = np.concatenate(
69+
(parent2[:crossover_point], parent1[crossover_point:])
70+
)
6671
return child1, child2
6772
return parent1, parent2
6873

@@ -73,8 +78,8 @@ def apply_mutation(self, individual: np.ndarray) -> np.ndarray:
7378
if self.rng.random() < self.mutation_probability:
7479
mutation_index = self.rng.integers(0, self.num_variables)
7580
individual[mutation_index] = self.rng.uniform(
76-
self.variable_bounds[mutation_index, 0],
77-
self.variable_bounds[mutation_index, 1]
81+
self.variable_bounds[mutation_index, 0],
82+
self.variable_bounds[mutation_index, 1],
7883
)
7984
return individual
8085

@@ -108,11 +113,15 @@ def optimize(self) -> tuple[np.ndarray, float]:
108113
best_fitness_value = fitness_values[min_fitness_index]
109114
best_solution = population[min_fitness_index]
110115

111-
print(f"Generation {generation + 1}, Best Fitness Value: {best_fitness_value}")
116+
print(
117+
f"Generation {generation + 1}, Best Fitness Value: {best_fitness_value}"
118+
)
112119

113120
return best_solution, best_fitness_value
114121

122+
115123
if __name__ == "__main__":
124+
116125
def objective_function(x: float, y: float) -> float:
117126
"""
118127
Example objective function to minimize x^2 + y^2
@@ -122,8 +131,7 @@ def objective_function(x: float, y: float) -> float:
122131
variable_bounds: list[tuple[float, float]] = [(-10, 10), (-10, 10)]
123132

124133
optimizer = GeneticAlgorithmOptimizer(
125-
objective_function=objective_function,
126-
variable_bounds=variable_bounds
134+
objective_function=objective_function, variable_bounds=variable_bounds
127135
)
128136
best_solution, best_fitness_value = optimizer.optimize()
129137

0 commit comments

Comments
 (0)