Skip to main content

cnvx_core/
solver.rs

1use crate::{Model, Solution, SolveError};
2
3/// Trait for optimization solvers.
4///
5/// Any struct implementing this trait can solve a [`Model`] and produce a [`Solution`].
6/// This trait provides a consistent interface across different solver implementations,
7/// such as simplex, interior point, branch-and-bound, or lexicographic solvers.
8///
9/// ```rust
10/// # use cnvx_core::{Model, Solver, SolveError, Solution};
11/// # struct DummySolver {}
12/// #
13/// # impl Solver<'_> for DummySolver {
14/// #   fn new(model: &Model) -> Self { DummySolver {} }
15/// #   fn solve(&mut self) -> Result<Solution, SolveError> {
16/// #       Err(SolveError::Unsupported("DummySolver does not implement solving".to_string()))
17/// #   }
18/// #   fn get_objective_value(&self) -> f64 { 0.0 }
19/// #   fn get_solution(&self) -> Vec<f64> { vec![] }
20/// # }
21/// let mut model = Model::new();
22/// // ... build model variables, constraints, objective ...
23///
24/// let mut solver = DummySolver::new(&model);
25/// let result: Result<_, SolveError> = solver.solve();
26/// match result {
27///     Ok(solution) => println!("Optimal solution: {}", solution.objective_value.unwrap_or(0.0)),
28///     Err(e) => println!("Solver error: {}", e),
29/// }
30/// ```
31///
32/// Generic over:
33/// - `S`: solver state type
34pub trait Solver<'model> {
35    /// Create a new solver for the given model.
36    fn new(model: &'model Model) -> Self
37    where
38        Self: Sized;
39
40    /// Solve the model.
41    fn solve(&mut self) -> Result<Solution, SolveError>;
42
43    /// Get the current objective value (if available).
44    fn get_objective_value(&self) -> f64;
45
46    /// Return the current solution vector.
47    fn get_solution(&self) -> Vec<f64>;
48}