solverforge_solver/termination/
best_score.rs1use std::fmt::Debug;
4
5use solverforge_core::domain::PlanningSolution;
6use solverforge_core::score::Score;
7use solverforge_scoring::Director;
8
9use super::Termination;
10use crate::scope::BestSolutionCallback;
11use crate::scope::SolverScope;
12
13#[derive(Debug, Clone)]
28pub struct BestScoreTermination<Sc: Score> {
29 target_score: Sc,
30}
31
32impl<Sc: Score> BestScoreTermination<Sc> {
33 pub fn new(target_score: Sc) -> Self {
35 Self { target_score }
36 }
37}
38
39impl<S, D, BestCb, Sc> Termination<S, D, BestCb> for BestScoreTermination<Sc>
40where
41 S: PlanningSolution<Score = Sc>,
42 D: Director<S>,
43 BestCb: BestSolutionCallback<S>,
44 Sc: Score,
45{
46 fn is_terminated(&self, solver_scope: &SolverScope<S, D, BestCb>) -> bool {
47 solver_scope
48 .best_score()
49 .map(|score| *score >= self.target_score)
50 .unwrap_or(false)
51 }
52}
53
54pub struct BestScoreFeasibleTermination<S, F>
65where
66 S: PlanningSolution,
67 F: Fn(&S::Score) -> bool + Send + Sync,
68{
69 feasibility_check: F,
70 _phantom: std::marker::PhantomData<fn() -> S>,
71}
72
73impl<S, F> Debug for BestScoreFeasibleTermination<S, F>
74where
75 S: PlanningSolution,
76 F: Fn(&S::Score) -> bool + Send + Sync,
77{
78 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79 f.debug_struct("BestScoreFeasibleTermination").finish()
80 }
81}
82
83impl<S, F> BestScoreFeasibleTermination<S, F>
84where
85 S: PlanningSolution,
86 F: Fn(&S::Score) -> bool + Send + Sync,
87{
88 pub fn new(feasibility_check: F) -> Self {
90 Self {
91 feasibility_check,
92 _phantom: std::marker::PhantomData,
93 }
94 }
95}
96
97impl<S: PlanningSolution> BestScoreFeasibleTermination<S, fn(&S::Score) -> bool> {
98 pub fn score_at_least_zero() -> Self {
102 Self::new(|score| *score >= S::Score::zero())
103 }
104}
105
106impl<S, D, BestCb, F> Termination<S, D, BestCb> for BestScoreFeasibleTermination<S, F>
107where
108 S: PlanningSolution,
109 D: Director<S>,
110 BestCb: BestSolutionCallback<S>,
111 F: Fn(&S::Score) -> bool + Send + Sync,
112{
113 fn is_terminated(&self, solver_scope: &SolverScope<S, D, BestCb>) -> bool {
114 solver_scope
115 .best_score()
116 .map(|score| (self.feasibility_check)(score))
117 .unwrap_or(false)
118 }
119}