Population

class evolib.core.population.Pop(config_path, lineage_file='lineage_log.csv', fitness_function=None, initialize=True)[source]

Bases: object

Represents a population for evolutionary optimization, including configuration, statistics, and operator integration.

classmethod from_config(cfg, fitness_function=None, initialize=False)[source]

Create a new population from an existing validated config.

Return type:

Pop

add_indiv(new_indiv=None)[source]

Add a new individual to the population.

Parameters:

new_indiv (Indiv | None) – The individual to be added.

Return type:

None

age_indivs()[source]

Increment the age of all individuals in the population by 1 and set their ‘origin’ to indicate they are now considered parents in the evolutionary process.

Raises:

ValueError – If the population is empty.

Return type:

None

best(sort=True)[source]

Return the best individual (lowest fitness).

Parameters:

sort (bool) – If True, sort the population before returning the best. If False, return first individual as-is. Default: True.

Return type:

Indiv

clear_indivs()[source]

Remove all individuals from the population.

Return type:

None

create_indiv()[source]

Create a new individual using default settings.

Return type:

Indiv

ensure_evaluated()[source]

Evaluate individuals that have no valid fitness yet.

Return type:

None

evaluate_fitness()[source]

Evaluate the fitness function for all individuals in the population.

Return type:

None

evaluate_indivs(indivs)[source]

Evaluate fitness for a custom list of individuals.

Return type:

None

fitness_diversity(method=DiversityMethod.IQR)[source]

Computes population diversity based on fitness values.

Parameters:

method (DiversityMethod) – One of [‘iqr’, ‘std’, ‘var’, ‘range’, ‘normalized_std’]

Returns:

Diversity score.

Return type:

float

get_elites()[source]

Return a list of elite individuals and set their is_elite flag.

Return type:

list[Indiv]

get_fitness_array(include_none=False)[source]

Return a NumPy array of all fitness values in the population.

Returns:

Array of fitness values (ignores None).

Return type:

ndarray

initialize_population(initializer=None)[source]

Initializes the population using the provided para initializer function.

Parameters:

initializer (Optional[Callable[[Pop], Any]]) – Function to generate Para instances for each individual.

Return type:

None

print_history(last_n=None, columns=None)[source]

Prints the evolution history in a simple tabular format using pandas.

Parameters:
  • last_n (int | None) – If set, only print the last N generations.

  • columns (list[str] | None) – If set, restrict output to specific columns.

Return type:

None

print_indivs()[source]

Print the status of all individuals in the population.

Return type:

None

print_status(verbosity=1)[source]

Prints information about the population based on the verbosity level.

Parameters:
  • verbosity (int) – Level of detail for the output. - 0: No output - 1: Basic information (generation, fitness, diversity) - 2: Additional parameters (e.g., mutation rate, population fitness) - 3: Detailed information (e.g., number of individuals, elites) - 10: Full details including a call to info_indivs()

  • Default – 1

Raises:
  • TypeError – If verbosity is not an integer.

  • AttributeError – If required population data is incomplete.

Return type:

None

remove_indiv(indiv)[source]

Remove an individual from the population.

Parameters:

indiv (Indiv) – The individual to be removed.

Return type:

None

remove_old_indivs()[source]

Removes individuals whose age exceeds the maximum allowed age, excluding elite individuals.

Returns:

Number of individuals removed.

Return type:

int

reset()[source]

Reset the population to an empty state and reset all statistics.

Keeps configuration and mutation/crossover strategy, but removes all individuals and clears the history logger.

Return type:

None

run(*, strategy=None, max_generations=None, target_fitness=None, minimize=None, patience=None, min_delta=0.0, time_limit_s=None, verbosity=1, on_start=None, on_generation_start=None, on_generation_end=None, on_improvement=None, on_end=None)[source]

Run the evolutionary process until a stopping criterion is met.

Parameters:
  • strategy (EvolutionStrategy | None) – Optional override of the evolution strategy.

  • max_generations (Optional[int]) – Maximum number of generations to run (fallback: self.max_generations).

  • target_fitness (Optional[float]) – Desired fitness threshold to stop evolution early.

  • minimize (Optional[bool]) – If True, lower fitness is better; else maximize. Defaults to True.

  • patience (Optional[int]) – Stop if no improvement after this many generations.

  • min_delta (float) – Minimum improvement to reset patience counter.

  • time_limit_s (Optional[float]) – Stop evolution after this many seconds (wall clock).

  • verbosity (int) – 0 = silent, 1 = status messages (default).

  • on_start (Optional[Callable[[Pop], None]]) – Optional callback(pop)

  • on_generation – Optional callback(pop)

  • on_improvement (Optional[Callable[[Pop], None]]) – Optional callback(pop)

  • on_end (Optional[Callable[[Pop], None]]) – Optional callback(pop)

Returns:

Number of generations completed.

Return type:

int

run_one_generation(strategy=None, sort=False)[source]

Executes a single evolutionary generation using the selected strategy.

Parameters:
  • strategy (EvolutionStrategy | None) – Optional override for the evolution

  • strategy.

  • None (If)

  • initialization. (uses the strategy defined during)

Raises:

ValueError – If no strategy is defined or the strategy is unknown.

Return type:

None

select_parents(num_parents)[source]

Selects parents using the configured selection strategy.

Parameters:

num_parents (int) – Number of parents to select.

Returns:

Selected parents (deep copies).

Return type:

list[Indiv]

set_fitness_function(func)[source]

Sets the fitness function to be used for evaluating individuals.

Parameters:
  • func (FitnessFunction) – A function that modifies an individual

  • .... (in-place by assigning indiv.fitness =)

Raises:

TypeError – If the argument is not callable.

Return type:

None

set_functions(fitness_function)[source]

[DEPRECATED] Use set_fitness_function() or constructor argument instead.

Registers the fitness function used during evolution.

Parameters:

fitness_function (FitnessFunction) – Function to assign fitness to an individual.

Return type:

None

sort_by_fitness(reverse=False)[source]

Sorts the individuals in the population by their fitness (ascending by default).

Parameters:

reverse (bool) – If True, sort in descending order.

Return type:

None

step()[source]

Alias for run_one_generation().

Return type:

None

update_crossover_parameters(indivs)[source]

Update crossover-related parameters for a given set of individuals.

Return type:

None

Typical usage:
  • During population initialization: called once on all parents to ensure they start with valid crossover parameters.

  • During evolution: called on offspring before crossover, so that new individuals use up-to-date parameters (e.g. annealing schedules or adaptive rates).

Notes

  • Parents are not updated in every generation. They keep the parameters assigned at initialization, ensuring selection acts on stable values.

  • Offspring are updated once per generation, prior to crossover.

update_mutation_parameters(indivs)[source]

Update mutation-related parameters for a given set of individuals via their para objects.

Return type:

None

Typical usage:
  • During population initialization: called once on all parents to ensure they start with valid adaptive parameters.

  • During evolution: called on offspring before mutation, so that new individuals use up-to-date parameters (e.g. annealing schedules).

Notes

  • Parents are not updated in every generation. They keep the parameters assigned at initialization, ensuring selection acts on stable values.

  • Offspring are updated once per generation, prior to mutation.

update_parameters(indivs)[source]

Update all strategy-dependent parameters for the current generation.

Calls both update_mutation_parameters() and update_crossover_parameters().

Raises:
  • ValueError or AttributeError if the population or its individuals

  • are invalid.

Return type:

None

update_statistics()[source]

Update all fitness-related statistics of the population.

Raises:

ValueError – If no individuals have a valid fitness value.

Return type:

None

property history_df: DataFrame

Return the evolution history as a pandas DataFrame.

This is a convenience wrapper around history_logger.to_dataframe() so users don’t need to access internal logger details.

property history_dicts: List[Dict[str, Any]]

Return history as list of dicts (pandas-free).

property lambda_: int
property mu: int
property sample_indiv: Indiv

Returns a representative individual from the current population.

Useful for inspecting parameter module dimensions, shapes, or bounds