Skip to main content

Algorithm

Trait Algorithm 

Source
pub trait Algorithm<T, Q = f64>
where T: Clone + Send + 'static + Display, Q: Clone + Default + Send + 'static + Display,
{ type SolutionSet: SolutionSet<T, Q>; type Parameters; type StepState: StepStateCheckpoint<T, Q>;
Show 14 methods // Required methods fn new(parameters: Self::Parameters) -> Self; fn algorithm_name(&self) -> &str; fn termination_criteria(&self) -> TerminationCriteria; fn observers_mut(&mut self) -> &mut Vec<Box<dyn AlgorithmObserver<T, Q>>>; fn set_solution_set(&mut self, solution_set: Self::SolutionSet); fn get_solution_set(&self) -> Option<&Self::SolutionSet>; fn initialize_step_state( &self, problem: &(impl Problem<T, Q> + Sync), ) -> Self::StepState; fn step( &self, problem: &(impl Problem<T, Q> + Sync), state: &mut Self::StepState, ); fn build_snapshot( &self, problem: &(impl Problem<T, Q> + Sync), state: &Self::StepState, ) -> ExecutionStateSnapshot; fn finalize_step_state(&self, state: Self::StepState) -> Self::SolutionSet; // Provided methods fn run<P>(&mut self, problem: &P) -> Result<Self::SolutionSet, String> where Self: Sized, Self::SolutionSet: Clone, P: Problem<T, Q> + Sync { ... } fn validate_parameters(&self) -> Result<(), String> { ... } fn checkpoint_algorithm_parameters(&self) -> String { ... } fn get_resume_checkpoint( &self, runtime_metadata: &CheckpointRuntimeMetadata<'_>, checkpoint_policy: &CheckpointPolicy, ) -> Option<CheckpointRecord> { ... }
}
Expand description

Basic interface for all optimization algorithms.

All algorithms execute with the same step-based lifecycle: initialize state -> report initial snapshot -> loop step/snapshot until termination -> finalize to a solution set.

Required Associated Types§

Required Methods§

Source

fn new(parameters: Self::Parameters) -> Self

Source

fn algorithm_name(&self) -> &str

Human-readable algorithm name used by observers and runtime reports.

Source

fn termination_criteria(&self) -> TerminationCriteria

Termination criteria configured for this algorithm instance.

Source

fn observers_mut(&mut self) -> &mut Vec<Box<dyn AlgorithmObserver<T, Q>>>

Mutable access to registered observers.

Source

fn set_solution_set(&mut self, solution_set: Self::SolutionSet)

Stores the last solution set produced by run.

Source

fn get_solution_set(&self) -> Option<&Self::SolutionSet>

Source

fn initialize_step_state( &self, problem: &(impl Problem<T, Q> + Sync), ) -> Self::StepState

Source

fn step( &self, problem: &(impl Problem<T, Q> + Sync), state: &mut Self::StepState, )

Source

fn build_snapshot( &self, problem: &(impl Problem<T, Q> + Sync), state: &Self::StepState, ) -> ExecutionStateSnapshot

Source

fn finalize_step_state(&self, state: Self::StepState) -> Self::SolutionSet

Provided Methods§

Source

fn run<P>(&mut self, problem: &P) -> Result<Self::SolutionSet, String>
where Self: Sized, Self::SolutionSet: Clone, P: Problem<T, Q> + Sync,

Runs the optimization algorithm on the given problem.

Default implementation shared by all algorithms.

Examples found in repository?
examples/internal_parallel_demo.rs (line 59)
53fn benchmark_sequential(problem: &KnapsackProblem, instances: usize, base_seed: u64) -> Result<(Duration, f64), String> {
54    measure_result(|| {
55        let mut checksum = 0.0;
56
57        for i in 0..instances {
58            let mut algorithm = GeneticAlgorithm::new(ga_params(base_seed + i as u64));
59            let solution_set = algorithm.run(problem)?;
60            checksum += solution_set.best_solution_value_or(problem, 0.0);
61        }
62
63        Ok::<f64, String>(checksum)
64    })
65}
More examples
Hide additional examples
examples/zdt1_nsga2_demo.rs (line 36)
14fn main() {
15    let seed = CliArgs::from_env().seed_or(42);
16
17    let problem = ZDT1Problem::new(30);
18
19    let parameters = NSGAIIParameters::new(
20        60,
21        0.9,
22        1.0 / 30.0,
23        SBXCrossover::new_default(),
24        PolynomialMutation::new_default(),
25        MultiObjectiveTournamentSelection::new(),
26        TerminationCriteria::new(vec![TerminationCriterion::MaxIterations(40)]),
27    )
28    .with_seed(seed);
29
30    let mut algorithm = NSGAII::new(parameters);
31    let observer = ConsoleObserver::new(true);
32    let observer2 = ChartObserver::new_default();
33    algorithm.add_observer(Box::new(observer));
34    algorithm.add_observer(Box::new(observer2));
35    let result = algorithm
36        .run(&problem)
37        .expect("NSGA-II run failed");
38
39    if let Some(best) = result.get(0) {
40        println!(
41            "NSGA-II finished (seed={}). population={}, best objectives={:?}",
42            seed,
43            result.size(),
44            best.objectives()
45        );
46    } else {
47        println!("NSGA-II finished with empty population (seed={})", seed);
48    }
49}
examples/knapsack_hc_demo.rs (line 37)
15fn main() {
16    let seed = CliArgs::from_env().seed_or(42);
17
18    let problem = KnapsackBuilder::new()
19        .with_capacity(90.0)
20        .add_item(12.0, 24.0)
21        .add_item(22.0, 33.0)
22        .add_item(41.0, 80.0)
23        .build();
24
25    let parameters = HillClimbingParameters::new(
26        BitFlipNeighborhood::new(),
27        TerminationCriteria::new(vec![TerminationCriterion::MaxIterations(120)]),
28    )
29    .with_seed(seed);
30    let mut algorithm = HillClimbing::new(parameters);
31
32    algorithm.add_observer(Box::new(ConsoleObserver::new(true)));
33    algorithm.add_observer(Box::new(ChartObserver::new_default()));
34    algorithm.add_observer(Box::new(HtmlReportObserver::new_default()));
35
36    let result = algorithm
37        .run(&problem)
38        .expect("Hill Climbing run failed");
39
40    if let Some(best) = result.best_solution(&problem) {
41        println!(
42            "Hill-Climbing finished (seed={}). Best fitness={:.4}",
43            seed,
44            best.quality_value()
45        );
46    } else {
47        println!("Hill-Climbing finished with no solutions (seed={})", seed);
48    }
49}
examples/knapsack_ga_demo.rs (line 45)
14fn main() {
15    let seed = CliArgs::from_env().seed_or(42);
16
17    let problem = KnapsackBuilder::new()
18        .with_capacity(150.0)
19        .add_item(10.0, 20.0)
20        .add_item(20.0, 30.0)
21        .add_item(30.0, 60.0)
22        .add_item(35.0, 65.0)
23        .add_item(45.0, 70.0)
24        .add_item(55.0, 90.0)
25        .add_item(150.0, 300.0)
26        .build();
27
28    let parameters = GeneticAlgorithmParameters::new(
29        50,
30        0.85,
31        0.08,
32        SinglePointCrossover::new(),
33        BitFlipMutation::new(),
34        BinaryTournamentSelection::new(),
35        TerminationCriteria::new(vec![TerminationCriterion::MaxIterations(4000)]),
36    )
37    .with_elite_size(1)
38    .with_seed(seed);
39
40    let mut algorithm = GeneticAlgorithm::new(parameters);
41    algorithm.add_observer(Box::new(ConsoleObserver::new(true)));
42    algorithm.add_observer(Box::new(ChartObserver::new_default()));
43
44    let result = algorithm
45        .run(&problem)
46        .expect("GA run failed");
47
48    if let Some(best) = result.best_solution(&problem) {
49        println!(
50            "GA finished (seed={}). Best fitness={:.4}",
51            seed,
52            best.quality_value()
53        );
54    } else {
55        println!("GA finished with no solutions (seed={})", seed);
56    }
57}
examples/knapsack_items_file/main.rs (line 245)
203fn main() {
204    let cli_args = CliArgs::from_env();
205
206    if print_help_if_requested(&cli_args) {
207        return;
208    }
209
210    let seed = cli_args.seed_or(42);
211    let input_path = resolve_input_path(&cli_args);
212    let input_format = resolve_input_format(&cli_args, &input_path)
213        .unwrap_or_else(|msg| panic!("{}", msg));
214    let records_path = records_path_for_format(input_format);
215    let weight_key = weight_key_for_format(input_format);
216    let value_key = value_key_for_format(input_format);
217    let (capacity, row_limit) = resolve_capacity_and_limit(&cli_args, &input_path, input_format)
218        .unwrap_or_else(|msg| panic!("{}", msg));
219
220    let records = read_records_from_input(&input_path, input_format, records_path)
221        .unwrap_or_else(|msg| panic!("{}", msg));
222
223    let (problem, loaded_items) =
224        build_knapsack_from_records(&records, capacity, row_limit, weight_key, value_key)
225            .unwrap_or_else(|msg| panic!("{}", msg));
226
227    // Build the algorithm 
228    let parameters = GeneticAlgorithmParameters::new(
229        80,
230        0.85,
231        0.04,
232        SinglePointCrossover::new(),
233        BitFlipMutation::new(),
234        BinaryTournamentSelection::new(),
235        TerminationCriteria::new(vec![TerminationCriterion::MaxIterations(60)]),
236    )
237    .with_seed(seed);
238
239    let chart_observer = ChartObserver::new_default();
240    let html_observer = HtmlReportObserver::new_default();
241
242    let mut algorithm = GeneticAlgorithm::new(parameters);
243    algorithm.add_observer(Box::new(chart_observer));
244    algorithm.add_observer(Box::new(html_observer));
245    let result = algorithm.run(&problem).expect("Large CSV GA run failed");
246
247    if let Some(best) = result.best_solution(&problem) {
248        println!(
249            "Large dataset GA demo finished (seed={}). input='{}', format={:?}, capacity={}, limit={}, records_path='{}', weight_key='{}', value_key='{}', items={}, best fitness={:.4}",
250            seed,
251            input_path.display(),
252            input_format,
253            capacity,
254            row_limit,
255            records_path,
256            weight_key,
257            value_key,
258            loaded_items,
259            best.quality_value()
260        );
261    } else {
262        println!("Large CSV GA demo finished with no solutions (seed={})", seed);
263    }
264}
Source

fn validate_parameters(&self) -> Result<(), String>

Returns Ok(()) when parameters are valid, or Err(message) otherwise.

Source

fn checkpoint_algorithm_parameters(&self) -> String

Returns a string used to fingerprint algorithm checkpoint compatibility.

Source

fn get_resume_checkpoint( &self, runtime_metadata: &CheckpointRuntimeMetadata<'_>, checkpoint_policy: &CheckpointPolicy, ) -> Option<CheckpointRecord>

Resolves a resumable checkpoint when --resume is present.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§

Source§

impl Algorithm<bool> for PSO

Source§

impl Algorithm<f64> for DifferentialEvolution

Source§

impl<C, M, Sel> Algorithm<f64, ParetoCrowdingDistanceQuality> for NSGAII<C, M, Sel>

Source§

impl<T, C, M, Sel> Algorithm<T> for GeneticAlgorithm<T, C, M, Sel>
where T: Clone + Send + Sync + 'static + Display + FromStr, C: CrossoverOperator<T> + Send + Sync, M: MutationOperator<T> + Send + Sync, Sel: SelectionOperator<T> + Send + Sync,

Source§

type SolutionSet = VectorSolutionSet<T>

Source§

type Parameters = GeneticAlgorithmParameters<T, C, M, Sel>

Source§

type StepState = GeneticAlgorithmState<T>

Source§

impl<T, N, Mem> Algorithm<T> for TabuSearch<T, N, Mem>
where T: Clone + Send + Sync + 'static + Display + FromStr + Debug, N: NeighborhoodOperator<T> + Send + Sync, Mem: TabuMemoryOperator<T> + Send + Sync,

Source§

impl<T, N> Algorithm<T> for HillClimbing<T, N>
where T: Clone + Send + Sync + 'static + Display + FromStr + Debug, N: NeighborhoodOperator<T> + Send + Sync,

Source§

impl<T, N> Algorithm<T> for SimulatedAnnealing<T, N>
where T: Clone + Send + Sync + 'static + Display + FromStr, N: NeighborhoodOperator<T> + Send + Sync,

Source§

impl<T, N> Algorithm<T> for VNS<T, N>
where T: Clone + Send + Sync + 'static + Display + FromStr + Debug, N: NeighborhoodOperator<T> + Send + Sync,