Skip to main content

spectrafit_models/
lib.rs

1//! spectrafit-models — analytical model kernels with exact Jacobians.
2#![warn(missing_docs)]
3
4pub(crate) mod erf_ext;
5pub(crate) mod faddeeva;
6pub(crate) mod math_backend;
7
8/// Asymmetric IR band (Gaussian × logistic sigmoid).
9pub mod asym_ir;
10/// Breit-Wigner-Fano resonance.
11pub mod breit_wigner;
12/// Cauchy refractive-index dispersion (`a + b/x² + c/x⁴`).
13pub mod cauchy_dispersion;
14/// Doniach–Šunjić asymmetric core-level lineshape (XPS).
15pub mod doniach;
16/// Exponentially-modified Gaussian (asymmetric tailing peak).
17pub mod emg;
18/// Exponential over a line (NIST StRD Chwirut1, Chwirut2):
19/// `exp(−rate·x) / (den_const + den_lin·x)`.
20pub mod exp_over_linear;
21/// Exponential decay and double-exponential models.
22pub mod exponential;
23/// Fano resonance lineshape model.
24pub mod fano;
25/// Gaussian peak model with exact Jacobian.
26pub mod gaussian;
27/// Axis-aligned 2-D Gaussian peak model (n_dims == 2).
28pub mod gaussian2d;
29/// Axis-aligned N-D Gaussian peak model (parametric dimensionality).
30pub mod gaussian_nd;
31/// Generalised logistic / Richards curve (NIST StRD Rat42, Rat43):
32/// `amplitude / (1 + exp(shift − rate·x))^(1/shape)`.
33pub mod generalised_logistic;
34/// Driven damped harmonic-oscillator IR absorption.
35pub mod harmonic_ir;
36/// Kohlrausch–Williams–Watts stretched exponential (`A·exp(−(x/τ)^β)`).
37pub mod kww;
38/// Log-normal peak (`A·exp(−(ln(x/c))²/(2σ²))` for x > 0).
39pub mod log_normal;
40/// Lorentzian (Cauchy) peak model with exact Jacobian.
41pub mod lorentzian;
42/// Kowalik–Osborne rational function (NIST StRD MGH09):
43/// `amplitude · (x² + num_lin·x) / (x² + den_lin·x + den_const)`.
44pub mod mgh09_rational;
45/// Moffat peak (`A / (((x−c)/σ)²+1)^β`).
46pub mod moffat;
47/// Pearson VII peak (`A / [1 + ((x−c)/σ)²·(2^{1/m}−1)]^m`).
48pub mod pearson7;
49/// Constant and linear polynomial baseline models.
50pub mod polynomial;
51/// Power-law with offset: `amplitude · (offset + x)^(−1/shape)` (Bennett5 model).
52pub mod power_law_offset;
53/// Power-law saturation: `amplitude · (1 − (1 + rate·x/2)^(−2))` (Misra1b model).
54pub mod power_saturation;
55/// Pseudo-Voigt (Gaussian/Lorentzian mixture) model.
56pub mod pseudo_voigt;
57/// Rational cubic over cubic, denominator constant pinned at 1 (NIST StRD
58/// Kirby2, Hahn1, Thurber): `(a0+a1x+a2x²+a3x³) / (1+b1x+b2x²+b3x³)`.
59pub mod rational_cubic;
60/// Saturating exponential: `amplitude · (1 − exp(−rate · x))` (BoxBOD model).
61pub mod saturating_exponential;
62/// Skewed Gaussian (error-function-modulated asymmetry).
63pub mod skewed_gaussian;
64/// Split (asymmetric) Gaussian — different width each side (a.k.a. bi-Gaussian).
65pub mod split_gaussian;
66/// Split Pearson VII (split width + exponent each side).
67pub mod split_pearson7;
68/// Step-function models: arctan, tanh, and erfc variants.
69pub mod step;
70/// Student's-t peak (`A / (1+((x−c)/σ)²/ν)^((ν+1)/2)`).
71pub mod students_t;
72/// Tauc optical band-gap edge (`A·((x−e_gap)·H(x−e_gap))^p`).
73pub mod tauc;
74/// Pseudo-Voigt linear-mixture model (the `voigt`/`pseudo_voigt` key).
75pub mod voigt;
76/// True Voigt profile via the Faddeeva function (Gaussian ⊗ Lorentzian).
77pub mod voigt_true;
78
79/// Core model trait implemented by every built-in kernel.
80///
81/// Convention: `x` is a coordinate slice.
82/// - 1-D models expect `x.len() == 1` (i.e. `x[0]` is the scalar coordinate).
83/// - n-D models declare `n_dims() > 1`.
84pub trait Model: Send + Sync {
85    /// Evaluate the model at coordinate `x` with the given `params`.
86    ///
87    /// # Preconditions
88    ///
89    /// Implementations index `params` and `x` by raw position and assume the
90    /// caller has already validated arity (this keeps the per-point evaluation
91    /// branch-free on the hot path). The caller MUST guarantee:
92    /// - `params.len() == self.param_names().len()`
93    /// - `x.len() >= self.n_dims()`
94    ///
95    /// # Panics
96    ///
97    /// Panics (index-out-of-bounds) if `params.len() < self.param_names().len()`
98    /// or `x.len() < self.n_dims()`. Because the pyo3 binding crate calls these
99    /// kernels on the hot path, a panic here would unwind across the FFI
100    /// boundary — validate param/coordinate arity at graph-compile time so the
101    /// kernel is only ever invoked well-formed.
102    fn eval(&self, x: &[f64], params: &[f64]) -> f64;
103
104    /// Jacobian — one derivative per parameter, in the same order as
105    /// `param_names()`.
106    ///
107    /// The default implementation uses forward-difference finite differences
108    /// with step `h = 1e-7 * |p[i]|.max(1e-7)` (relative + absolute floor).
109    /// Override with an analytical formula when possible for best performance.
110    ///
111    /// # Preconditions / Panics
112    ///
113    /// Same arity contract as [`eval`](Model::eval): the caller MUST ensure
114    /// `params.len() == self.param_names().len()` and `x.len() >= self.n_dims()`.
115    /// A short slice panics with an index-out-of-bounds rather than returning an
116    /// error; the same FFI-unwind hazard applies, so validate arity upstream.
117    fn jacobian(&self, x: &[f64], params: &[f64]) -> Vec<f64> {
118        let f0 = self.eval(x, params);
119        let mut p = params.to_vec();
120        (0..params.len())
121            .map(|i| {
122                let h = 1e-7_f64 * params[i].abs().max(1e-7);
123                p[i] = params[i] + h;
124                let df = (self.eval(x, &p) - f0) / h;
125                p[i] = params[i];
126                df
127            })
128            .collect()
129    }
130
131    /// Fill a pre-allocated slice with Jacobian values (one entry per parameter).
132    ///
133    /// This is the hot-path companion to [`jacobian`].  The caller provides a
134    /// scratch buffer (`out`) of length ≥ `param_names().len()`; the method
135    /// writes derivatives into `out[0..n_params]` without any heap allocation.
136    ///
137    /// The default falls back to [`jacobian`] and copies the result.  Models
138    /// with analytical Jacobians **should override** this to compute values
139    /// directly into `out`, sharing intermediate calculations across parameters.
140    #[inline]
141    fn jacobian_into(&self, x: &[f64], params: &[f64], out: &mut [f64]) {
142        let jac = self.jacobian(x, params);
143        out[..jac.len()].copy_from_slice(&jac);
144    }
145
146    /// Batch evaluation of a 1-D model: fill `out[i] = eval([xs[i]], params)`.
147    ///
148    /// **Only called when `n_dims() == 1`.**
149    ///
150    /// Default: per-point loop calling `eval()`.  Override to hoist
151    /// loop-invariant constants (e.g. precompute `1/(2σ²)` once) and let LLVM
152    /// eliminate redundant arithmetic across the slice.
153    #[inline]
154    fn eval_slice_into(&self, xs: &[f64], params: &[f64], out: &mut [f64]) {
155        debug_assert_eq!(xs.len(), out.len());
156        for (xi, slot) in xs.iter().zip(out.iter_mut()) {
157            *slot = self.eval(std::slice::from_ref(xi), params);
158        }
159    }
160
161    /// Batch Jacobian for a 1-D model: fill `out` in row-major layout
162    /// `[i * params.len() + j] = d(model)/d(params[j])` at `xs[i]`.
163    ///
164    /// **Only called when `n_dims() == 1`.**
165    ///
166    /// Default: per-point loop calling `jacobian_into()`.  Override to hoist
167    /// invariants (avoids recomputing `σ²` and the `exp()` argument for every
168    /// point call).
169    #[inline]
170    fn jac_slice_into(&self, xs: &[f64], params: &[f64], out: &mut [f64]) {
171        debug_assert_eq!(xs.len() * params.len(), out.len());
172        let np = params.len();
173        for (i, xi) in xs.iter().enumerate() {
174            self.jacobian_into(
175                std::slice::from_ref(xi),
176                params,
177                &mut out[i * np..(i + 1) * np],
178            );
179        }
180    }
181
182    /// Ordered parameter names, matching the layout expected by `eval` and `jacobian`.
183    ///
184    /// Returns an owned `Vec` of `Cow<'static, str>` so that runtime-generated
185    /// models (e.g. `GaussianND{d}` with dynamic `center_0..center_{d-1}`) can
186    /// produce their parameter names without requiring compile-time-static slices.
187    /// For all built-in kernels with static names, every element is
188    /// `Cow::Borrowed(&'static str)` — zero extra heap allocation.
189    fn param_names(&self) -> Vec<std::borrow::Cow<'static, str>>;
190
191    /// Number of coordinate dimensions consumed from `x`.  Defaults to 1.
192    fn n_dims(&self) -> usize {
193        1
194    }
195}
196
197/// Canonical list of every model-type string [`model_from_str`] can construct.
198///
199/// **Derived from the single source of truth** — the
200/// `model_manifest!`-generated `spectrafit_types::ModelTypeStr::ALL`, mapped
201/// through `as_str()`. There is no second hand-maintained list to drift: adding
202/// a model is one manifest row in `spectrafit-types`, and it auto-enrolls here.
203///
204/// The invariant `all_model_types_round_trip_through_model_from_str` (in the
205/// self-consistency test) pins that every entry here is accepted by
206/// [`model_from_str`] and that every `model_from_str` arm appears here — which,
207/// now that this list IS the manifest, proves every `ModelTypeStr` variant's
208/// wire string is constructible. Adding a model is therefore one manifest row
209/// plus one [`model_from_str`] arm — never a third edit to a parallel list here.
210/// Order follows `ModelTypeStr::ALL` declaration order (consumers iterate it as
211/// a set, not by position).
212pub fn all_model_types() -> &'static [&'static str] {
213    use std::sync::LazyLock;
214    static ALL: LazyLock<Vec<&'static str>> = LazyLock::new(|| {
215        spectrafit_types::ModelTypeStr::ALL
216            .iter()
217            .map(|m| m.as_str())
218            .collect()
219    });
220    ALL.as_slice()
221}
222
223/// Dimension-aware model construction.
224///
225/// Identical to [`model_from_str`] for every fixed-dimensionality kernel, but
226/// for the parametric `"gaussian_nd"` it builds a [`gaussian_nd::GaussianND`] of
227/// the dimensionality `n_dims` (the node's explicit field, passed by the
228/// compiler). Returns `None` for an unknown type, OR for `"gaussian_nd"` with
229/// `n_dims == None` (the caller must surface a clear "dimension required" error).
230pub fn model_from_str_with_dims(model_type: &str, n_dims: Option<usize>) -> Option<Box<dyn Model>> {
231    match model_type {
232        "gaussian_nd" => {
233            n_dims.map(|d| Box::new(crate::gaussian_nd::GaussianND::new(d)) as Box<dyn Model>)
234        }
235        other => model_from_str(other),
236    }
237}
238
239/// Dispatch a model type string to a boxed `Model` implementation.
240///
241/// Returns `None` for unknown type strings.
242pub fn model_from_str(model_type: &str) -> Option<Box<dyn Model>> {
243    match model_type {
244        "gaussian" => Some(Box::new(crate::gaussian::Gaussian)),
245        "gaussian2d" => Some(Box::new(crate::gaussian2d::Gaussian2D)),
246        // Default 1-D instance for the string-registry roundtrip; the compiler
247        // builds the real D-dimensional instance via `model_from_str_with_dims`
248        // from the node's explicit `n_dims`.
249        "gaussian_nd" => Some(Box::new(crate::gaussian_nd::GaussianND::new(1))),
250        "lorentzian" => Some(Box::new(crate::lorentzian::Lorentzian)),
251        "voigt" => Some(Box::new(crate::voigt::Voigt)),
252        "constant" => Some(Box::new(crate::polynomial::Constant)),
253        "linear" => Some(Box::new(crate::polynomial::Linear)),
254        "quadratic" => Some(Box::new(crate::polynomial::Quadratic)),
255        "arctan_step" => Some(Box::new(crate::step::ArctanStep)),
256        "tanh_step" => Some(Box::new(crate::step::TanhStep)),
257        "erfc_step" => Some(Box::new(crate::step::ErfcStep)),
258        "pseudo_voigt" => Some(Box::new(crate::pseudo_voigt::PseudoVoigt)),
259        "fano" => Some(Box::new(crate::fano::Fano)),
260        "double_exponential" => Some(Box::new(crate::exponential::DoubleExponential)),
261        "true_voigt" => Some(Box::new(crate::voigt_true::TrueVoigt)),
262        "skewed_gaussian" => Some(Box::new(crate::skewed_gaussian::SkewedGaussian)),
263        "exp_gaussian" => Some(Box::new(crate::emg::ExpGaussian)),
264        "doniach_sunjic" => Some(Box::new(crate::doniach::DoniachSunjic)),
265        "log_normal" => Some(Box::new(crate::log_normal::LogNormal)),
266        "pearson7" => Some(Box::new(crate::pearson7::Pearson7)),
267        "split_gaussian" => Some(Box::new(crate::split_gaussian::SplitGaussian)),
268        "moffat" => Some(Box::new(crate::moffat::Moffat)),
269        "students_t" => Some(Box::new(crate::students_t::StudentsT)),
270        "split_pearson7" => Some(Box::new(crate::split_pearson7::SplitPearson7)),
271        "breit_wigner" => Some(Box::new(crate::breit_wigner::BreitWigner)),
272        "asym_ir" => Some(Box::new(crate::asym_ir::AsymIr)),
273        "harmonic_ir" => Some(Box::new(crate::harmonic_ir::HarmonicIr)),
274        "tauc" => Some(Box::new(crate::tauc::Tauc)),
275        "cauchy_dispersion" => Some(Box::new(crate::cauchy_dispersion::CauchyDispersion)),
276        "kww" => Some(Box::new(crate::kww::Kww)),
277        "saturating_exponential" => Some(Box::new(
278            crate::saturating_exponential::SaturatingExponential,
279        )),
280        "power_saturation" => Some(Box::new(crate::power_saturation::PowerSaturation)),
281        "power_law_offset" => Some(Box::new(crate::power_law_offset::PowerLawOffset)),
282        "mgh09_rational" => Some(Box::new(crate::mgh09_rational::Mgh09Rational)),
283        "rational_cubic" => Some(Box::new(crate::rational_cubic::RationalCubic)),
284        "generalised_logistic" => Some(Box::new(crate::generalised_logistic::GeneralisedLogistic)),
285        "exp_over_linear" => Some(Box::new(crate::exp_over_linear::ExpOverLinear)),
286        _ => None,
287    }
288}