def __get_child(self, other): child_solution_cities = [] # Add required cities child_solution_cities += self.required_cities # Add cities present in both parents for city_parent_1 in self.solution.cities: if city_parent_1 in other.solution.cities: if city_parent_1 not in child_solution_cities: child_solution_cities.append(city_parent_1) # Get random sample of cities from parent 1 and add them to child if not already present parent_solution_cities = [] if len(self.solution.cities) > 0: parent_solution_cities = random.sample( self.solution.cities, random.randint(1, len(self.solution.cities))) random.shuffle(parent_solution_cities) for parent_solution_city in parent_solution_cities: if parent_solution_city in child_solution_cities: continue child_solution_cities.append(parent_solution_city) # Get random sample of cities from parent 2 and add them to child if not already present parent_solution_cities = [] if len(other.solution.cities) > 0: parent_solution_cities = random.sample( other.solution.cities, random.randint(1, len(other.solution.cities))) random.shuffle(parent_solution_cities) for parent_solution_city in parent_solution_cities: if parent_solution_city in child_solution_cities: continue child_solution_cities.append(parent_solution_city) # Get child solution child_solution = Solution(self.origin_city, child_solution_cities, self.required_cities, self.max_trip_time) # Optimize tsp optimizer = TSPOptimizerClosestCityStrategy(self.origin_city, child_solution.cities) child_solution.cities = optimizer.optimize() # Delete random cities until solution is valid while not child_solution.is_valid_total_trip_time(): self.solution_delete_city(child_solution) # Optimize the tsp part of the solution optimizer = TSPOptimizerClosestCityStrategy( self.origin_city, child_solution.cities) child_solution.cities = optimizer.optimize() child_solution.update_fitness() child_individual = Individual(self.origin_city, self.possible_cities, self.required_cities, self.max_trip_time, child_solution) return child_individual
def solve(self): # Add all required cities solution = Solution(self.origin_city, list(self.required_cities), self.required_cities, self.max_trip_time) solution.update_fitness() if not solution.is_valid(): raise Exception() # Compute ratios ratios = [] for city in self.possible_trip_cities: if city in self.required_cities: continue ratios.append([city, city.value / city.stay_time]) ratios.sort(reverse=True, key=lambda x: x[1]) # Add city until knapsack is full for r in ratios: city = r[0] backup = list(solution.cities) solution.cities.append(city) solution.update_fitness() tsp_optimizer = TSPOptimizerClosestCityStrategy( self.origin_city, solution.cities) solution.cities = tsp_optimizer.optimize() if not solution.is_valid_total_trip_time(): solution.cities = backup solution.update_fitness() break self.improve_solution(solution) return solution