@@ -1145,7 +1145,17 @@ def cal_pop_fitness(self):
11451145 pop_fitness = []
11461146 # Calculating the fitness value of each solution in the current population.
11471147 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 )
11491159 pop_fitness .append (fitness )
11501160
11511161 pop_fitness = numpy .array (pop_fitness )
@@ -1174,7 +1184,7 @@ def run(self):
11741184 # Appending the best solution in the initial population to the best_solutions list.
11751185 if self .save_best_solutions :
11761186 self .best_solutions .append (best_solution )
1177-
1187+
11781188 # Appending the solutions in the initial population to the solutions list.
11791189 if self .save_solutions :
11801190 self .solutions .extend (self .population .copy ())
@@ -1377,7 +1387,7 @@ def tournament_selection(self, fitness, num_parents):
13771387 parents = numpy .empty ((num_parents , self .population .shape [1 ]), dtype = self .gene_type [0 ])
13781388 else :
13791389 parents = numpy .empty ((num_parents , self .population .shape [1 ]), dtype = object )
1380-
1390+
13811391 parents_indices = []
13821392
13831393 for parent_num in range (num_parents ):
0 commit comments