metaheuristic_designer.algorithms package

Submodules

metaheuristic_designer.algorithms.algorithm_selection module

Utility for benchmarking a set of algorithms with independent repetitions.

class AlgorithmSelection(algorithm_list: Iterable[Algorithm], repetitions: int = 10)[source]

Bases: object

Run several algorithms multiple times and collect performance data.

Each algorithm in the list is executed repetitions times. During the runs, every algorithm gets a silent reporter and a fresh HistoryTracker that records best, median, and worst objectives. After all runs finish, you can obtain the raw per-repetition data (raw_data) and an aggregated report().

Parameters:
  • algorithm_list (iterable of Algorithm) – The algorithms to evaluate. They are copied before execution so the originals are not modified.

  • repetitions (int, optional) – How many independent repetitions to perform for each algorithm (default 10).

optimize() Tuple[Population, DataFrame][source]

Execute all repetitions and return the best population found.

The raw data is stored in self.raw_data for later inspection.

Returns:

The population with the best overall fitness across all repetitions and algorithms.

Return type:

Population

report() DataFrame[source]

Return an aggregated summary of the raw data.

The report contains one row per algorithm, with columns for the number of runs, overall best, average best, standard deviation, timing averages, and more.

Returns:

A DataFrame with the aggregated statistics.

Return type:

pd.DataFrame

metaheuristic_designer.algorithms.memetic_algorithm module

Memetic algorithm that enhances a base optimisation strategy with local search.

class MemeticAlgorithm(objfunc: ObjectiveFunc, search_strategy: SearchStrategy, local_search: SearchStrategy, improvement_selection: ParentSelection, local_search_frequency: int = 1, local_search_depth: int = 1, keep_improved_solutions: bool = True, name: str | None = None, stop_cond: str = 'real_time_limit', progress_metric: str | None = None, max_iterations: int = 1000, max_evaluations: int = 100000.0, real_time_limit: float = 60.0, cpu_time_limit: float = 60.0, objective_target: float = 1e-10, max_patience: int = 100, track_median: bool = False, track_worst: bool = False, track_complete: bool = False, track_diversity: bool = False, stopping_condition: StoppingCondition | None = None, reporter: str | Reporter | None = None, history_tracker: HistoryTracker | None = None, parallel: bool = False, threads: int = 8)[source]

Bases: Algorithm

A memetic algorithm that interleaves a local search step into the main loop.

After the usual perturbation and evaluation, a subset of the offspring is improved by a separate SearchStrategy (the local search). The improved individuals can either replace the original offspring (Lamarckian, keep_improved_solutions=True) or only transfer their fitness (Baldwinian, keep_improved_solutions=False).

Parameters:
  • objfunc (ObjectiveFunc) – Objective function to optimise.

  • search_strategy (SearchStrategy) – The main search strategy.

  • local_search (SearchStrategy) – Strategy used for local improvement.

  • improvement_selection (ParentSelection) – How to choose which offspring are improved.

  • local_search_frequency (int, optional) – Apply local search every n generations (default 1).

  • local_search_depth (int, optional) – Number of local search iterations per application (default 1).

  • keep_improved_solutions (bool, optional) – If True (Lamarckian), the improved genotypes replace the original offspring. If False (Baldwinian), only the fitness values are transferred.

  • name (str, optional) – Display name; defaults to "Memetic {strategy_name}".

  • stop_cond (optional) – See Algorithm.

  • progress_metric (optional) – See Algorithm.

  • ... (optional) – See Algorithm.

initialize()[source]

Create and evaluate the initial population, then sync the local search.

Returns:

The evaluated initial population.

Return type:

Population

step(population: Population | None = None, time_start: float = 0, verbose: bool = False) Population[source]

Execute one memetic iteration (global step + optional local search).

Parameters:
  • population (Population, optional) – The population at the start of the iteration.

  • time_start (float, optional) – Start time (unused, kept for interface compatibility).

  • verbose (bool, optional) – Whether to produce verbose output (unused).

Returns:

The population after the iteration.

Return type:

Population

get_state(store_population: bool = False) dict[source]

Extend Algorithm.get_state() with local search data.

Parameters:

store_population (bool, optional) – See Algorithm.

Returns:

Dictionary containing the memetic algorithm state.

Return type:

dict

step_info(start_time: int = 0)[source]

Print per-generation information including local search details.

metaheuristic_designer.algorithms.strategy_selection module

Convenience wrapper that benchmarks strategies instead of pre-built algorithms.

class StrategySelection(objfunc: ObjectiveFunc, strategy_list: Iterable[SearchStrategy], repetitions: int = 10, **kwargs)[source]

Bases: AlgorithmSelection

Evaluate a set of search strategies by automatically wrapping them in Algorithm objects.

This is a thin wrapper around AlgorithmSelection that accepts SearchStrategy instances and a shared configuration dictionary. It converts each strategy into an Algorithm with the same settings and then delegates to the parent class.

Parameters:
  • objfunc (ObjectiveFunc) – Objective function to evaluate.

  • strategy_list (iterable of SearchStrategy) – The search strategies to compare.

  • repetitions (int, optional) – Number of independent runs per strategy (default 10).

  • **kwargs – Keyword arguments forwarded to every Algorithm constructor (e.g., stop_cond="max_iterations", max_iterations=100).

Module contents

Algorithm variant, and comparison utilities.

class Algorithm(objfunc: ObjectiveFunc, search_strategy: SearchStrategy, name: str | None = None, stop_cond: str = 'real_time_limit', progress_metric: str | None = None, max_iterations: int = 1000, max_evaluations: int = 100000.0, real_time_limit: float = 60.0, cpu_time_limit: float = 60.0, objective_target: float = 1e-10, max_patience: int = 100, verbose_timer: float = 0.5, track_median: bool = False, track_worst: bool = False, track_full_objective: bool = False, track_full_population: bool = False, track_diversity: bool = False, checkpoint_file: str | None = None, checkpoint_time_frequency: float | None = None, checkpoint_iteration_frequency: float | None = None, stopping_condition: StoppingCondition | None = None, reporter: str | Reporter | None = None, history_tracker: HistoryTracker | None = None, checkpointer: Checkpointer | None = None, parallel: bool = False, threads: int = 8)[source]

Bases: object

Orchestrates a complete optimisation run.

An Algorithm combines a ObjectiveFunc with a SearchStrategy and manages the iteration loop, stopping conditions, reporting, history tracking, and checkpointing.

All runtime settings can be supplied as plain keyword arguments (e.g., max_iterations=200) or as pre-built objects (StoppingCondition, Reporter, etc.). The keyword-argument style is convenient for quick experiments; the object-based style gives finer control and reusability.

Parameters:
  • objfunc (ObjectiveFunc) – The objective function to optimise.

  • search_strategy (SearchStrategy) – Strategy that defines one iteration of the algorithm.

  • name (str, optional) – Display name for the algorithm (defaults to the strategy’s name).

  • stop_cond (str, optional) – Expression that defines the stopping condition (see StoppingCondition). Default "real_time_limit".

  • progress_metric (str, optional) – Token used to compute the 0-1 progress value for parameter schedules. Defaults to the same tokens as stop_cond.

  • max_iterations (int, optional) – Maximum number of iterations (default 1000).

  • max_evaluations (int, optional) – Maximum number of objective evaluations (default 1e5).

  • real_time_limit (float, optional) – Wall-clock time limit in seconds (default 60).

  • cpu_time_limit (float, optional) – CPU time limit in seconds (default 60).

  • objective_target (float, optional) – Target value for the raw objective (default 1e-10).

  • max_patience (int, optional) – Iterations without improvement before convergence stops (default 100).

  • verbose_timer (float, optional) – Interval in seconds between prints when using the default VerboseReporter (default 0.5).

  • track_diversity (track_median / track_worst / track_full_objective / track_full_population /) – Flags forwarded to the HistoryTracker when one is not supplied explicitly.

  • checkpoint_iteration_frequency (checkpoint_file / checkpoint_time_frequency /) – Arguments used to construct a Checkpointer when checkpointer is not given.

  • stopping_condition (StoppingCondition, optional) – Explicit stopping condition object.

  • reporter (str or Reporter, optional) – Reporter instance or name ("tqdm", "silent", "verbose").

  • history_tracker (HistoryTracker, optional) – Explicit history tracker.

  • checkpointer (Checkpointer, optional) – Explicit checkpointer.

  • parallel (bool, optional) – Whether to evaluate the population in parallel (currently reserved for future use).

  • threads (int, optional) – Number of threads for parallel evaluation (reserved).

property initializer: Initializer
property iterations: int
property evaluations: int
property patience_left: int
property progress: float
property population: Population
gather_parameters() dict[source]

Collect the current parameters of the underlying search strategy.

Returns:

A dictionary of parameter names and their current values.

Return type:

dict

best_solution() Tuple[Any, float][source]

Return the best decoded solution and its raw objective value.

Returns:

best_solution – A pair of the best individual with its objective value.

Return type:

Tuple[Any, float]

best_individual() Tuple[ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], float][source]

Return the best genotype and its internal fitness value.

Returns:

best_solution – A pair of the best individual with its fitness.

Return type:

Tuple[VectorLike, float]

restart(restart_objfunc: bool = True)[source]

Reset internal counters and, optionally, the objective function.

Parameters:

restart_objfunc (bool, optional) – If True, also reset the objective function’s evaluation counter.

initialize(reset_objfunc: bool = True) Population[source]

Create and evaluate the initial population.

Parameters:

reset_objfunc (bool, optional) – Passed through to restart().

Returns:

The evaluated initial population.

Return type:

Population

step(population: Population | None = None) Population[source]

Execute one iteration of the optimisation loop.

The default implementation performs: parent selection -> perturbation -> evaluation -> survivor selection.

Parameters:

population (Population, optional) – The population at the start of the iteration. If not given, the currently stored population is used.

Returns:

The population after the iteration.

Return type:

Population

resume() Population[source]

Resume an interrupted run from the last checkpoint.

Returns:

The final population after the run completes.

Return type:

Population

optimize(resume: bool = False) Population[source]

Run the optimisation loop until a stopping condition is met.

Parameters:

resume (bool, optional) – If True, do not reset the algorithm state - continue from the current population and counters.

Returns:

The final population.

Return type:

Population

Raises:

KeyboardInterrupt, TerminationException – If the process is interrupted, a checkpoint is attempted before re-raising.

get_state(store_population: bool = False) dict[source]

Serialise the current algorithm state to a dictionary.

Parameters:

store_population (bool, optional) – If True, include the complete genotype matrix.

Returns:

Dictionary representation of the algorithm state.

Return type:

dict

store_state(file_name: str = 'dumped_state.json', readable: bool = False)[source]

Serialise the current algorithm state to a JSON file.

Parameters:
  • file_name (str, optional) – Destination path (default "dumped_state.json").

  • readable (bool, optional) – If True, produce indented JSON (larger but human readable).

to_pandas()[source]

Shorthand for self.history_tracker.to_pandas().

Returns:

Per-iteration summary of tracked metrics.

Return type:

pandas.DataFrame

to_pandas_full_objective()[source]

Shorthand for self.history_tracker.to_pandas_full_objective().

Returns:

Wide-format DataFrame with the full objective vector per generation.

Return type:

pandas.DataFrame

class AlgorithmSelection(algorithm_list: Iterable[Algorithm], repetitions: int = 10)[source]

Bases: object

Run several algorithms multiple times and collect performance data.

Each algorithm in the list is executed repetitions times. During the runs, every algorithm gets a silent reporter and a fresh HistoryTracker that records best, median, and worst objectives. After all runs finish, you can obtain the raw per-repetition data (raw_data) and an aggregated report().

Parameters:
  • algorithm_list (iterable of Algorithm) – The algorithms to evaluate. They are copied before execution so the originals are not modified.

  • repetitions (int, optional) – How many independent repetitions to perform for each algorithm (default 10).

optimize() Tuple[Population, DataFrame][source]

Execute all repetitions and return the best population found.

The raw data is stored in self.raw_data for later inspection.

Returns:

The population with the best overall fitness across all repetitions and algorithms.

Return type:

Population

report() DataFrame[source]

Return an aggregated summary of the raw data.

The report contains one row per algorithm, with columns for the number of runs, overall best, average best, standard deviation, timing averages, and more.

Returns:

A DataFrame with the aggregated statistics.

Return type:

pd.DataFrame

class MemeticAlgorithm(objfunc: ObjectiveFunc, search_strategy: SearchStrategy, local_search: SearchStrategy, improvement_selection: ParentSelection, local_search_frequency: int = 1, local_search_depth: int = 1, keep_improved_solutions: bool = True, name: str | None = None, stop_cond: str = 'real_time_limit', progress_metric: str | None = None, max_iterations: int = 1000, max_evaluations: int = 100000.0, real_time_limit: float = 60.0, cpu_time_limit: float = 60.0, objective_target: float = 1e-10, max_patience: int = 100, track_median: bool = False, track_worst: bool = False, track_complete: bool = False, track_diversity: bool = False, stopping_condition: StoppingCondition | None = None, reporter: str | Reporter | None = None, history_tracker: HistoryTracker | None = None, parallel: bool = False, threads: int = 8)[source]

Bases: Algorithm

A memetic algorithm that interleaves a local search step into the main loop.

After the usual perturbation and evaluation, a subset of the offspring is improved by a separate SearchStrategy (the local search). The improved individuals can either replace the original offspring (Lamarckian, keep_improved_solutions=True) or only transfer their fitness (Baldwinian, keep_improved_solutions=False).

Parameters:
  • objfunc (ObjectiveFunc) – Objective function to optimise.

  • search_strategy (SearchStrategy) – The main search strategy.

  • local_search (SearchStrategy) – Strategy used for local improvement.

  • improvement_selection (ParentSelection) – How to choose which offspring are improved.

  • local_search_frequency (int, optional) – Apply local search every n generations (default 1).

  • local_search_depth (int, optional) – Number of local search iterations per application (default 1).

  • keep_improved_solutions (bool, optional) – If True (Lamarckian), the improved genotypes replace the original offspring. If False (Baldwinian), only the fitness values are transferred.

  • name (str, optional) – Display name; defaults to "Memetic {strategy_name}".

  • stop_cond (optional) – See Algorithm.

  • progress_metric (optional) – See Algorithm.

  • ... (optional) – See Algorithm.

initialize()[source]

Create and evaluate the initial population, then sync the local search.

Returns:

The evaluated initial population.

Return type:

Population

step(population: Population | None = None, time_start: float = 0, verbose: bool = False) Population[source]

Execute one memetic iteration (global step + optional local search).

Parameters:
  • population (Population, optional) – The population at the start of the iteration.

  • time_start (float, optional) – Start time (unused, kept for interface compatibility).

  • verbose (bool, optional) – Whether to produce verbose output (unused).

Returns:

The population after the iteration.

Return type:

Population

get_state(store_population: bool = False) dict[source]

Extend Algorithm.get_state() with local search data.

Parameters:

store_population (bool, optional) – See Algorithm.

Returns:

Dictionary containing the memetic algorithm state.

Return type:

dict

step_info(start_time: int = 0)[source]

Print per-generation information including local search details.

class StrategySelection(objfunc: ObjectiveFunc, strategy_list: Iterable[SearchStrategy], repetitions: int = 10, **kwargs)[source]

Bases: AlgorithmSelection

Evaluate a set of search strategies by automatically wrapping them in Algorithm objects.

This is a thin wrapper around AlgorithmSelection that accepts SearchStrategy instances and a shared configuration dictionary. It converts each strategy into an Algorithm with the same settings and then delegates to the parent class.

Parameters:
  • objfunc (ObjectiveFunc) – Objective function to evaluate.

  • strategy_list (iterable of SearchStrategy) – The search strategies to compare.

  • repetitions (int, optional) – Number of independent runs per strategy (default 10).

  • **kwargs – Keyword arguments forwarded to every Algorithm constructor (e.g., stop_cond="max_iterations", max_iterations=100).