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

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, stopping_condition: StoppingCondition | None = None, history_tracker: HistoryTracker | None = None, reporter: str | Reporter | None = None, checkpointer: Checkpointer | None = None, *, stop_condition_str: str = 'real_time_limit', progress_metric_str: str | None = None, max_iterations: int | None = None, max_evaluations: int | None = None, real_time_limit: float | None = None, cpu_time_limit: float | None = None, objective_target: float | None = None, max_patience: int | None = None, 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)[source]

Bases: object

Orchestrates a complete optimization 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 optimize.

  • 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
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.

resume() Population[source]

Resume an interrupted run from the last checkpoint.

Returns:

The final population after the run completes.

Return type:

Population

initialize() Population[source]

Generates the initial population from the search strategy.

This method stores the population in the .population attribute and returns it.

Returns:

The initial population generated.

Return type:

initial_population

step(prev_population: Population)[source]

Performs a single step of the optimization algorithm.

This method stores the population in the .population attribute and returns it.

Parameters:

prev_population (Population) – Population to be improved in this step of the optimization.

Returns:

The improved next population.

Return type:

population

update()[source]

Updates the internal state of the algorithm.

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

Run the optimization 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]

Serializes 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]

Serialize 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 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).