1
1
from collections .abc import Callable # Fixes the UP035 warning
2
2
import numpy as np
3
3
4
+
4
5
class GeneticAlgorithmOptimizer :
5
6
def __init__ (
6
7
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 ]],
9
10
population_size : int = 100 ,
10
11
max_generations : int = 500 ,
11
12
crossover_probability : float = 0.9 ,
@@ -61,8 +62,12 @@ def perform_crossover(
61
62
62
63
if self .rng .random () < self .crossover_probability :
63
64
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
+ )
66
71
return child1 , child2
67
72
return parent1 , parent2
68
73
@@ -73,8 +78,8 @@ def apply_mutation(self, individual: np.ndarray) -> np.ndarray:
73
78
if self .rng .random () < self .mutation_probability :
74
79
mutation_index = self .rng .integers (0 , self .num_variables )
75
80
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 ],
78
83
)
79
84
return individual
80
85
@@ -108,11 +113,15 @@ def optimize(self) -> tuple[np.ndarray, float]:
108
113
best_fitness_value = fitness_values [min_fitness_index ]
109
114
best_solution = population [min_fitness_index ]
110
115
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
+ )
112
119
113
120
return best_solution , best_fitness_value
114
121
122
+
115
123
if __name__ == "__main__" :
124
+
116
125
def objective_function (x : float , y : float ) -> float :
117
126
"""
118
127
Example objective function to minimize x^2 + y^2
@@ -122,8 +131,7 @@ def objective_function(x: float, y: float) -> float:
122
131
variable_bounds : list [tuple [float , float ]] = [(- 10 , 10 ), (- 10 , 10 )]
123
132
124
133
optimizer = GeneticAlgorithmOptimizer (
125
- objective_function = objective_function ,
126
- variable_bounds = variable_bounds
134
+ objective_function = objective_function , variable_bounds = variable_bounds
127
135
)
128
136
best_solution , best_fitness_value = optimizer .optimize ()
129
137
0 commit comments