cnvx_core/solution.rs
1use crate::{SolveStatus, VarId};
2use std::fmt::Display;
3
4/// Represents the result of solving an optimization problem.
5///
6/// Contains the values assigned to each variable, the value of the objective function,
7/// and the solver status.
8///
9/// # Examples
10///
11/// ```rust
12/// use cnvx_core::{Solution, SolveStatus, VarId};
13///
14/// // Example solution with 3 variables
15/// let solution = Solution {
16/// values: vec![1.0, 2.0, 3.0],
17/// objective_value: Some(10.0),
18/// status: SolveStatus::Optimal,
19/// };
20///
21/// assert_eq!(solution.value(VarId(0)), 1.0);
22/// assert_eq!(solution.value(VarId(2)), 3.0);
23/// ```
24#[derive(Debug)]
25pub struct Solution {
26 /// Variable assignments, indexed by variable ID.
27 ///
28 /// The value at index `i` corresponds to the variable with ID [`VarId(i)`](VarId).
29 pub values: Vec<f64>,
30
31 /// The value of the objective function at the solution.
32 ///
33 /// [`None`] if the solver did not produce an objective value (e.g., infeasible or unbounded problem).
34 pub objective_value: Option<f64>,
35
36 /// The solver status indicating whether the solution is optimal, feasible, infeasible, or unbounded.
37 pub status: SolveStatus,
38}
39
40impl Solution {
41 /// Returns the value assigned to the variable with the given [`VarId`].
42 ///
43 /// # Example
44 ///
45 /// ```rust
46 /// # use cnvx_core::{Model, Solution, SolveStatus, VarId};
47 /// # let mut model = Model::new();
48 /// let x1: VarId = model.add_var().finish();
49 /// let solution = Solution {
50 /// values: vec![1.0], // Assuming x1 has ID 0
51 /// objective_value: Some(10.0),
52 /// status: SolveStatus::Optimal,
53 /// };
54 /// let value = solution.value(x1);
55 /// ```
56 pub fn value(&self, var: VarId) -> f64 {
57 self.values[var.0]
58 }
59}
60
61impl Display for Solution {
62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 if let Some(obj_val) = self.objective_value {
64 write!(f, "{}: {}", self.status, obj_val)?;
65 } else {
66 write!(f, "{}", self.status)?;
67 }
68 Ok(())
69 }
70}