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, context: &ExecutionContext<T, Q>, ); fn build_snapshot( &self, problem: &(impl Problem<T, Q> + Sync), state: &Self::StepState, ) -> ExecutionStateSnapshot<T, Q>; 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, problem: &(impl Problem<T, Q> + Sync), checkpoint_dir: &PathBuf, ) -> 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§

Source

type SolutionSet: SolutionSet<T, Q>

Source

type Parameters

Source

type StepState: StepStateCheckpoint<T, Q>

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, context: &ExecutionContext<T, Q>, )

Source

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

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 = seed_from_cli_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 38)
15fn main() {
16    let seed = seed_from_cli_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        BitFlipMutation::new(),
27        0.10,
28        TerminationCriteria::new(vec![TerminationCriterion::MaxIterations(120)]),
29    )
30    .with_seed(seed);
31    let mut algorithm = HillClimbing::new(parameters);
32
33    algorithm.add_observer(Box::new(ConsoleObserver::new(true)));
34    algorithm.add_observer(Box::new(ChartObserver::new_default()));
35    algorithm.add_observer(Box::new(HtmlReportObserver::new_default()));
36
37    let result = algorithm
38        .run(&problem)
39        .expect("Hill Climbing run failed");
40
41    if let Some(best) = result.best_solution(&problem) {
42        println!(
43            "Hill-Climbing finished (seed={}). Best fitness={:.4}",
44            seed,
45            best.quality_value()
46        );
47    } else {
48        println!("Hill-Climbing finished with no solutions (seed={})", seed);
49    }
50}
examples/knapsack_ga_demo.rs (line 45)
14fn main() {
15    let seed = seed_from_cli_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(40)]),
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 235)
196fn main() {
197    if print_help_if_requested() {
198        return;
199    }
200
201    let seed = seed_from_cli_or(42);
202    let input_path = resolve_input_path();
203    let input_format = resolve_input_format(&input_path).unwrap_or_else(|msg| panic!("{}", msg));
204    let records_path = records_path_for_format(input_format);
205    let weight_key = weight_key_for_format(input_format);
206    let value_key = value_key_for_format(input_format);
207    let (capacity, row_limit) =
208        resolve_capacity_and_limit(&input_path, input_format).unwrap_or_else(|msg| panic!("{}", msg));
209
210    let records = read_records_from_input(&input_path, input_format, records_path)
211        .unwrap_or_else(|msg| panic!("{}", msg));
212
213    let (problem, loaded_items) =
214        build_knapsack_from_records(&records, capacity, row_limit, weight_key, value_key)
215            .unwrap_or_else(|msg| panic!("{}", msg));
216
217    // Build the algorithm 
218    let parameters = GeneticAlgorithmParameters::new(
219        80,
220        0.85,
221        0.04,
222        SinglePointCrossover::new(),
223        BitFlipMutation::new(),
224        BinaryTournamentSelection::new(),
225        TerminationCriteria::new(vec![TerminationCriterion::MaxIterations(60)]),
226    )
227    .with_seed(seed);
228
229    let chart_observer = ChartObserver::new_default();
230    let html_observer = HtmlReportObserver::new_default();
231
232    let mut algorithm = GeneticAlgorithm::new(parameters);
233    algorithm.add_observer(Box::new(chart_observer));
234    algorithm.add_observer(Box::new(html_observer));
235    let result = algorithm.run(&problem).expect("Large CSV GA run failed");
236
237    if let Some(best) = result.best_solution(&problem) {
238        println!(
239            "Large dataset GA demo finished (seed={}). input='{}', format={:?}, capacity={}, limit={}, records_path='{}', weight_key='{}', value_key='{}', items={}, best fitness={:.4}",
240            seed,
241            input_path.display(),
242            input_format,
243            capacity,
244            row_limit,
245            records_path,
246            weight_key,
247            value_key,
248            loaded_items,
249            best.quality_value()
250        );
251    } else {
252        println!("Large CSV GA demo finished with no solutions (seed={})", seed);
253    }
254}
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, problem: &(impl Problem<T, Q> + Sync), checkpoint_dir: &PathBuf, ) -> Option<CheckpointRecord>

Resolves a resumable checkpoint when --resume is present.

This method resolves the checkpoint directory, computes algorithm/problem identity fingerprints and delegates checkpoint selection to the checkpoint module. It returns None when resume is disabled, no compatible checkpoint is found, or selection fails.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

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, M> Algorithm<T> for HillClimbing<T, M>
where T: Clone + Send + Sync + 'static + Display + FromStr + Debug, M: MutationOperator<T> + Send + Sync,

Source§

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

Source§

impl<T, M> Algorithm<T> for TabuSearch<T, M>
where T: Clone + Send + Sync + 'static + Display + FromStr + Debug, M: MutationOperator<T> + Send + Sync,

Source§

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