1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//! 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)
}
}