Skip to main content

numra_fit/
types.rs

1//! Types for curve fitting results and options.
2//!
3//! Author: Moussa Leblouba
4//! Date: 9 February 2026
5//! Modified: 2 May 2026
6
7use numra_core::Scalar;
8
9/// Result of a curve fit.
10#[derive(Clone, Debug)]
11pub struct FitResult<S: Scalar> {
12    /// Optimized parameters.
13    pub params: Vec<S>,
14    /// Covariance matrix of parameters (row-major, n_params x n_params).
15    /// `None` if covariance could not be estimated (singular Jacobian).
16    pub covariance: Option<Vec<S>>,
17    /// Standard errors of parameters (sqrt of diagonal of covariance).
18    /// `None` if covariance could not be estimated.
19    pub std_errors: Option<Vec<S>>,
20    /// Residuals at the optimized parameters (y_data - model(x, params)).
21    pub residuals: Vec<S>,
22    /// Sum of squared residuals.
23    pub chi_squared: S,
24    /// Reduced chi-squared: chi_squared / dof.
25    pub reduced_chi_squared: S,
26    /// Coefficient of determination (R-squared).
27    pub r_squared: S,
28    /// Degrees of freedom (n_data - n_params).
29    pub dof: usize,
30    /// Number of function evaluations.
31    pub n_evaluations: usize,
32    /// Whether the optimizer converged.
33    pub converged: bool,
34}
35
36/// Options for curve fitting.
37#[derive(Clone, Debug)]
38pub struct FitOptions<S: Scalar> {
39    /// Maximum iterations.
40    pub max_iter: usize,
41    /// Function tolerance.
42    pub ftol: S,
43    /// Gradient tolerance.
44    pub gtol: S,
45    /// Step tolerance.
46    pub xtol: S,
47}
48
49impl<S: Scalar> Default for FitOptions<S> {
50    fn default() -> Self {
51        Self {
52            max_iter: 200,
53            ftol: S::from_f64(1e-12),
54            gtol: S::from_f64(1e-10),
55            xtol: S::from_f64(1e-10),
56        }
57    }
58}
59
60impl<S: Scalar> FitOptions<S> {
61    /// Set maximum iterations.
62    pub fn max_iter(mut self, n: usize) -> Self {
63        self.max_iter = n;
64        self
65    }
66
67    /// Set function tolerance.
68    pub fn ftol(mut self, v: S) -> Self {
69        self.ftol = v;
70        self
71    }
72
73    /// Set gradient tolerance.
74    pub fn gtol(mut self, v: S) -> Self {
75        self.gtol = v;
76        self
77    }
78
79    /// Set step tolerance.
80    pub fn xtol(mut self, v: S) -> Self {
81        self.xtol = v;
82        self
83    }
84}