@@ -60,10 +60,7 @@ def initialize_population(self) -> list[np.ndarray]:
60
60
True
61
61
"""
62
62
return [
63
- rng .uniform (
64
- low = [self .bounds [j ][0 ] for j in range (self .dim )],
65
- high = [self .bounds [j ][1 ] for j in range (self .dim )],
66
- )
63
+ np .array ([rng .uniform (b [0 ], b [1 ]) for b in self .bounds ])
67
64
for _ in range (self .population_size )
68
65
]
69
66
@@ -122,6 +119,10 @@ def select_parents(
122
119
# Parent 2 should be [-1.0, -2.0]
123
120
True
124
121
"""
122
+
123
+ if not population_score :
124
+ raise ValueError ("Population score is empty, cannot select parents." )
125
+
125
126
population_score .sort (key = lambda score_tuple : score_tuple [1 ], reverse = True )
126
127
selected_count = min (N_SELECTED , len (population_score ))
127
128
return [ind for ind , _ in population_score [:selected_count ]]
@@ -244,30 +245,32 @@ def evolve(self, verbose: bool = True) -> np.ndarray:
244
245
for generation in range (self .generations ):
245
246
# Evaluate population fitness (multithreaded)
246
247
population_score = self .evaluate_population ()
247
-
248
+
249
+ # Ensure population_score isn't empty
250
+ if not population_score :
251
+ raise ValueError ("Population score is empty. No individuals evaluated." )
252
+
248
253
# Check the best individual
249
- best_individual = max (
250
- population_score , key = lambda score_tuple : score_tuple [1 ]
251
- )[0 ]
254
+ best_individual = max (population_score , key = lambda score_tuple : score_tuple [1 ])[0 ]
252
255
best_fitness = self .fitness (best_individual )
253
-
256
+
254
257
# Select parents for next generation
255
258
parents = self .select_parents (population_score )
256
259
next_generation = []
257
-
260
+
258
261
# Generate offspring using crossover and mutation
259
262
for i in range (0 , len (parents ), 2 ):
260
- parent1 , parent2 = parents [i ], parents [(i + 1 ) % len (parents )]
263
+ parent1 , parent2 = parents [i ], parents [(i + 1 ) % len (parents )] # Wrap around for odd cases
261
264
child1 , child2 = self .crossover (parent1 , parent2 )
262
265
next_generation .append (self .mutate (child1 ))
263
266
next_generation .append (self .mutate (child2 ))
264
-
267
+
265
268
# Ensure population size remains the same
266
269
self .population = next_generation [: self .population_size ]
267
-
270
+
268
271
if verbose and generation % 10 == 0 :
269
272
print (f"Generation { generation } : Best Fitness = { best_fitness } " )
270
-
273
+
271
274
return best_individual
272
275
273
276
0 commit comments