metaheuristic_designer.algorithms package#
Submodules#
Module contents#
Algorithm variant, and comparison utilities.
- class Algorithm(objfunc, search_strategy, name=None, stopping_condition=None, history_tracker=None, reporter=None, checkpointer=None, *, stop_condition_str='real_time_limit', progress_metric_str=None, max_iterations=None, max_evaluations=None, real_time_limit=None, cpu_time_limit=None, objective_target=None, max_patience=None, verbose_timer=0.5, track_median=False, track_worst=False, track_full_objective=False, track_full_population=False, track_diversity=False, checkpoint_file=None, checkpoint_time_frequency=None, checkpoint_iteration_frequency=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.Note
The constructor accepts either an explicit object (e.g.,
stopping_condition) or the individual keyword arguments that would build that object. If both are provided, the explicit object takes precedence and the keyword-only arguments are silently ignored.- Parameters:
- objfuncObjectiveFunc
The objective function to optimize.
- search_strategySearchStrategy
Strategy that defines one iteration of the algorithm.
- namestr, optional
Display name for the algorithm (defaults to the strategy’s name).
- stopping_conditionStoppingCondition, optional
Stopping condition object.
- reporterstr or Reporter, optional
Reporter instance or name (
"tqdm","silent","verbose").- history_trackerHistoryTracker, optional
History tracker object.
- checkpointerCheckpointer, optional
Checkpointer object.
- stop_condition_str / progress_metric / max_iterations / max_evaluations / real_time_limit / cpu_time_limit / objective_target / max_patience: optional
Flags forwarded to the
ParsedStoppingConditionwhen one is not supplied explicitly.Keyword-only, ignored if
stopping_conditionis given.- verbose_timerfloat, optional
Interval in seconds between prints when using the default
VerboseReporter(default 0.5).Keyword-only, ignored if
reporteris given.- track_median / track_worst / track_full_objective / track_full_population / track_diversitybool, optional
Flags forwarded to the
HistoryTrackerwhen one is not supplied explicitly.Keyword-only, ignored if
history_trackeris given.- checkpoint_file / checkpoint_time_frequency / checkpoint_iteration_frequencyoptional
Arguments used to construct a
Checkpointerwhen checkpointer is not given.Keyword-only, ignored if
checkpointeris given.
- Attributes:
- evaluations
- initializer
- iterations
- patience_left
- progress
- Parameters:
objfunc (ObjectiveFunc)
search_strategy (SearchStrategy)
name (Optional[str])
stopping_condition (Optional[StoppingCondition])
history_tracker (Optional[HistoryTracker])
reporter (Optional[str | Reporter])
checkpointer (Optional[Checkpointer])
stop_condition_str (str)
progress_metric_str (Optional[str])
max_iterations (Optional[int])
max_evaluations (Optional[int])
real_time_limit (Optional[float])
cpu_time_limit (Optional[float])
objective_target (Optional[float])
max_patience (Optional[int])
verbose_timer (float)
track_median (bool)
track_worst (bool)
track_full_objective (bool)
track_full_population (bool)
track_diversity (bool)
checkpoint_file (Optional[str])
checkpoint_time_frequency (Optional[float])
checkpoint_iteration_frequency (Optional[float])
Methods
Return the best genotype and its internal fitness value.
Return the best decoded solution and its raw objective value.
Collect the current parameters of the underlying search strategy.
get_state([store_population])Serializes the current algorithm state to a dictionary.
Generates the initial population from the search strategy.
optimize([resume])Run the optimization loop until a stopping condition is met.
restart([restart_objfunc])Reset internal counters and, optionally, the objective function.
resume()Resume an interrupted run from the last checkpoint.
step(prev_population)Performs a single step of the optimization algorithm.
store_state([file_name, readable])Serialize the current algorithm state to a JSON file.
Shorthand for
self.history_tracker.to_pandas().Shorthand for
self.history_tracker.to_pandas_full_objective().update()Updates the internal state of the algorithm.
- gather_parameters()[source]#
Collect the current parameters of the underlying search strategy.
- Return type:
dict- Returns:
- dict
A dictionary of parameter names and their current values.
- best_solution()[source]#
Return the best decoded solution and its raw objective value.
- Return type:
Tuple[Any,float]- Returns:
- best_solution: Tuple[Any, float]
A pair of the best individual with its objective value.
- best_individual()[source]#
Return the best genotype and its internal fitness value.
- Return type:
Tuple[ndarray[tuple[int],floating] |ndarray[tuple[int],integer] |ndarray[tuple[int],uint8|bool],float]- Returns:
- best_solution: Tuple[VectorLike, float]
A pair of the best individual with its fitness.
- restart(restart_objfunc=True)[source]#
Reset internal counters and, optionally, the objective function.
- Parameters:
- restart_objfuncbool, optional
If
True, also reset the objective function’s evaluation counter.
- Parameters:
restart_objfunc (bool)
- resume()[source]#
Resume an interrupted run from the last checkpoint.
- Return type:
- Returns:
- Population
The final population after the run completes.
- initialize()[source]#
Generates the initial population from the search strategy.
This method stores the population in the .population attribute and returns it.
- Return type:
- Returns:
- initial_population
The initial population generated.
- step(prev_population)[source]#
Performs a single step of the optimization algorithm.
This method stores the population in the .population attribute and returns it.
- Parameters:
- prev_populationPopulation
Population to be improved in this step of the optimization.
- Returns:
- population
The improved next population.
- Parameters:
prev_population (Population)
- optimize(resume=False)[source]#
Run the optimization loop until a stopping condition is met.
- Return type:
- Parameters:
- resumebool, optional
If
True, do not reset the algorithm state - continue from the current population and counters.
- Returns:
- Population
The final population.
- Raises:
- KeyboardInterrupt, TerminationException
If the process is interrupted, a checkpoint is attempted before re-raising.
- Parameters:
resume (bool)
- get_state(store_population=False)[source]#
Serializes the current algorithm state to a dictionary.
- Return type:
dict- Parameters:
- store_populationbool, optional
If
True, include the complete genotype matrix.
- Returns:
- dict
Dictionary representation of the algorithm state.
- Parameters:
store_population (bool)
- store_state(file_name='dumped_state.json', readable=False)[source]#
Serialize the current algorithm state to a JSON file.
- Parameters:
- file_namestr, optional
Destination path (default
"dumped_state.json").- readablebool, optional
If
True, produce indented JSON (larger but human readable).
- Parameters:
file_name (str)
readable (bool)
- class AlgorithmSelection(algorithm_list, repetitions=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_listiterable of Algorithm
The algorithms to evaluate. They are copied before execution so the originals are not modified.
- repetitionsint, optional
How many independent repetitions to perform for each algorithm (default 10).
- Parameters:
algorithm_list (Iterable[Algorithm])
repetitions (int)
Methods
optimize()Execute all repetitions and return the best population found.
report()Return an aggregated summary of the raw data.
- optimize()[source]#
Execute all repetitions and return the best population found.
The raw data is stored in
self.raw_datafor later inspection.- Return type:
Tuple[Population,DataFrame]- Returns:
- Population
The population with the best overall fitness across all repetitions and algorithms.
- report()[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.
- Return type:
DataFrame- Returns:
- pd.DataFrame
A DataFrame with the aggregated statistics.
- class StrategySelection(objfunc, strategy_list, repetitions=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:
- objfuncObjectiveFunc
Objective function to evaluate.
- strategy_listiterable of SearchStrategy
The search strategies to compare.
- repetitionsint, 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).
- Parameters:
objfunc (ObjectiveFunc)
strategy_list (Iterable[SearchStrategy])
repetitions (int)
Methods
optimize()Execute all repetitions and return the best population found.
report()Return an aggregated summary of the raw data.