scirs2_optimize/
result.rs

1//! Optimization result structures
2//!
3//! This module defines the common result structures for optimization algorithms.
4
5use scirs2_core::ndarray::Array1;
6use scirs2_core::numeric::Zero;
7use std::fmt;
8
9/// A structure that contains the results of an optimization.
10///
11/// This structure is modeled after SciPy's `OptimizeResult` structure.
12#[derive(Clone, Debug)]
13pub struct OptimizeResults<T> {
14    /// The solution array
15    pub x: Array1<T>,
16
17    /// Value of objective function at the solution
18    pub fun: T,
19
20    /// Value of the gradient/jacobian at the solution
21    pub jac: Option<Vec<T>>,
22
23    /// Value of the Hessian at the solution
24    pub hess: Option<Vec<T>>,
25
26    /// Value of constraint functions at the solution (if applicable)
27    pub constr: Option<Array1<T>>,
28
29    /// Number of iterations performed
30    pub nit: usize,
31
32    /// Number of evaluations of the objective function
33    pub nfev: usize,
34
35    /// Number of evaluations of the gradient
36    pub njev: usize,
37
38    /// Number of evaluations of the Hessian
39    pub nhev: usize,
40
41    /// Maximum number of iterations exceeded flag
42    pub maxcv: usize,
43
44    /// Termination message
45    pub message: String,
46
47    /// Whether or not the optimizer exited successfully
48    pub success: bool,
49
50    /// Termination status code
51    pub status: i32,
52}
53
54impl<T: fmt::Display + fmt::Debug> fmt::Display for OptimizeResults<T>
55where
56    T: Copy,
57    Array1<T>: fmt::Debug,
58{
59    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60        writeln!(f, "Optimization Results:")?;
61        writeln!(f, "  success: {}", self.success)?;
62        writeln!(f, "  status: {}", self.status)?;
63        writeln!(f, "  message: {}", self.message)?;
64        writeln!(f, "  nfev: {}", self.nfev)?;
65        writeln!(f, "  njev: {}", self.njev)?;
66        writeln!(f, "  nhev: {}", self.nhev)?;
67        writeln!(f, "  nit: {}", self.nit)?;
68        writeln!(f, "  final value: {}", self.fun)?;
69        writeln!(f, "  solution: {:?}", self.x)?;
70        if let Some(ref jac) = self.jac {
71            writeln!(f, "  jacobian: {:?} (vector)", jac)?;
72        }
73        Ok(())
74    }
75}
76
77impl<T> Default for OptimizeResults<T>
78where
79    T: Default + Clone + Zero,
80{
81    fn default() -> Self {
82        OptimizeResults {
83            x: Array1::<T>::zeros(0),
84            fun: T::default(),
85            jac: None,
86            hess: None,
87            constr: None,
88            nit: 0,
89            nfev: 0,
90            njev: 0,
91            nhev: 0,
92            maxcv: 0,
93            message: String::new(),
94            success: false,
95            status: 0,
96        }
97    }
98}