1
1
from collections .abc import Callable # Sorted import
2
2
import numpy as np # Sorted import
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 ,
@@ -58,8 +59,12 @@ def perform_crossover(
58
59
59
60
if self .rng .random () < self .crossover_probability :
60
61
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
+ )
63
68
return child1 , child2
64
69
return parent1 , parent2
65
70
@@ -71,7 +76,7 @@ def apply_mutation(self, individual: np.ndarray) -> np.ndarray:
71
76
mutation_index = self .rng .integers (0 , self .num_variables )
72
77
individual [mutation_index ] = self .rng .uniform (
73
78
self .variable_bounds [mutation_index , 0 ],
74
- self .variable_bounds [mutation_index , 1 ]
79
+ self .variable_bounds [mutation_index , 1 ],
75
80
)
76
81
return individual
77
82
@@ -105,11 +110,15 @@ def optimize(self) -> tuple[np.ndarray, float]:
105
110
best_fitness_value = fitness_values [min_fitness_index ]
106
111
best_solution = population [min_fitness_index ]
107
112
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
+ )
109
116
110
117
return best_solution , best_fitness_value
111
118
119
+
112
120
if __name__ == "__main__" :
121
+
113
122
def objective_function (x : float , y : float ) -> float :
114
123
"""
115
124
Example objective function to minimize x^2 + y^2
@@ -119,8 +128,7 @@ def objective_function(x: float, y: float) -> float:
119
128
variable_bounds : list [tuple [float , float ]] = [(- 10 , 10 ), (- 10 , 10 )]
120
129
121
130
optimizer = GeneticAlgorithmOptimizer (
122
- objective_function = objective_function ,
123
- variable_bounds = variable_bounds
131
+ objective_function = objective_function , variable_bounds = variable_bounds
124
132
)
125
133
best_solution , best_fitness_value = optimizer .optimize ()
126
134
0 commit comments