mahf/conditions/
mod.rs

1//! Metaheuristic algorithm conditions.
2//!
3//! This module contains definition and implementation of [`Condition`]s.
4
5#![allow(clippy::new_ret_no_self)]
6
7use crate::{
8    component::{AnyComponent, ExecResult},
9    state::StateReq,
10    Problem, State,
11};
12
13pub mod common;
14pub mod cro;
15pub mod logical;
16
17pub use common::{ChangeOf, EveryN, LessThanN, OptimumReached, RandomChance};
18pub use logical::{And, Not, Or};
19
20/// Trait to represent a condition *component* for loops or branches.
21///
22/// This is the twin trait to [`Component`], with the difference that the `evaluate`
23/// method replaces `execute` and returns a `bool`.
24///
25/// Specifically, everything in the documentation of [`Component`] also applies to `Condition`s.
26///
27/// [`Component`]: crate::Component
28///
29/// # Combining conditions
30///
31/// `Condition`s can be combined using [`BitAnd`], [`BitOr`], and [`Not`] (`|`, `&`, and `!` operators).
32///
33/// [`BitAnd`]: std::ops::BitAnd
34/// [`BitOr`]: std::ops::BitOr
35/// [`Not`]: std::ops::Not
36pub trait Condition<P: Problem>: AnyComponent {
37    /// Can be used to initialize custom state required by the condition.
38    #[allow(unused_variables)]
39    fn init(&self, problem: &P, state: &mut State<P>) -> ExecResult<()> {
40        Ok(())
41    }
42
43    /// Can be used to specify custom state requirements.
44    #[allow(unused_variables)]
45    fn require(&self, problem: &P, state_req: &StateReq<P>) -> ExecResult<()> {
46        Ok(())
47    }
48
49    /// Evaluates the condition, performing the actual logic.
50    fn evaluate(&self, problem: &P, state: &mut State<P>) -> ExecResult<bool>;
51}
52
53erased_serde::serialize_trait_object!(<P: Problem> Condition<P>);
54dyn_clone::clone_trait_object!(<P: Problem> Condition<P>);