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:
objectRun several algorithms multiple times and collect performance data.
Each algorithm in the list is executed
repetitionstimes. During the runs, every algorithm gets a silent reporter and a freshHistoryTrackerthat records best, median, and worst objectives. After all runs finish, you can obtain the raw per-repetition data (raw_data) and an aggregatedreport().- 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_datafor later inspection.- Returns:
The population with the best overall fitness across all repetitions and algorithms.
- Return type:
- 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:
AlgorithmSelectionEvaluate a set of search strategies by automatically wrapping them in
Algorithmobjects.This is a thin wrapper around
AlgorithmSelectionthat acceptsSearchStrategyinstances and a shared configuration dictionary. It converts each strategy into anAlgorithmwith 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
Algorithmconstructor (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:
objectOrchestrates a complete optimization run.
An
Algorithmcombines aObjectiveFuncwith aSearchStrategyand 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
convergencestops (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
HistoryTrackerwhen one is not supplied explicitly.checkpoint_iteration_frequency (checkpoint_file / checkpoint_time_frequency /) – Arguments used to construct a
Checkpointerwhen 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:
- 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
- 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:
- 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).
- class AlgorithmSelection(algorithm_list: Iterable[Algorithm], repetitions: int = 10)[source]¶
Bases:
objectRun several algorithms multiple times and collect performance data.
Each algorithm in the list is executed
repetitionstimes. During the runs, every algorithm gets a silent reporter and a freshHistoryTrackerthat records best, median, and worst objectives. After all runs finish, you can obtain the raw per-repetition data (raw_data) and an aggregatedreport().- 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_datafor later inspection.- Returns:
The population with the best overall fitness across all repetitions and algorithms.
- Return type:
- 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:
AlgorithmSelectionEvaluate a set of search strategies by automatically wrapping them in
Algorithmobjects.This is a thin wrapper around
AlgorithmSelectionthat acceptsSearchStrategyinstances and a shared configuration dictionary. It converts each strategy into anAlgorithmwith 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
Algorithmconstructor (e.g.,stop_cond="max_iterations",max_iterations=100).