|
1 | 1 | import random
|
2 | 2 | from collections.abc import Callable, Sequence
|
3 | 3 | from concurrent.futures import ThreadPoolExecutor
|
| 4 | + |
4 | 5 | import numpy as np
|
5 | 6 |
|
6 | 7 | # Parameters
|
@@ -82,10 +83,10 @@ def fitness(self, individual: np.ndarray) -> float:
|
82 | 83 | ... )
|
83 | 84 | >>> individual = np.array([1.0, 2.0])
|
84 | 85 | >>> ga.fitness(individual)
|
85 |
| - 5.0 # The fitness should be 1^2 + 2^2 = 5 |
| 86 | + -5.0 # The fitness should be -1^2 + 2^2 = 5 for minimizing |
86 | 87 | >>> ga.maximize = True
|
87 | 88 | >>> ga.fitness(individual)
|
88 |
| - -5.0 # The fitness should be -5 when maximizing |
| 89 | + 5.0 # The fitness should be 1^2 + 2^2 = 5 when maximizing |
89 | 90 | """
|
90 | 91 | value = float(self.function(*individual)) # Ensure fitness is a float
|
91 | 92 | return value if self.maximize else -value # If minimizing, invert the fitness
|
@@ -114,9 +115,11 @@ def select_parents(
|
114 | 115 | >>> selected_parents = ga.select_parents(population_score)
|
115 | 116 | >>> len(selected_parents)
|
116 | 117 | 2 # Should select the two parents with the best fitness scores.
|
117 |
| - >>> np.array_equal(selected_parents[0], np.array([1.0, 2.0])) # Parent 1 should be [1.0, 2.0] |
| 118 | + >>> np.array_equal(selected_parents[0], np.array([1.0, 2.0])) |
| 119 | + # Parent 1 should be [1.0, 2.0] |
118 | 120 | True
|
119 |
| - >>> np.array_equal(selected_parents[1], np.array([-1.0, -2.0])) # Parent 2 should be [-1.0, -2.0] |
| 121 | + >>> np.array_equal(selected_parents[1], np.array([-1.0, -2.0])) |
| 122 | + # Parent 2 should be [-1.0, -2.0] |
120 | 123 | True
|
121 | 124 | """
|
122 | 125 | population_score.sort(key=lambda score_tuple: score_tuple[1], reverse=True)
|
@@ -237,6 +240,7 @@ def evolve(self, verbose: bool = True) -> np.ndarray:
|
237 | 240 | >>> isinstance(best_solution[1], float) # Second element should be a float
|
238 | 241 | True
|
239 | 242 | """
|
| 243 | + best_individual = None |
240 | 244 | for generation in range(self.generations):
|
241 | 245 | # Evaluate population fitness (multithreaded)
|
242 | 246 | population_score = self.evaluate_population()
|
|
0 commit comments