culebra.trainer.ea.SimpleEA class¶
- class SimpleEA(solution_cls: type[Individual], species: Species, fitness_function: FitnessFunction, max_num_iters: int | None = None, custom_termination_func: Callable[[SinglePopEA], bool] | None = None, pop_size: int | None = None, crossover_func: Callable[[Individual, Individual], tuple[Individual, Individual]] | None = None, mutation_func: Callable[[Individual, float], tuple[Individual]] | None = None, selection_func: Callable[[list[Individual], int, Any], list[Individual]] | None = None, crossover_prob: float | None = None, mutation_prob: float | None = None, gene_ind_mutation_prob: float | None = None, selection_func_params: dict[str, Any] | None = None, checkpoint_activation: bool | None = None, checkpoint_freq: int | None = None, checkpoint_filename: str | None = None, verbosity: bool | None = None, random_seed: int | None = None)¶
Bases:
SinglePopEACreate a new single-population evolutionary trainer.
- Parameters:
solution_cls (type[Individual]) – The individual class
species (Species) – The species for all the individuals
fitness_function (FitnessFunction) – The training fitness function
max_num_iters (int) – Maximum number of iterations. If omitted,
_default_max_num_iterswill be used. Defaults toNonecustom_termination_func (Callable) – Custom termination criterion. If omitted,
_default_termination_func()is used. Defaults toNonepop_size (int) – The population size. If omitted,
_default_pop_sizeis used. Defaults toNonecrossover_func (Callable) – The crossover function. If omitted,
_default_crossover_funcis used. Defaults toNonemutation_func (Callable) – The mutation function. If omitted,
_default_mutation_funcis used. Defaults toNoneselection_func (Callable) – The selection function. If omitted,
_default_selection_funcis used. Defaults toNonecrossover_prob (float) – The crossover probability. If omitted,
_default_crossover_probis used. Defaults toNonemutation_prob (float) – The mutation probability. If omitted,
_default_mutation_probis used. Defaults toNonegene_ind_mutation_prob (float) – The gene independent mutation probability. If omitted,
_default_gene_ind_mutation_probis used. Defaults toNoneselection_func_params (dict) – The parameters for the selection function. If omitted,
_default_selection_func_paramsis used. Defaults toNonecheckpoint_activation (bool) – Checkpoining activation. If omitted,
_default_checkpoint_activationwill be used. Defaults toNonecheckpoint_freq (int) – The checkpoint frequency. If omitted,
_default_checkpoint_freqwill be used. Defaults toNonecheckpoint_filename (str) – The checkpoint file path. If omitted,
_default_checkpoint_filenamewill be used. Defaults toNoneverbosity (bool) – The verbosity. If omitted,
_default_verbositywill be used. Defaults toNone
- Raises:
TypeError – If any argument is not of the appropriate type
ValueError – If any argument has an incorrect value
Class attributes¶
- SimpleEA.objective_stats = {'Avg': <function mean>, 'Max': <function max>, 'Min': <function min>, 'Std': <function std>}¶
Statistics calculated for each objective.
- SimpleEA.stats_names = ('Iter', 'NEvals')¶
Statistics calculated each iteration.
Class methods¶
- classmethod SimpleEA.load(filename: str) Base¶
Load a serialized object from a file.
- Parameters:
filename (str) – The file name.
- Returns:
The loaded object
- Raises:
TypeError – If filename is not a valid file name
ValueError – If the filename extension is not
SERIALIZED_FILE_EXTENSION
Properties¶
- property SimpleEA.checkpoint_filename: str¶
Checkpoint file path.
- Return type:
- Setter:
Modify the checkpoint file path
- Parameters:
value (str) – New value for the checkpoint file path. If set to
None,_default_checkpoint_filenameis chosen- Raises:
TypeError – If value is not a valid file name
ValueError – If the value extension is not
SERIALIZED_FILE_EXTENSION
- property SimpleEA.checkpoint_freq: int¶
Checkpoint frequency.
- Return type:
- Setter:
Modify the checkpoint frequency
- Parameters:
value (int) – New value for the checkpoint frequency. If set to
None,_default_checkpoint_freqis chosen- Raises:
TypeError – If value is not an integer
ValueError – If value is not a positive number
- property SimpleEA.container: Trainer | None¶
Container of this trainer.
The trainer container is only used by distributed trainers. For the rest of trainers defaults to
None.
- property SimpleEA.crossover_func: Callable[[Individual, Individual], tuple[Individual, Individual]]¶
Crossover function.
- Return type:
- Setter:
Set a new crossover function
- Parameters:
func (Callable) – The new crossover function. If omitted,
_default_crossover_funcis chosen- Raises:
TypeError – If func is not callable
- property SimpleEA.crossover_prob: float¶
Crossover probability.
- Return type:
- Setter:
Set a new crossover probability
- Parameters:
prob (float) – The new probability. If omitted,
_default_crossover_probis chosen- Raises:
TypeError – If prob is not a real number
ValueError – If prob is not in (0, 1)
- property SimpleEA.custom_termination_func: Callable[[Trainer], bool] | None¶
Custom termination criterion.
Although the trainer will always stop when the
max_num_itersare reached, a custom termination criterion can be set to detect convergente and stop the trainer earlier. This custom termination criterion must be a function which receives the trainer as its unique argument and returns a boolean value,Trueif the search should terminate orFalseotherwise.If more than one arguments are needed to define the termination condition,
functools.partial()can be used:from functools import partial def my_crit(trainer, max_iters): if trainer.current_iter < max_iters: return False return True trainer.custom_termination_func = partial(my_crit, max_iters=10)
- property SimpleEA.fitness_function: FitnessFunction¶
Training fitness function.
- Return type:
- Setter:
Set a new fitness function
- Parameters:
func (FitnessFunction) – The new training fitness function
- Raises:
TypeError – If func is not a valid fitness function
- property SimpleEA.gene_ind_mutation_prob: float¶
Gene independent mutation probability.
- Return type:
- Setter:
Set a new gene independent mutation probability
- Parameters:
prob (float) – The new probability. If omitted,
_default_gene_ind_mutation_probis chosen- Raises:
TypeError – If prob is not a real number
ValueError – If prob is not in (0, 1)
- property SimpleEA.index: int¶
Trainer index.
The trainer index is only used by distributed trainers. For the rest of trainers
_default_indexis used.- Return type:
- Setter:
Set a new value for trainer index.
- Parameters:
value (int) – New value for the trainer index. If set to
None,_default_indexis chosen- Raises:
TypeError – If value is not an integer
ValueError – If value is a negative number
- property SimpleEA.max_num_iters: int¶
Maximum number of iterations.
- Return type:
- Setter:
Set a new value for the maximum number of iterations
- Parameters:
value (int) – The new maximum number of iterations. If set to
None, the default maximum number of iterations,_default_max_num_iters, is chosen- Raises:
TypeError – If value is not an integer
ValueError – If value is not a positive number
- property SimpleEA.mutation_func: Callable[[Individual, float], tuple[Individual]]¶
Mutation function.
- Return type:
- Setter:
Set a new mutation function
- Parameters:
func (Callable) – The new mutation function. If omitted,
_default_mutation_funcis chosen- Raises:
TypeError – If func is not callable
- property SimpleEA.mutation_prob: float¶
Mutation probability.
- Return type:
- Setter:
Set a new mutation probability
- Parameters:
prob (float) – The new probability. If omitted,
_default_mutation_probis chosen- Raises:
TypeError – If prob is not a real number
ValueError – If prob is not in (0, 1)
- property SimpleEA.pop: list[Individual] | None¶
Population.
- Return type:
- property SimpleEA.pop_size: int¶
Population size.
- Return type:
- Setter:
Set a new population size
- Parameters:
size (int) – The new population size. If omitted,
_default_pop_sizeis chosen- Raises:
ValueError – If size is not greater than zero
- property SimpleEA.representatives: list[list[Solution | None]] | None¶
Representatives of the other species.
Only used by cooperative trainers. If the trainer does not use representatives,
Noneis returned.
- property SimpleEA.selection_func: Callable[[list[Individual], int, Any], list[Individual]]¶
Selection function.
- Return type:
- Setter:
Set a new selection function
- Parameters:
func (Callable) – The new selection function. If omitted,
_default_selection_funcis chosen- Raises:
TypeError – If func is not callable
- property SimpleEA.selection_func_params: dict[str, Any]¶
Parameters of the selection function.
- Return type:
- Setter:
Set new parameters for the selection function
- Parameters:
params (dict) – The new parameters. If omitted,
_default_selection_func_paramsis chosen- Raises:
Private properties¶
- property SimpleEA._default_checkpoint_activation: bool¶
Default checkpointing activation.
- Returns:
- Return type:
- property SimpleEA._default_checkpoint_filename: str¶
Default checkpointing file name.
- Returns:
- Return type:
- property SimpleEA._default_checkpoint_freq: int¶
Default checkpointing frequency.
- Returns:
- Return type:
- property SimpleEA._default_crossover_func: Callable[[Individual, Individual], tuple[Individual, Individual]]¶
Default crossover function.
- Returns:
The
crossover()method ofsolution_cls- Return type:
- property SimpleEA._default_crossover_prob: float¶
Default crossover probability.
- Returns:
- Return type:
- property SimpleEA._default_gene_ind_mutation_prob: float¶
Default gene independent mutation probability.
- Returns:
- Return type:
- property SimpleEA._default_max_num_iters: int¶
Default maximum number of iterations.
- Returns:
- Return type:
- property SimpleEA._default_mutation_func: Callable[[Individual, float], tuple[Individual]]¶
Default mutation function.
- Returns:
The
mutate()method ofsolution_cls- Return type:
- property SimpleEA._default_mutation_prob: float¶
Default mutation probability.
- Returns:
- Return type:
- property SimpleEA._default_selection_func: Callable[[list[Individual], int, Any], list[Individual]]¶
Default selection function.
- Returns:
- Return type:
- property SimpleEA._default_selection_func_params: dict[str, Any]¶
Parameters of the default selection function.
- Returns:
- Return type:
Methods¶
- SimpleEA.best_representatives() list[list[Solution]] | None¶
Return a list of representatives from each species.
Only used for cooperative trainers.
- SimpleEA.best_solutions() tuple[HallOfFame]¶
Get the best solutions found for each species.
- Returns:
One Hall of Fame for each species
- Return type:
- SimpleEA.dump(filename: str) None¶
Serialize this object and save it to a file.
- Parameters:
filename (str) – The file name.
- Raises:
TypeError – If filename is not a valid file name
ValueError – If the filename extension is not
SERIALIZED_FILE_EXTENSION
- SimpleEA.evaluate(sol: Solution, fitness_func: FitnessFunction | None = None, index: int | None = None, representatives: Sequence[Sequence[Solution | None]] | None = None) None¶
Evaluate one solution.
Its fitness will be modified according with the fitness function results. Besides, if called during training, the number of evaluations will be also updated.
- Parameters:
sol (Solution) – The solution
fitness_func (FitnessFunction) – The fitness function. If omitted, the default training fitness function (
fitness_function) is usedindex (int) – Index where sol should be inserted in the representatives sequence to form a complete solution for the problem. If omitted,
indexis usedrepresentatives (Sequence[Sequence[Solution]]) – Sequence of representatives of other species or
None(if no representatives are needed to evaluate sol). If omitted, the current value ofrepresentativesis used
- SimpleEA.reset() None¶
Reset the trainer.
Delete the state of the trainer (with
_reset_state()) and also all the internal data structures needed to perform the search (with_reset_internals()).This method should be invoqued each time a hyper parameter is modified.
- SimpleEA.test(best_found: Sequence[HallOfFame], fitness_func: FitnessFunction | None = None, representatives: Sequence[Sequence[Solution]] | None = None) None¶
Apply the test fitness function to the solutions found.
Update the solutions in best_found with their test fitness.
- Parameters:
best_found (Sequence[HallOfFame]) – The best solutions found for each species. One
HallOfFamefor each speciesfitness_func (FitnessFunction) – Fitness function used to evaluate the final solutions. If ommited, the default training fitness function (
fitness_function) will be usedrepresentatives (Sequence[Sequence[Solution]]) – Sequence of representatives of other species or
None(if no representatives are needed). If omitted, the current value ofrepresentativesis used
- Raises:
TypeError – If any parameter has a wrong type
ValueError – If any parameter has an invalid value.
- SimpleEA.train(state_proxy: DictProxy | None = None) None¶
Perform the training process.
- Parameters:
state_proxy (DictProxy) – dictionary proxy to copy the output state of the trainer procedure. Only used if train is executed within a
multiprocess.Process. Defaults toNone
Private methods¶
- SimpleEA._default_termination_func() bool¶
Default termination criterion.
- Returns:
Trueifmax_num_itersiterations have been run- Return type:
- SimpleEA._do_iteration() None¶
Implement an iteration of the search process.
In this case, the simplest evolutionary algorithm, as presented in chapter 7 of [Back2000], is implemented.
[Back2000]T. Back, D. Fogel and Z. Michalewicz, eds. Evolutionary Computation 1: Basic Algorithms and Operators, CRC Press, 2000.
- SimpleEA._evaluate_pop(pop: list[Individual]) None¶
Evaluate the individuals of pop that have an invalid fitness.
- Parameters:
pop (list[Individual]) – A population
- SimpleEA._finish_iteration() None¶
Finish an iteration.
Finish the iteration metrics (number of evaluations, execution time) after each iteration is run.
- SimpleEA._finish_search() None¶
Finish the search process.
This method is called after the search has finished. It can be overridden to perform any treatment of the solutions found.
- SimpleEA._generate_initial_pop() None¶
Generate the initial population.
The population is filled with random generated individuals.
- SimpleEA._get_state() dict[str, Any]¶
Return the state of this trainer.
Overridden to add the current population to the trainer’s state.
- Getter:
Return the state
- Setter:
Set a new state
- Return type:
- SimpleEA._init_internals() None¶
Set up the trainer internal data structures to start searching.
Overridden to create and initialize the Deap’s
Toolbox.
- SimpleEA._init_representatives() None¶
Init the representatives of the other species.
Only used for cooperative approaches, which need representatives of all the species to form a complete solution for the problem. Cooperative subclasses of the
Trainerclass should override this method to get the representatives of the other species initialized.
- SimpleEA._init_search() None¶
Init the search process.
Initialize the state of the trainer (with
_init_state()) and all the internal data structures needed (with_init_internals()) to perform the search.
- SimpleEA._init_state() None¶
Init the trainer state.
If there is any checkpoint file, the state is initialized from it with the
_load_state()method. Otherwise a new initial state is generated with the_new_state()method.
- SimpleEA._load_state() None¶
Load the state of the last checkpoint.
- Raises:
Exception – If the checkpoint file can’t be loaded
- SimpleEA._new_state() None¶
Generate a new trainer state.
Overridden to fill the population with evaluated random individuals.
- SimpleEA._postprocess_iteration() None¶
Postprocess after doing the iteration.
Subclasses should override this method to make any postprocessment after performing an iteration.
- SimpleEA._preprocess_iteration() None¶
Preprocess before doing the iteration.
Subclasses should override this method to make any preprocessment before performing an iteration.
- SimpleEA._reset_internals() None¶
Reset the internal structures of the trainer.
Overridden to reset the Deap’s
Toolbox.
- SimpleEA._save_state() None¶
Save the state at a new checkpoint.
- Raises:
Exception – If the checkpoint file can’t be written
- SimpleEA._search() None¶
Apply the search algorithm.
Execute the trainer until the termination condition is met. Each iteration is composed by the following steps:
- SimpleEA._set_cooperative_fitness(sol: Solution, fitness_trials_values: [Sequence[tuple[float]]]) None¶
Estimate a solution fitness from multiple evaluation trials.
Applies an average of the fitness trials values. Trainers requiring another estimation should override this method.
- SimpleEA._set_state(state: dict[str, Any]) None¶
Set the state of this trainer.
Overridden to add the current population to the trainer’s state.
- Parameters:
state (dict) – The last loaded state
- SimpleEA._start_iteration() None¶
Start an iteration.
Prepare the iteration metrics (number of evaluations, execution time) before each iteration is run.
- SimpleEA._termination_criterion() bool¶
Control the search termination.
- Returns:
Trueif either the default termination criterion or a custom termination criterion is met. The default termination criterion is implemented by the_default_termination_func()method. Another custom termination criterion can be set withcustom_termination_funcmethod.- Return type:

