def manage_preferences(self, preference=None): """Run the interruption phase of EA. Use this phase to make changes to RVEA.params or other objects. Updates Reference Vectors (adaptation), conducts interaction with the user. """ if preference is None: msg = "Giving preferences is mandatory" raise eaError(msg) if not isinstance(preference, ReferencePointPreference): msg = (f"Wrong object sent as preference. Expected type = " f"{type(ReferencePointPreference)} or None\n" f"Recieved type = {type(preference)}") raise eaError(msg) if preference.request_id != self._interaction_request_id: msg = (f"Wrong preference object sent. Expected id = " f"{self._interaction_request_id}.\n" f"Recieved id = {preference.request_id}") raise eaError(msg) refpoint = preference.response.values * self.population.problem._max_multiplier self._preference = refpoint scalarized_space_fitness = np.asarray([ scalar(self.population.fitness, self._preference) for scalar in self.scalarization_methods ]).T self.reference_vectors.adapt(scalarized_space_fitness) self.reference_vectors.neighbouring_angles()
def manage_preferences(self, preference=None): """Run the interruption phase of EA. Conducts the interaction with the user. """ # start only with reference point reference as in article if (self.interact is False): return if preference is None: msg = "Giving preferences is mandatory" raise eaError(msg) if not isinstance(preference, ReferencePointPreference): msg = (f"Wrong object sent as preference. Expected type = " f"{type(ReferencePointPreference)}\n" f"Recieved type = {type(preference)}") raise eaError(msg) if preference is not None: if preference.request_id != self._interaction_request_id: msg = (f"Wrong preference object sent. Expected id = " f"{self._interaction_request_id}.\n" f"Recieved id = {preference.request_id}") raise eaError(msg) if preference is not None: self.reference_point = preference.response.values * self.population.problem._max_multiplier # TODO: there was thing about doing this but i think i do already. self.n_iterations += self.n_iterations self.total_function_evaluations += self.total_function_evaluations
def __init__( self, problem, initial_population: Population, n_gen_per_iter: int = 10, n_iterations: int = 10, tournament_size: int = 5, population_size: int = 500, ): """Run generations of evolutionary algorithm using tournament selection. Parameters ---------- population : "Population" This variable is updated as evolution takes place ea_parameters : dict Takes the EA parameters. Returns ------- Population: Returns the Population after evolution. """ super().__init__(n_gen_per_iter=n_gen_per_iter, n_iterations=n_iterations) if initial_population is None: msg = "Provide initial population" raise eaError(msg) self.population = initial_population self.target_pop_size = population_size self.tournament_size = tournament_size selection_operator = TournamentSelection(self.population, self.tournament_size) self.selection_operator = selection_operator
def move_prey(self): """Find an empty position in prey neighbourhood for the prey to move in, and choose a mate for breeding if any available. Returns ------- mating_pop : list List of parent indices to use for mating """ mating_pop = [] for prey, pos in enumerate(self.preys_loc): if np.random.random() < self.prob_prey_move: for i in range(self.prey_max_moves): neighbours = self.neighbours(self.lattice, pos[0], pos[1]) dy = np.random.randint(neighbours.shape[0]) dx = np.random.randint(neighbours.shape[1]) # If neighbouring cell is occupied, skip turn if neighbours[dy][dx] != 0: continue dest_y = dy - 1 + pos[0] dest_x = dx - 1 + pos[1] # Check boundaries of the lattice if dest_y not in range(self.size_y) or dest_x not in range( self.size_x): dest_y, dest_x = self.lattice_wrap_idx( (dest_y, dest_x), np.shape(self.lattice)) # Move prey, clear previous location self.lattice[dest_y][dest_x] = int(prey + 1) self.lattice[pos[0]][pos[1]] = 0 # Update prey location in the list pos[0], pos[1] = dest_y, dest_x neighbours = self.neighbours(self.lattice, self.preys_loc[prey][0], self.preys_loc[prey][1]) mates = neighbours[(neighbours > 0) & (neighbours != prey + 1)] if len(mates) < 1: continue else: # -1 for lattice offset mate = int(choice(mates)) - 1 mating_pop.append([prey, mate]) if mating_pop == []: raise eaError("What's ahppening?!") return mating_pop
def manage_preferences(self, preference=None): """Run the interruption phase of EA. Use this phase to make changes to RVEA.params or other objects. Updates Reference Vectors (adaptation), conducts interaction with the user. """ if not isinstance(preference, (ReferencePointPreference, type(None))): msg = (f"Wrong object sent as preference. Expected type = " f"{type(ReferencePointPreference)} or None\n" f"Recieved type = {type(preference)}") raise eaError(msg) if preference is not None: if preference.request_id != self._interaction_request_id: msg = (f"Wrong preference object sent. Expected id = " f"{self._interaction_request_id}.\n" f"Recieved id = {preference.request_id}") raise eaError(msg) if preference is None and not self._ref_vectors_are_focused: self.reference_vectors.adapt(self.population.fitness) if preference is not None: ideal = self.population.ideal_fitness_val #fitness_vals = self.population.ob refpoint_actual = (preference.response.values * self.population.problem._max_multiplier) refpoint = refpoint_actual - ideal norm = np.sqrt(np.sum(np.square(refpoint))) refpoint = refpoint / norm """ # evaluate alpha_k cos_theta_f_k = self.reference_vectors.find_cos_theta_f_k(refpoint_actual, self.population, self.objs_interation_end, self.unc_interaction_end) # adapt reference vectors self.reference_vectors.interactive_adapt_offline_adaptive(refpoint, cos_theta_f_k) """ #self.reference_vectors.iteractive_adapt_1(refpoint) self.reference_vectors.add_edge_vectors() self.reference_vectors.neighbouring_angles()
def __init__( self, problem, population_size: int = 100, population_params=None, initial_population=None, n_iterations: int = 10, n_gen_per_iter: int = 10, predator_pop_size: int = 50, prey_max_moves: int = 10, prob_prey_move: float = 0.3, offspring_place_attempts: int = 10, kill_interval: int = 7, max_rank: int = 20, neighbourhood_radius: int = 3, ): super().__init__(n_gen_per_iter=n_gen_per_iter, n_iterations=n_iterations) if initial_population is None: msg = "Provide initial population" raise eaError(msg) self.population = initial_population self.target_pop_size = population_size self.predator_pop_size: int = predator_pop_size self.prey_max_moves: int = prey_max_moves self.prob_prey_move: float = prob_prey_move self.offspring_place_attempts: int = offspring_place_attempts self.kill_interval: int = kill_interval self.max_rank: int = max_rank self.neighbourhood_radius: int = neighbourhood_radius self.lattice = Lattice( size_x=60, size_y=60, population=self.population, predator_pop_size=predator_pop_size, target_pop_size=self.target_pop_size, prob_prey_move=prob_prey_move, prey_max_moves=prey_max_moves, offspring_place_attempts=offspring_place_attempts, neighbourhood_radius=neighbourhood_radius, )
def __init__( self, problem: MOProblem, population_size: int = None, population_params: Dict = None, initial_population: Population = None, alpha: float = None, lattice_resolution: int = None, n_iterations: int = 10, n_gen_per_iter: int = 100, total_function_evaluations: int = 0, time_penalty_component: Union[str, float] = None, use_surrogates: bool = False, ): super().__init__( problem=problem, population_size=population_size, population_params=population_params, initial_population=initial_population, lattice_resolution=lattice_resolution, n_iterations=n_iterations, n_gen_per_iter=n_gen_per_iter, total_function_evaluations=total_function_evaluations, use_surrogates=use_surrogates, ) self.time_penalty_component = time_penalty_component time_penalty_component_options = [ "original", "function_count", "interactive" ] if time_penalty_component is None: if self.interact is True: time_penalty_component = "interactive" elif total_function_evaluations > 0: time_penalty_component = "function_count" else: time_penalty_component = "original" if not (type(time_penalty_component) is float or str): msg = (f"type(time_penalty_component) should be float or str" f"Provided type: {type(time_penalty_component)}") eaError(msg) if type(time_penalty_component) is float: if (time_penalty_component <= 0) or (time_penalty_component >= 1): msg = ( f"time_penalty_component should either be a float in the range" f"[0, 1], or one of {time_penalty_component_options}.\n" f"Provided value = {time_penalty_component}") eaError(msg) time_penalty_function = self._time_penalty_constant if type(time_penalty_component) is str: if time_penalty_component == "original": time_penalty_function = self._time_penalty_original elif time_penalty_component == "function_count": time_penalty_function = self._time_penalty_function_count elif time_penalty_component == "interactive": time_penalty_function = self._time_penalty_interactive else: msg = ( f"time_penalty_component should either be a float in the range" f"[0, 1], or one of {time_penalty_component_options}.\n" f"Provided value = {time_penalty_component}") eaError(msg) self.time_penalty_function = time_penalty_function self.alpha = alpha selection_operator = IOPIS_APD_Select(self.time_penalty_function, self.scalarization_methods, self.alpha) self.selection_operator = selection_operator
def __init__( self, problem: MOProblem, population_size: int = None, population_params: Dict = None, initial_population: Population = None, lattice_resolution: int = None, n_iterations: int = 10, n_gen_per_iter: int = 100, total_function_evaluations: int = 0, use_surrogates: bool = False, ): a_priori: bool = True interact: bool = True if problem.ideal is None or problem.nadir is None: msg = ( f"The problem instance should contain the information about ideal and " f"nadir point.") raise eaError(msg) BaseEA.__init__( self=self, a_priori=a_priori, interact=interact, n_iterations=n_iterations, n_gen_per_iter=n_gen_per_iter, total_function_evaluations=total_function_evaluations, use_surrogates=use_surrogates, ) scalarization_methods = [ StomASF(ideal=problem.ideal * problem._max_multiplier), # PointMethodASF( # nadir=problem.nadir * problem._max_multiplier, # ideal=problem.ideal * problem._max_multiplier, # ), AugmentedGuessASF( nadir=problem.nadir * problem._max_multiplier, ideal=problem.ideal * problem._max_multiplier, indx_to_exclude=[], ), ] if lattice_resolution is None: lattice_res_options = [49, 13, 7, 5, 4, 3, 3, 3, 3] if len(scalarization_methods) < 11: lattice_resolution = lattice_res_options[ len(scalarization_methods) - 2] else: lattice_resolution = 3 reference_vectors = ReferenceVectors( lattice_resolution=lattice_resolution, number_of_objectives=len(scalarization_methods), ) population_size = reference_vectors.number_of_vectors population = Population(problem, population_size, population_params) self.reference_vectors = reference_vectors self.scalarization_methods = scalarization_methods if initial_population is not None: # Population should be compatible. self.population = initial_population # TODO put checks here. elif initial_population is None: if population_size is None: population_size = self.reference_vectors.number_of_vectors self.population = Population(problem, population_size, population_params, use_surrogates) self._function_evaluation_count += population_size self._ref_vectors_are_focused: bool = False