navicatGA.base_solver¶
Attributes¶
Classes¶
Base solver class for the GA. |
Module Contents¶
- class navicatGA.base_solver.GenAlgSolver(n_genes: int, fitness_function=None, assembler=None, max_gen: int = 1000, max_conv: int = 100, pop_size: int = 100, mutation_rate: float = 0.15, selection_rate: float = 0.5, selection_strategy: str = 'roulette_wheel', excluded_genes: Sequence = None, n_crossover_points: int = 1, random_state: int = None, lru_cache: bool = False, scalarizer=None, prune_duplicates=False, verbose: bool = True, show_stats: bool = False, plot_results: bool = False, to_stdout: bool = True, to_file: bool = True, logger_file: str = 'output.log', logger_level: str = 'INFO', progress_bars: bool = False, problem_type: str = 'base')¶
Base solver class for the GA. Has the core methods and attributes that any GA run will require. However, it lacks a way to create new offspring evaluate fitness, and generate mutations. Those must be defined in a child class.
Parameters: :param n_genes: number of genes (variables) to have in each chromosome :type n_genes: int :param fitness_function: a fitness function that takes assembler(chromosome) and returns one (or more) fitness scores :type fitness_function: object :param assembler: a function that takes a chromosome and returns an (ideally hashable) object to be evaluated :type assembler: object :param max_gen: maximum number of generations to perform the optimization :type max_gen: int :param max_conv: maximum number of generations with same max fitness until convergence is assumed :type max_conv : int :param pop_size: number of chromosomes in population :type pop_size: int :param mutation_rate: rate at which random mutations occur :type mutation_rate: float :param selection_rate: top percentage of the population to be selected for crossover :type selection_rate: float :param selection_strategy: strategy to use for selection, several available :type selection_strategy: string :param excluded_genes: indices of chromosomes that should not be changed during run :type excluded_genes: optional, array-like :param n_crossover_points: number of slices to make for the crossover :type n_crossover_points: int :param random_state: fixed the random seed for the run :type random_state: int, optional :param lru_cache: whether to use lru_cacheing, which is monkeypatched into the class. Requires that the fitness function is hashable. :type lru_cache: bool :param scalarizer: chimera scalarizer object initialized to work on the results of fitness function :type scalarizer: optional, object with a scalarize method that takes in a population fitness and rescales it :param prune_duplicates: whether to prune duplicates in each generation :type prune_duplicates: bool :param verbose: whether to print iterations status :type verbose: int :param show_stats: whether to print stats at the end :type show_stats: bool :param plot_results: whether to plot results of the run at the end :type plot_results: bool :param to_stdout: whether to write output to stdout :type to_stdout: bool :param to_file: whether to write output to file :type to_file: bool :param logger_file: name of the file where output will be written if to_file is True :type logger_file: string :param progess_bars: whether to monkeypatch progress bars for monitoring run :type progress_bars: bool :param problem_type: passing a simple flag from child class for some in built hashable fitness functions. :type problem_type: string
- calculate_fitness(population)¶
Calculates the fitness of the population using the defined fitness function.
Parameters: :param population: population (array of chromosomes)
Returns: :return fitness: scalarized fitness of the current population, will be used :return pfitness: not-scalarized fitness of the current population, for printing
- check_input_base(fitness_function, selection_strategy, pop_size: int, excluded_genes)¶
Function to check that the main arguments have been passed to the GenAlgSolver instance.
Parameters: :param fitness_function: a fitness function that takes a chromosome and returns a fitness :param selection_strategy: a selection strategy string that can be recognized by this class :param pop_size: the number of chromosomes :param excluded_genes: a sequence of genes that should not change or mutate
- close_solver_logger()¶
Closes the logger of this solver. This avoid multiple loggers stacking when another solver is created.
- static create_offspring(first_parent, sec_parent, crossover_pt, offspring_number)¶
Creates an offspring from 2 parent chromosomes. It uses the crossover point(s) to determine how to perform the crossover. To be implemented on each child class. Must return the resulting offspring chromosome.
- get_boltzmann_probabilities(fitness)¶
Calculates selection probabilities according to a fitness Boltzmann distribution with an increasing temperature.
- get_crossover_points()¶
Retrieves random crossover points.
- get_number_mutations()¶
Returns the number of mutations that need to be performed.
- get_selection_probabilities()¶
Calculates selection probabilities either randomly or scaled by position.
- abstractmethod initialize_population()¶
Initializes the population of the problem. To be implemented in each child class.
- interval_selection(value)¶
Select based on self.prob_intervals, which are given by the selection strategy.
Parameters: :param value: random value defining which individual is selected from the probability intervals
Returns: :return: the selected individual from the population
- mutate_population(population, n_mutations)¶
Mutates the population according to a given user defined rule. To be defined further in each child class. Each direct child class can call this super method to retrieve the mutation rows and mutations columns in population.
- static plot_fitness_results(mean_fitness, max_fitness, iterations: int)¶
Plots the evolution of the mean and max fitness of the population using matplotlib.
Parameters: :param mean_fitness: mean fitness array for each generation :param max_fitness: max fitness array for each generation :param iterations: total number of generations
- print_stats(time_str)¶
Prints the statistics of the optimization run.
- select_parents(fitness)¶
Selects the parents according to a given selection strategy. Options are: roulette_wheel: Selects individuals from mating pool giving higher probabilities to fitter individuals. two_by_two: Pairs fittest individuals two by two random: Selects individuals from mating pool randomly. tournament: Selects individuals by choosing groups of 3 candidate individuals and then selecting the fittest one from the 3.
Parameters: :param fitness: the fitness values of the whole population at a given iteration
Returns: :return (ma, pa): a tuple containing the selected 2 parents for each mating
- solve(niter=None)¶
Performs the genetic algorithm optimization according to the parameters loaded in __init__. Will run for max_gen or until it converges for max_conv iterations, or for min(niter,max_gen) iterations if niter is an integer. Will start using previous state if available.
Parameters: :param niter: the number of generations to run
- static sort_by_fitness(fitness, population, printable_fitness)¶
Sorts fitness, population and printable fitness according to fitness.
- tournament_selection(fitness, range_max)¶
Performs tournament selection.
Parameters: :param fitness: the fitness values of the population at a given iteration :param range_max: range of individuals that can be selected for the tournament
Returns: :return: the selected individuals
- static tournament_selection_helper(selected_individuals, fitness)¶
Helper for tournament selection method. Selects the fittest individual from a pool of candidate individuals.
- allowed_mutation_genes¶
- assembler = None¶
- best_fitness_ = 0¶
- best_individual_ = None¶
- best_pfitness_ = 0¶
- fitness_ = None¶
- generations_ = 0¶
- logger¶
- max_conv = 100¶
- max_fitness_ = None¶
- max_gen = 1000¶
- mean_fitness_ = None¶
- mutation_rate = 0.15¶
- n_crossover_points = 1¶
- n_genes¶
- n_matings¶
- n_mutations¶
- plot_results = False¶
- pop_keep¶
- pop_size = 100¶
- population_ = None¶
- printable_fitness = None¶
- prob_intervals¶
- problem_type = 'base'¶
- progress_bars = False¶
- prune_duplicates = False¶
- runtime_ = 0.0¶
- scalarizer = None¶
- selection_rate = 0.5¶
- selection_strategy = 'roulette_wheel'¶
- show_stats = False¶
- temperature = 100¶
- verbose = True¶
- navicatGA.base_solver.allowed_selection_strategies¶