Skip to main content

solverforge_solver/
run.rs

1/* Solver entry point. */
2
3use std::fmt;
4use std::marker::PhantomData;
5use std::path::Path;
6use std::time::Duration;
7
8use solverforge_config::SolverConfig;
9use solverforge_core::domain::{PlanningSolution, SolutionDescriptor};
10use solverforge_core::score::{ParseableScore, Score};
11use solverforge_scoring::{ConstraintSet, Director, ScoreDirector};
12use tracing::info;
13
14use crate::manager::{SolverRuntime, SolverTerminalReason};
15use crate::phase::{Phase, PhaseSequence};
16use crate::scope::{ProgressCallback, SolverProgressKind, SolverProgressRef, SolverScope};
17use crate::solver::Solver;
18use crate::stats::{format_duration, whole_units_per_second};
19use crate::termination::{
20    BestScoreTermination, OrTermination, StepCountTermination, Termination, TimeTermination,
21    UnimprovedStepCountTermination, UnimprovedTimeTermination,
22};
23
24/// Monomorphized termination enum for config-driven solver configurations.
25///
26/// Avoids repeated branching across termination overloads by capturing the
27/// selected termination variant upfront.
28pub enum AnyTermination<S: PlanningSolution, D: Director<S>> {
29    Default(OrTermination<(TimeTermination,), S, D>),
30    WithBestScore(OrTermination<(TimeTermination, BestScoreTermination<S::Score>), S, D>),
31    WithStepCount(OrTermination<(TimeTermination, StepCountTermination), S, D>),
32    WithUnimprovedStep(OrTermination<(TimeTermination, UnimprovedStepCountTermination<S>), S, D>),
33    WithUnimprovedTime(OrTermination<(TimeTermination, UnimprovedTimeTermination<S>), S, D>),
34}
35
36#[derive(Clone)]
37pub struct ChannelProgressCallback<S: PlanningSolution> {
38    runtime: SolverRuntime<S>,
39    _phantom: PhantomData<fn() -> S>,
40}
41
42impl<S: PlanningSolution> ChannelProgressCallback<S> {
43    fn new(runtime: SolverRuntime<S>) -> Self {
44        Self {
45            runtime,
46            _phantom: PhantomData,
47        }
48    }
49}
50
51impl<S: PlanningSolution> fmt::Debug for ChannelProgressCallback<S> {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        f.debug_struct("ChannelProgressCallback").finish()
54    }
55}
56
57impl<S: PlanningSolution> ProgressCallback<S> for ChannelProgressCallback<S> {
58    fn invoke(&self, progress: SolverProgressRef<'_, S>) {
59        match progress.kind {
60            SolverProgressKind::Progress => {
61                self.runtime.emit_progress(
62                    progress.current_score.copied(),
63                    progress.best_score.copied(),
64                    progress.telemetry,
65                );
66            }
67            SolverProgressKind::BestSolution => {
68                if let (Some(solution), Some(score)) = (progress.solution, progress.best_score) {
69                    self.runtime.emit_best_solution(
70                        (*solution).clone(),
71                        progress.current_score.copied(),
72                        *score,
73                        progress.telemetry,
74                    );
75                }
76            }
77        }
78    }
79}
80
81impl<S: PlanningSolution, D: Director<S>> fmt::Debug for AnyTermination<S, D> {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        match self {
84            Self::Default(_) => write!(f, "AnyTermination::Default"),
85            Self::WithBestScore(_) => write!(f, "AnyTermination::WithBestScore"),
86            Self::WithStepCount(_) => write!(f, "AnyTermination::WithStepCount"),
87            Self::WithUnimprovedStep(_) => write!(f, "AnyTermination::WithUnimprovedStep"),
88            Self::WithUnimprovedTime(_) => write!(f, "AnyTermination::WithUnimprovedTime"),
89        }
90    }
91}
92
93impl<S: PlanningSolution, D: Director<S>, ProgressCb: ProgressCallback<S>>
94    Termination<S, D, ProgressCb> for AnyTermination<S, D>
95where
96    S::Score: Score,
97{
98    fn is_terminated(&self, solver_scope: &SolverScope<S, D, ProgressCb>) -> bool {
99        match self {
100            Self::Default(t) => t.is_terminated(solver_scope),
101            Self::WithBestScore(t) => t.is_terminated(solver_scope),
102            Self::WithStepCount(t) => t.is_terminated(solver_scope),
103            Self::WithUnimprovedStep(t) => t.is_terminated(solver_scope),
104            Self::WithUnimprovedTime(t) => t.is_terminated(solver_scope),
105        }
106    }
107
108    fn install_inphase_limits(&self, solver_scope: &mut SolverScope<S, D, ProgressCb>) {
109        match self {
110            Self::Default(t) => t.install_inphase_limits(solver_scope),
111            Self::WithBestScore(t) => t.install_inphase_limits(solver_scope),
112            Self::WithStepCount(t) => t.install_inphase_limits(solver_scope),
113            Self::WithUnimprovedStep(t) => t.install_inphase_limits(solver_scope),
114            Self::WithUnimprovedTime(t) => t.install_inphase_limits(solver_scope),
115        }
116    }
117}
118
119/// Builds a termination from config, returning both the termination and the time limit.
120pub fn build_termination<S, C>(
121    config: &SolverConfig,
122    default_secs: u64,
123) -> (AnyTermination<S, ScoreDirector<S, C>>, Duration)
124where
125    S: PlanningSolution,
126    S::Score: Score + ParseableScore,
127    C: ConstraintSet<S, S::Score>,
128{
129    let term_config = config.termination.as_ref();
130    let time_limit = term_config
131        .and_then(|c| c.time_limit())
132        .unwrap_or(Duration::from_secs(default_secs));
133    let time = TimeTermination::new(time_limit);
134
135    let best_score_target: Option<S::Score> = term_config
136        .and_then(|c| c.best_score_limit.as_ref())
137        .and_then(|s| S::Score::parse(s).ok());
138
139    let termination = if let Some(target) = best_score_target {
140        AnyTermination::WithBestScore(OrTermination::new((
141            time,
142            BestScoreTermination::new(target),
143        )))
144    } else if let Some(step_limit) = term_config.and_then(|c| c.step_count_limit) {
145        AnyTermination::WithStepCount(OrTermination::new((
146            time,
147            StepCountTermination::new(step_limit),
148        )))
149    } else if let Some(unimproved_step_limit) =
150        term_config.and_then(|c| c.unimproved_step_count_limit)
151    {
152        AnyTermination::WithUnimprovedStep(OrTermination::new((
153            time,
154            UnimprovedStepCountTermination::<S>::new(unimproved_step_limit),
155        )))
156    } else if let Some(unimproved_time) = term_config.and_then(|c| c.unimproved_time_limit()) {
157        AnyTermination::WithUnimprovedTime(OrTermination::new((
158            time,
159            UnimprovedTimeTermination::<S>::new(unimproved_time),
160        )))
161    } else {
162        AnyTermination::Default(OrTermination::new((time,)))
163    };
164
165    (termination, time_limit)
166}
167
168pub fn log_solve_start(
169    entity_count: usize,
170    element_count: Option<usize>,
171    has_standard: Option<bool>,
172    variable_count: Option<usize>,
173) {
174    info!(
175        event = "solve_start",
176        entity_count = entity_count,
177        value_count = element_count.or(variable_count).unwrap_or(0),
178        solve_shape = if element_count.is_some() {
179            "list"
180        } else if has_standard.unwrap_or(false) {
181            "standard"
182        } else {
183            "solution"
184        },
185    );
186}
187
188fn load_solver_config_from(path: impl AsRef<Path>) -> SolverConfig {
189    SolverConfig::load(path).unwrap_or_default()
190}
191
192fn load_solver_config() -> SolverConfig {
193    load_solver_config_from("solver.toml")
194}
195
196#[allow(clippy::too_many_arguments)]
197pub fn run_solver<S, C, P>(
198    solution: S,
199    constraints_fn: fn() -> C,
200    descriptor: fn() -> SolutionDescriptor,
201    entity_count_by_descriptor: fn(&S, usize) -> usize,
202    runtime: SolverRuntime<S>,
203    default_time_limit_secs: u64,
204    is_trivial: fn(&S) -> bool,
205    log_scale: fn(&S),
206    build_phases: fn(&SolverConfig) -> PhaseSequence<P>,
207) -> S
208where
209    S: PlanningSolution,
210    S::Score: Score + ParseableScore,
211    C: ConstraintSet<S, S::Score>,
212    P: Send + std::fmt::Debug,
213    PhaseSequence<P>: Phase<S, ScoreDirector<S, C>, ChannelProgressCallback<S>>,
214{
215    let config = load_solver_config();
216    run_solver_with_config(
217        solution,
218        constraints_fn,
219        descriptor,
220        entity_count_by_descriptor,
221        runtime,
222        config,
223        default_time_limit_secs,
224        is_trivial,
225        log_scale,
226        build_phases,
227    )
228}
229
230#[allow(clippy::too_many_arguments)]
231pub fn run_solver_with_config<S, C, P>(
232    solution: S,
233    constraints_fn: fn() -> C,
234    descriptor: fn() -> SolutionDescriptor,
235    entity_count_by_descriptor: fn(&S, usize) -> usize,
236    runtime: SolverRuntime<S>,
237    config: SolverConfig,
238    default_time_limit_secs: u64,
239    is_trivial: fn(&S) -> bool,
240    log_scale: fn(&S),
241    build_phases: fn(&SolverConfig) -> PhaseSequence<P>,
242) -> S
243where
244    S: PlanningSolution,
245    S::Score: Score + ParseableScore,
246    C: ConstraintSet<S, S::Score>,
247    P: Send + std::fmt::Debug,
248    PhaseSequence<P>: Phase<S, ScoreDirector<S, C>, ChannelProgressCallback<S>>,
249{
250    log_scale(&solution);
251    let trivial = is_trivial(&solution);
252
253    let constraints = constraints_fn();
254    let director = ScoreDirector::with_descriptor(
255        solution,
256        constraints,
257        descriptor(),
258        entity_count_by_descriptor,
259    );
260
261    if trivial {
262        let mut solver_scope = SolverScope::new(director);
263        solver_scope = solver_scope.with_runtime(Some(runtime));
264        if let Some(seed) = config.random_seed {
265            solver_scope = solver_scope.with_seed(seed);
266        }
267        solver_scope.start_solving();
268        let score = solver_scope.calculate_score();
269        let solution = solver_scope.score_director().clone_working_solution();
270        solver_scope.set_best_solution(solution.clone(), score);
271        solver_scope.report_best_solution();
272        solver_scope.pause_if_requested();
273        info!(event = "solve_end", score = %score);
274        let telemetry = solver_scope.stats().snapshot();
275        if runtime.is_cancel_requested() {
276            runtime.emit_cancelled(Some(score), Some(score), telemetry);
277        } else {
278            runtime.emit_completed(
279                solution.clone(),
280                Some(score),
281                score,
282                telemetry,
283                SolverTerminalReason::Completed,
284            );
285        }
286        return solution;
287    }
288
289    let (termination, time_limit) = build_termination::<S, C>(&config, default_time_limit_secs);
290
291    let callback = ChannelProgressCallback::new(runtime);
292
293    let phases = build_phases(&config);
294    let solver = Solver::new((phases,))
295        .with_config(config.clone())
296        .with_termination(termination)
297        .with_time_limit(time_limit)
298        .with_runtime(runtime)
299        .with_progress_callback(callback);
300
301    let result = solver.with_terminate(runtime.cancel_flag()).solve(director);
302
303    let crate::solver::SolveResult {
304        solution,
305        current_score,
306        best_score: final_score,
307        terminal_reason,
308        stats,
309    } = result;
310    let final_telemetry = stats.snapshot();
311    let final_move_speed = whole_units_per_second(stats.moves_evaluated, stats.elapsed());
312    match terminal_reason {
313        SolverTerminalReason::Completed | SolverTerminalReason::TerminatedByConfig => {
314            runtime.emit_completed(
315                solution.clone(),
316                current_score,
317                final_score,
318                final_telemetry,
319                terminal_reason,
320            );
321        }
322        SolverTerminalReason::Cancelled => {
323            runtime.emit_cancelled(current_score, Some(final_score), final_telemetry);
324        }
325        SolverTerminalReason::Failed => unreachable!("solver completion cannot report failure"),
326    }
327
328    info!(
329        event = "solve_end",
330        score = %final_score,
331        steps = stats.step_count,
332        moves_generated = stats.moves_generated,
333        moves_evaluated = stats.moves_evaluated,
334        moves_accepted = stats.moves_accepted,
335        score_calculations = stats.score_calculations,
336        generation_time = %format_duration(stats.generation_time()),
337        evaluation_time = %format_duration(stats.evaluation_time()),
338        moves_speed = final_move_speed,
339        acceptance_rate = format!("{:.1}%", stats.acceptance_rate() * 100.0),
340    );
341    solution
342}
343
344#[cfg(test)]
345#[path = "run_tests.rs"]
346mod tests;