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)]
29pub struct BestScoreTermination<Sc: Score> {
30 target_score: Sc,
31}
32
33impl<Sc: Score> BestScoreTermination<Sc> {
34 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 {
89 Self {
90 feasibility_check,
91 _phantom: std::marker::PhantomData,
92 }
93 }
94}
95
96impl<S: PlanningSolution> BestScoreFeasibleTermination<S, fn(&S::Score) -> bool> {
97 pub fn score_at_least_zero() -> Self {
101 Self::new(|score| *score >= S::Score::zero())
102 }
103}
104
105impl<S, D, BestCb, F> Termination<S, D, BestCb> for BestScoreFeasibleTermination<S, F>
106where
107 S: PlanningSolution,
108 D: Director<S>,
109 BestCb: BestSolutionCallback<S>,
110 F: Fn(&S::Score) -> bool + Send + Sync,
111{
112 fn is_terminated(&self, solver_scope: &SolverScope<S, D, BestCb>) -> bool {
113 solver_scope
114 .best_score()
115 .map(|score| (self.feasibility_check)(score))
116 .unwrap_or(false)
117 }
118}