@@ -1145,7 +1145,17 @@ def cal_pop_fitness(self):
1145
1145
pop_fitness = []
1146
1146
# Calculating the fitness value of each solution in the current population.
1147
1147
for sol_idx , sol in enumerate (self .population ):
1148
- fitness = self .fitness_func (sol , sol_idx )
1148
+
1149
+ # Check if the parent's fitness value is already calculated. If so, use it instead of calling the fitness function.
1150
+ if not (self .last_generation_parents is None ) and len (numpy .where (numpy .all (self .last_generation_parents == sol , axis = 1 ))[0 ] > 0 ):
1151
+ # Index of the parent in the parents array (self.last_generation_parents). This is not its index within the population.
1152
+ parent_idx = numpy .where (numpy .all (self .last_generation_parents == sol , axis = 1 ))[0 ][0 ]
1153
+ # Index of the parent in the population.
1154
+ parent_idx = self .last_generation_parents_indices [parent_idx ]
1155
+ # Use the parent's index to return its pre-calculated fitness value.
1156
+ fitness = self .last_generation_fitness [parent_idx ]
1157
+ else :
1158
+ fitness = self .fitness_func (sol , sol_idx )
1149
1159
pop_fitness .append (fitness )
1150
1160
1151
1161
pop_fitness = numpy .array (pop_fitness )
@@ -1174,7 +1184,7 @@ def run(self):
1174
1184
# Appending the best solution in the initial population to the best_solutions list.
1175
1185
if self .save_best_solutions :
1176
1186
self .best_solutions .append (best_solution )
1177
-
1187
+
1178
1188
# Appending the solutions in the initial population to the solutions list.
1179
1189
if self .save_solutions :
1180
1190
self .solutions .extend (self .population .copy ())
@@ -1377,7 +1387,7 @@ def tournament_selection(self, fitness, num_parents):
1377
1387
parents = numpy .empty ((num_parents , self .population .shape [1 ]), dtype = self .gene_type [0 ])
1378
1388
else :
1379
1389
parents = numpy .empty ((num_parents , self .population .shape [1 ]), dtype = object )
1380
-
1390
+
1381
1391
parents_indices = []
1382
1392
1383
1393
for parent_num in range (num_parents ):
0 commit comments