Engines
Submodules
pygenalgo.engines.generic_ga module
- class pygenalgo.engines.generic_ga.GenericGA(initial_pop: list[Chromosome], fit_func: Callable, select_op: SelectionOperator | None = None, mutate_op: MutationOperator | None = None, crossx_op: CrossoverOperator | None = None, n_cpus: int | None = None)[source]
Bases:
objectDescription:
Generic GA class models the interface of a specific genetic algorithm model (or engine). It provides the common variables and functionality that all GA models should share.
- MAX_CPUs: int = 2
Set the maximum number of CPUs (at least one).
- adapt_probabilities(threshold: float | None = None) bool[source]
This method is used (optionally) to adjust simultaneously the crossover and mutation parameters of the GenericGA object.
- Parameters:
threshold – This float parameter is used to determine whether we are going to increase or decrease the crossover and mutation parameters.
- Returns:
True if the parameters have changed, else False.
- best_chromosome() Chromosome | None[source]
Auxiliary method that returns the chromosome with the highest fitness value. Safeguarded with ignoring NaNs.
- Returns:
Return the chromosome with the highest fitness.
- best_n(n: int = 1) list[Chromosome][source]
Auxiliary method that returns the best ‘n’ chromosomes with the highest fitness value.
- Parameters:
n – the number of the best chromosomes. Default = 1.
- Returns:
Return the ‘n’ chromosomes with the highest fitness.
- clear_all() None[source]
Make sure all the genetic operator counters and the stats are cleared. This reset everything before each run().
- Returns:
None.
- crossover_mutate(input_population: list[Chromosome]) None[source]
This is an auxiliary method that combines the crossover and mutation operations in one call. Since these operations happen in place the ‘input_population’ will be modified directly.
This method should be called AFTER the selection of the parents that have been selected for breeding.
- Parameters:
input_population – this is the population that we will apply the two genetic operators.
- Returns:
None.
- property crossx_op: CrossoverOperator
Accessor method that returns the crossover operator reference.
- Returns:
the CrossoverOperator.
- evaluate_fitness(input_population: list[Chromosome], parallel_mode: bool = False, backend: str = 'threading') tuple[list[float], bool][source]
Evaluate all the chromosomes of the input list with the custom fitness function. The parallel_mode is optional. Moreover, the default backend is “threading”, but in the IslandModelGA it is better to select “loky”.
- Parameters:
input_population – (list) The population of Chromosomes that we want to evaluate their fitness.
parallel_mode – (bool) Enables parallel computation of the fitness function.
backend – (str) Backend for the parallel Joblib framework.
- Returns:
a list with the fitness values and the found solution flag.
- f_eval_increase_by(new_counts: int) None[source]
Utility method to allow the ‘_f_eval’ to be updated with new counts outside the main class. This can happen during gene correction.
- Parameters:
new_counts – the new value of ‘counts’ that we want to add on the current f_eval.
- Returns:
None.
- property f_evals: int
Accessor method that returns the value of the f_eval.
- Returns:
(int) the counted number of function evaluations.
- fitness_func
- individual_fitness(index: int) float[source]
Get the fitness value of an individual member of the population.
- Parameters:
index – Position of the individual in the population.
- Returns:
The fitness value (float).
- property iteration: int
Accessor (getter) of the iteration parameter.
- Returns:
the iteration value.
- property mutate_op: MutationOperator
Accessor method that returns the mutation operator reference.
- Returns:
the MutationOperator.
- property n_cpus: int
Accessor method that returns the number of CPUs.
- Returns:
the n_cpus.
- population
- population_fitness() list[float][source]
Get the fitness values of all the population.
- Returns:
A list with all the fitness values.
- property rng: Generator
Get access of the Class variable (rng_GA).
- Returns:
the random number generator.
- rng_GA: Generator = Generator(PCG64) at 0x7078EF0DC900
Random Number Generator for the whole class.
- run(*args, **kwargs) None[source]
Main method of the Generic GA class, that implements the evolutionary routine.
- property select_op: SelectionOperator
Accessor method that returns the selection operator reference.
- Returns:
the SelectionOperator.
- classmethod set_seed(new_seed=None) None[source]
Sets a new seed for the random number generator.
- Parameters:
new_seed – New seed value (default=None).
- Returns:
None.
- property stats: dict
Accessor method that returns the ‘stats’ dictionary.
- Returns:
the dictionary with the statistics from the run.
pygenalgo.engines.island_model_ga module
- class pygenalgo.engines.island_model_ga.IslandModelGA(num_islands: int, migrate_op: MigrationOperator | None = None, **kwargs)[source]
Bases:
GenericGADescription:
In Island Model GA we run in parallel a number of “islands”, each one evolving its own (sub)-population. Optionally we can allow “migration”, among the best individuals from each island.
- property migrate_op: MigrationOperator
Accessor method that returns the migration operator reference.
- Returns:
the MigrationOperator.
- property num_islands: int
Accessor method that returns the number of islands in the model.
- Returns:
the number of islands.
- run(epochs: int = 500, correction: bool = False, elitism: bool = True, f_tol: float | None = None, allow_migration: bool = False, n_periods: int = 10, adapt_probs: bool = False, shuffle: bool = True, f_max_eval: int | None = None, verbose: bool = False) None[source]
Main method of the IslandModelGA class, that implements the evolutionary routine.
- Parameters:
epochs – (int) maximum number of iterations in the evolution process.
correction – (bool) flag that if set to ‘True’ will check the validity of the population (at the gene level) and attempt to correct the genome by calling the random() method of the flawed gene.
elitism – (bool) flag that enables elitism. If set to True then the chromosome with the highest fitness will always be copied to the next generation (unaltered).
f_tol – (float) tolerance in the difference between the average values of two consecutive populations. It is used to determine the convergence of the population. If this value is None (default) the algorithm will terminate using the epochs value.
allow_migration – (bool) flag that if set to ‘True’ will allow the migration of the best individuals among the different islands.
n_periods – (int) the number of times that we will break the main evolution to allow for chromosomes to migrate. NB: This setting is active only when the option allow_migration == True. Otherwise, is ignored.
adapt_probs – (bool) If enabled (set to True), it will allow the crossover and mutation probabilities to adapt according to the convergence of the population to a single solution. Default is set to False.
shuffle – (bool) If enabled (set to True), it will shuffle the population before the application of the crossover and mutation operations. The default is set to True.
f_max_eval – (int) it sets an upper limit of function evaluations. If the number is exceeded the genetic algorithm stops. If this value is set, the epochs will be ignored and re-adjusted to meet the new requirement.
verbose – (bool) if ‘True’ it will display periodically information about the current stats of the subpopulations. NB: This setting is active only when the option allow_migration == True. Otherwise, is ignored.
- Returns:
None.
pygenalgo.engines.standard_ga module
- class pygenalgo.engines.standard_ga.StandardGA(**kwargs)[source]
Bases:
GenericGADescription:
StandardGA model provides a basic implementation of the “GenericGA”, which at each iteration (epoch) replaces the whole population using the genetic operators (crossover and mutation).
- fitness_func
- population
- run(epochs: int = 100, elitism: bool = True, correction: bool = False, f_tol: float | None = None, parallel: bool = False, adapt_probs: bool = False, shuffle: bool = True, f_max_eval: int | None = None, verbose: bool = False) None[source]
Main method of the StandardGA class, that implements the evolutionary routine.
- Parameters:
epochs – (int) maximum number of iterations in the evolution process.
elitism – (bool) flag that enables elitism. If True then the chromosome with the highest fitness will always be copied to the next generation (unaltered).
correction – (bool) flag that if set to ‘True’ will check the validity of the population (at the gene level) and attempt to correct the genome by calling the random() method of the flawed gene.
f_tol – (float) tolerance in the difference between the average values of two consecutive populations. It is used to determine the convergence of the population. If this value is None (default) the algorithm will terminate using the epochs value.
parallel – (bool) Flag that enables parallel computation of the fitness function.
adapt_probs – (bool) If enabled (set to True), it will allow the crossover and mutation probabilities to adapt according to the convergence of the population to a single solution. Default is set to False.
shuffle – (bool) If enabled (set to True), it will shuffle the population before the application of the crossover and mutation operations. The default is set to True.
f_max_eval – (int) it sets an upper limit of function evaluations. If the number is exceeded the genetic algorithm stops.
verbose – (bool) if ‘True’ it will display periodically information about the current average fitness and spread of the population.
- Returns:
None.