crisol-plot 1.9.0

Crisol plot: interactive 2D charts and a 3D sibling with SVG, PNG, and PDF export.
Documentation
//! Least-squares fits: the math lives in `crisol-plot-core`; this adapter keeps the
//! plot-facing type and turns a fit into a series.

#[doc(inline)]
pub use crisol_plot_core::fit::FitKind;

use super::series::{LineStyle, Series};

/// A fitted model: its coefficients, its goodness of fit, and an evaluator.
#[derive(Clone, Debug, PartialEq)]
pub struct Fit {
    /// The model.
    pub kind: FitKind,
    /// Coefficients: `[a, b]` for two-parameter models, `c₀…cₙ` for polynomials.
    pub coefficients: Vec<f64>,
    /// Coefficient of determination on the original data (1 = perfect).
    pub r_squared: f64,
    /// Smallest and largest x of the fitted points.
    pub x_range: (f64, f64),
    inner: crisol_plot_core::fit::Fit,
}

impl Fit {
    /// Fit `kind` to `data`. Returns `None` for too few usable points or a singular
    /// system.
    pub fn new(kind: FitKind, data: &[[f64; 2]]) -> Option<Self> {
        let inner = crisol_plot_core::fit::Fit::new(kind, data)?;
        Some(Self {
            kind: inner.kind,
            coefficients: inner.coefficients.clone(),
            r_squared: inner.r_squared,
            x_range: inner.x_range,
            inner,
        })
    }

    /// The model value at `x` (`NaN` outside the model's domain).
    pub fn eval(&self, x: f64) -> f64 {
        self.inner.eval(x)
    }

    /// A short equation such as `y = 2.01x + 0.498`, with `R² = 0.998` when defined.
    pub fn equation(&self) -> String {
        self.inner.equation()
    }

    /// The fitted curve as a dashed line over the data's x range (`samples` points), or
    /// the smoothed points for a moving average.
    pub fn series(&self, name: impl Into<String>, samples: usize) -> Series<'static> {
        let series = if let FitKind::MovingAverage(_) = self.kind {
            Series::line(name, self.inner.smoothed().to_vec())
        } else {
            let (start, end) = self.x_range;
            Series::function(name, start..=end, samples, |x| self.eval(x))
        };
        series.style(LineStyle::Dashed).width(1.5)
    }
}