Skip to main content

argmin/core/
result.rs

1// Copyright 2018-2024 argmin developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use crate::core::{ArgminFloat, Problem, Solver, State};
9use num_traits::{Float, FromPrimitive};
10use std::cmp::Ordering;
11use std::fmt;
12
13/// Result of an optimization returned by after running an `Executor`.
14///
15/// Consists of the problem and the final state of the solver.
16/// Both can be accessed via deconstructing or via the methods
17/// [`problem`](`OptimizationResult::problem`) and [`state`](`OptimizationResult::state`).
18#[derive(Clone)]
19pub struct OptimizationResult<O, S, I> {
20    /// Problem
21    pub problem: Problem<O>,
22    /// Solver
23    pub solver: S,
24    /// Iteration state
25    pub state: I,
26}
27
28impl<O, S, I> OptimizationResult<O, S, I> {
29    /// Constructs a new instance of `OptimizationResult` from a `problem` and a `state`.
30    ///
31    /// # Example
32    ///
33    /// ```
34    /// # use argmin::core::{Problem, OptimizationResult, IterState, State};
35    /// # use argmin::core::test_utils::TestProblem;
36    /// #
37    /// # type Rosenbrock = TestProblem;
38    /// # #[derive(Eq, PartialEq, Debug)]
39    /// # struct SomeSolver {}
40    /// #
41    /// let rosenbrock = Rosenbrock::new();
42    /// let state: IterState<Vec<f64>, (), (), (), (), f64> = IterState::new();
43    /// let solver = SomeSolver {};
44    ///
45    /// let result = OptimizationResult::new(Problem::new(rosenbrock), solver, state);
46    /// # let OptimizationResult { mut problem, solver, state } = result;
47    /// # assert_eq!(problem.take_problem().unwrap(), TestProblem::new());
48    /// # assert_eq!(solver, SomeSolver {});
49    /// ```
50    pub fn new(problem: Problem<O>, solver: S, state: I) -> Self {
51        OptimizationResult {
52            problem,
53            solver,
54            state,
55        }
56    }
57
58    /// Returns a reference to the stored problem.
59    ///
60    /// # Example
61    ///
62    /// ```
63    /// # use argmin::core::{Problem, OptimizationResult, IterState, State};
64    /// #
65    /// # struct Rosenbrock {}
66    /// # let solver = ();
67    /// #
68    /// # let state: IterState<Vec<f64>, (), (), (), (), f64> = IterState::new();
69    /// #
70    /// # let result = OptimizationResult::new(Problem::new(Rosenbrock {}), solver, state);
71    /// #
72    /// let problem: &Problem<Rosenbrock> = result.problem();
73    /// ```
74    pub fn problem(&self) -> &Problem<O> {
75        &self.problem
76    }
77
78    /// Returns a reference to the stored solver.
79    ///
80    /// # Example
81    ///
82    /// ```
83    /// # use argmin::core::{Problem, OptimizationResult, IterState, State};
84    /// #
85    /// # struct Rosenbrock {}
86    /// # let solver = ();
87    /// #
88    /// # let state: IterState<Vec<f64>, (), (), (), (), f64> = IterState::new();
89    /// #
90    /// # let result = OptimizationResult::new(Problem::new(Rosenbrock {}), solver, state);
91    /// #
92    /// let solver = result.solver();
93    /// ```
94    pub fn solver(&self) -> &S {
95        &self.solver
96    }
97
98    /// Returns a reference to the stored state.
99    ///
100    /// # Example
101    ///
102    /// ```
103    /// # use argmin::core::{Problem, OptimizationResult, IterState, State};
104    /// #
105    /// # struct Rosenbrock {}
106    /// # let solver = ();
107    /// #
108    /// # let state: IterState<Vec<f64>, (), (), (), (), f64> = IterState::new();
109    /// #
110    /// # let result = OptimizationResult::new(Problem::new(Rosenbrock {}), solver, state);
111    /// #
112    /// let state: &IterState<Vec<f64>, (), (), (), (), f64> = result.state();
113    /// ```
114    pub fn state(&self) -> &I {
115        &self.state
116    }
117}
118
119impl<O, S, I> std::fmt::Display for OptimizationResult<O, S, I>
120where
121    I: State,
122    I::Param: fmt::Debug,
123    S: Solver<O, I>,
124{
125    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
126        writeln!(f, "OptimizationResult:")?;
127        writeln!(f, "    Solver:        {}", self.solver.name())?;
128        writeln!(
129            f,
130            "    param (best):  {}",
131            if let Some(best_param) = self.state.get_best_param() {
132                format!("{best_param:?}")
133            } else {
134                String::from("None")
135            }
136        )?;
137        writeln!(f, "    cost (best):   {}", self.state.get_best_cost())?;
138        writeln!(f, "    iters (best):  {}", self.state.get_last_best_iter())?;
139        writeln!(f, "    iters (total): {}", self.state.get_iter())?;
140        writeln!(
141            f,
142            "    termination:   {}",
143            self.state.get_termination_status()
144        )?;
145        if let Some(time) = self.state.get_time() {
146            writeln!(f, "    time:          {time:?}")?;
147        }
148        Ok(())
149    }
150}
151
152impl<O, S, I: State> PartialEq for OptimizationResult<O, S, I>
153where
154    I::Float: ArgminFloat,
155{
156    /// Two `OptimizationResult`s are equal if the absolute of the difference between their best
157    /// cost values is smaller than epsilon.
158    fn eq(&self, other: &OptimizationResult<O, S, I>) -> bool {
159        (self.state.get_best_cost() - other.state.get_best_cost()).abs() < I::Float::epsilon()
160    }
161}
162
163impl<O, S, I: State> Eq for OptimizationResult<O, S, I> {}
164
165impl<O, S, I: State> Ord for OptimizationResult<O, S, I> {
166    /// Two `OptimizationResult`s are equal if the absolute of the difference between their best
167    /// cost values is smaller than epsilon.
168    /// Else, an `OptimizationResult` is better if the best cost function value is strictly better
169    /// than the others.
170    fn cmp(&self, other: &OptimizationResult<O, S, I>) -> Ordering {
171        let t = self.state.get_best_cost() - other.state.get_best_cost();
172        if t.abs() < I::Float::epsilon() {
173            Ordering::Equal
174        } else if t > I::Float::from_f64(0.0).unwrap() {
175            Ordering::Greater
176        } else {
177            Ordering::Less
178        }
179    }
180}
181
182impl<O, S, I: State> PartialOrd for OptimizationResult<O, S, I> {
183    /// Two `OptimizationResult`s are equal if the absolute of the difference between their best
184    /// cost values is smaller than epsilon.
185    /// Else, an `OptimizationResult` is better if the best cost function value is strictly better
186    /// than the others.
187    fn partial_cmp(&self, other: &OptimizationResult<O, S, I>) -> Option<Ordering> {
188        Some(self.cmp(other))
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195    use crate::core::{
196        test_utils::{TestProblem, TestSolver},
197        IterState,
198    };
199
200    send_sync_test!(
201        optimizationresult,
202        OptimizationResult<TestProblem, TestSolver, IterState<(), (), (), (), (), f64>>
203    );
204
205    // TODO: More tests, in particular the checking that the output is as intended.
206}