@@ -122,7 +122,7 @@ def select_parents(
122
122
123
123
if not population_score :
124
124
raise ValueError ("Population score is empty, cannot select parents." )
125
-
125
+
126
126
population_score .sort (key = lambda score_tuple : score_tuple [1 ], reverse = True )
127
127
selected_count = min (N_SELECTED , len (population_score ))
128
128
return [ind for ind , _ in population_score [:selected_count ]]
@@ -245,32 +245,37 @@ def evolve(self, verbose: bool = True) -> np.ndarray:
245
245
for generation in range (self .generations ):
246
246
# Evaluate population fitness (multithreaded)
247
247
population_score = self .evaluate_population ()
248
-
248
+
249
249
# Ensure population_score isn't empty
250
250
if not population_score :
251
251
raise ValueError ("Population score is empty. No individuals evaluated." )
252
-
252
+
253
253
# Check the best individual
254
- best_individual = max (population_score , key = lambda score_tuple : score_tuple [1 ])[0 ]
254
+ best_individual = max (
255
+ population_score , key = lambda score_tuple : score_tuple [1 ]
256
+ )[0 ]
255
257
best_fitness = self .fitness (best_individual )
256
-
258
+
257
259
# Select parents for next generation
258
260
parents = self .select_parents (population_score )
259
261
next_generation = []
260
-
262
+
261
263
# Generate offspring using crossover and mutation
262
264
for i in range (0 , len (parents ), 2 ):
263
- parent1 , parent2 = parents [i ], parents [(i + 1 ) % len (parents )] # Wrap around for odd cases
265
+ parent1 , parent2 = (
266
+ parents [i ],
267
+ parents [(i + 1 ) % len (parents )],
268
+ ) # Wrap around for odd cases
264
269
child1 , child2 = self .crossover (parent1 , parent2 )
265
270
next_generation .append (self .mutate (child1 ))
266
271
next_generation .append (self .mutate (child2 ))
267
-
272
+
268
273
# Ensure population size remains the same
269
274
self .population = next_generation [: self .population_size ]
270
-
275
+
271
276
if verbose and generation % 10 == 0 :
272
277
print (f"Generation { generation } : Best Fitness = { best_fitness } " )
273
-
278
+
274
279
return best_individual
275
280
276
281
0 commit comments