Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 84b29c0

Browse files
authoredNov 15, 2024··
Update genetic_algorithm_optimization.py
1 parent dbd29ae commit 84b29c0

File tree

1 file changed

+17
-14
lines changed

1 file changed

+17
-14
lines changed
 

‎genetic_algorithm/genetic_algorithm_optimization.py

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,7 @@ def initialize_population(self) -> list[np.ndarray]:
6060
True
6161
"""
6262
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])
6764
for _ in range(self.population_size)
6865
]
6966

@@ -122,6 +119,10 @@ def select_parents(
122119
# Parent 2 should be [-1.0, -2.0]
123120
True
124121
"""
122+
123+
if not population_score:
124+
raise ValueError("Population score is empty, cannot select parents.")
125+
125126
population_score.sort(key=lambda score_tuple: score_tuple[1], reverse=True)
126127
selected_count = min(N_SELECTED, len(population_score))
127128
return [ind for ind, _ in population_score[:selected_count]]
@@ -244,30 +245,32 @@ def evolve(self, verbose: bool = True) -> np.ndarray:
244245
for generation in range(self.generations):
245246
# Evaluate population fitness (multithreaded)
246247
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+
248253
# 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]
252255
best_fitness = self.fitness(best_individual)
253-
256+
254257
# Select parents for next generation
255258
parents = self.select_parents(population_score)
256259
next_generation = []
257-
260+
258261
# Generate offspring using crossover and mutation
259262
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
261264
child1, child2 = self.crossover(parent1, parent2)
262265
next_generation.append(self.mutate(child1))
263266
next_generation.append(self.mutate(child2))
264-
267+
265268
# Ensure population size remains the same
266269
self.population = next_generation[: self.population_size]
267-
270+
268271
if verbose and generation % 10 == 0:
269272
print(f"Generation {generation}: Best Fitness = {best_fitness}")
270-
273+
271274
return best_individual
272275

273276

0 commit comments

Comments
 (0)
Please sign in to comment.