Skip to main content

crisol_plot/plot/
fit.rs

1//! Least-squares fits: the math lives in `crisol-plot-core`; this adapter keeps the
2//! plot-facing type and turns a fit into a series.
3
4#[doc(inline)]
5pub use crisol_plot_core::fit::FitKind;
6
7use super::series::{LineStyle, Series};
8
9/// A fitted model: its coefficients, its goodness of fit, and an evaluator.
10#[derive(Clone, Debug, PartialEq)]
11pub struct Fit {
12    /// The model.
13    pub kind: FitKind,
14    /// Coefficients: `[a, b]` for two-parameter models, `c₀…cₙ` for polynomials.
15    pub coefficients: Vec<f64>,
16    /// Coefficient of determination on the original data (1 = perfect).
17    pub r_squared: f64,
18    /// Smallest and largest x of the fitted points.
19    pub x_range: (f64, f64),
20    inner: crisol_plot_core::fit::Fit,
21}
22
23impl Fit {
24    /// Fit `kind` to `data`. Returns `None` for too few usable points or a singular
25    /// system.
26    pub fn new(kind: FitKind, data: &[[f64; 2]]) -> Option<Self> {
27        let inner = crisol_plot_core::fit::Fit::new(kind, data)?;
28        Some(Self {
29            kind: inner.kind,
30            coefficients: inner.coefficients.clone(),
31            r_squared: inner.r_squared,
32            x_range: inner.x_range,
33            inner,
34        })
35    }
36
37    /// The model value at `x` (`NaN` outside the model's domain).
38    pub fn eval(&self, x: f64) -> f64 {
39        self.inner.eval(x)
40    }
41
42    /// A short equation such as `y = 2.01x + 0.498`, with `R² = 0.998` when defined.
43    pub fn equation(&self) -> String {
44        self.inner.equation()
45    }
46
47    /// The fitted curve as a dashed line over the data's x range (`samples` points), or
48    /// the smoothed points for a moving average.
49    pub fn series(&self, name: impl Into<String>, samples: usize) -> Series<'static> {
50        let series = if let FitKind::MovingAverage(_) = self.kind {
51            Series::line(name, self.inner.smoothed().to_vec())
52        } else {
53            let (start, end) = self.x_range;
54            Series::function(name, start..=end, samples, |x| self.eval(x))
55        };
56        series.style(LineStyle::Dashed).width(1.5)
57    }
58}