Skip to main content

spectrafit_models/
voigt_true.rs

1use crate::faddeeva;
2use crate::Model;
3
4/// True Voigt profile (Gaussian ⊗ Lorentzian) via the Faddeeva function.
5///
6/// `A · Re[w(z)] / Re[w(z₀)]`, with `z = ((x−c) + iγ)/(σ√2)` and
7/// `z₀ = iγ/(σ√2)`, so `amplitude` is the peak height (`A` at `x=c`).
8///
9/// Parameters (in order): `[amplitude, center, sigma, gamma]`
10///
11/// - `sigma` is the Gaussian standard deviation, `gamma` the Lorentzian HWHM.
12///   `γ→0` ⇒ Gaussian; `σ→0` ⇒ Lorentzian. Distinct from the `voigt`/`pseudo_voigt`
13///   key, which is the linear pseudo-Voigt approximation.
14pub struct TrueVoigt;
15
16impl Model for TrueVoigt {
17    fn eval(&self, x: &[f64], params: &[f64]) -> f64 {
18        let (a, c, sigma, gamma) = (params[0], params[1], params[2], params[3]);
19        let inv = 1.0 / (sigma * std::f64::consts::SQRT_2);
20        let zr = (x[0] - c) * inv;
21        let zi = gamma.abs() * inv;
22        let peak = faddeeva::w(0.0, zi).0; // Re[w(z₀)] at the center
23        a * faddeeva::w(zr, zi).0 / peak
24    }
25
26    /// Analytical Jacobian of the true Voigt profile.
27    ///
28    /// Uses the Faddeeva derivative `w'(z) = −2z·w(z) + 2i/√π` (from
29    /// `faddeeva::w_with_derivative`); by the Cauchy–Riemann equations
30    ///
31    ///   `∂Re[w]/∂z_r = Re[w'(z)]`,  `∂Re[w]/∂z_i = −Im[w'(z)]`.
32    ///
33    /// For the profile `f = A·w_r / peak0` (with `peak0 = Re[w(0, z_i)]`):
34    ///
35    ///   ∂f/∂A = w_r / peak0
36    ///   ∂f/∂c = A / peak0 · dwr_dzr · (−inv)      [∂z_r/∂c = −inv]
37    ///   ∂f/∂σ and ∂f/∂γ use the quotient rule because `peak0` also changes.
38    ///
39    /// `w` and `w'` are evaluated at full double precision (see the `faddeeva`
40    /// module), so the Jacobian carries no approximation floor.
41    fn jacobian(&self, x: &[f64], params: &[f64]) -> Vec<f64> {
42        let (a, c, sigma, gamma) = (params[0], params[1], params[2], params[3]);
43        let inv = 1.0 / (sigma * std::f64::consts::SQRT_2);
44
45        let zr = (x[0] - c) * inv;
46        let zi = gamma.abs() * inv;
47
48        // Faddeeva value and derivative at the profile point and at the peak centre.
49        let ((wr, _), (dwr, dwi)) = faddeeva::w_with_derivative(zr, zi);
50        let ((w0r, _), (_, dw0i)) = faddeeva::w_with_derivative(0.0, zi);
51
52        // ∂Re[w]/∂z_r and ∂Re[w]/∂z_i at (z_r, z_i)
53        let dwr_dzr = dwr;
54        let dwr_dzi = -dwi;
55
56        // ∂Re[w0]/∂z_i at (0, z_i)
57        let dw0r_dzi = -dw0i;
58
59        let peak0 = w0r;
60
61        // ∂f/∂A
62        let da = wr / peak0;
63
64        // ∂f/∂c : ∂z_r/∂c = −inv, ∂z_i/∂c = 0
65        let dc = a / peak0 * dwr_dzr * (-inv);
66
67        // ∂f/∂σ : ∂z_r/∂σ = −z_r/σ, ∂z_i/∂σ = −z_i/σ
68        let dwr_dsigma = dwr_dzr * (-zr / sigma) + dwr_dzi * (-zi / sigma);
69        let dpeak0_dsigma = dw0r_dzi * (-zi / sigma);
70        let ds = a * (dwr_dsigma * peak0 - wr * dpeak0_dsigma) / (peak0 * peak0);
71
72        // ∂f/∂γ : ∂z_r/∂γ = 0, ∂z_i/∂γ = sign(γ)·inv
73        let sign_gamma = if gamma >= 0.0 { 1.0 } else { -1.0 };
74        let dzi_dgamma = sign_gamma * inv;
75        let dwr_dgamma = dwr_dzi * dzi_dgamma;
76        let dpeak0_dgamma = dw0r_dzi * dzi_dgamma;
77        let dg = a * (dwr_dgamma * peak0 - wr * dpeak0_dgamma) / (peak0 * peak0);
78
79        vec![da, dc, ds, dg]
80    }
81
82    #[inline]
83    fn jacobian_into(&self, x: &[f64], params: &[f64], out: &mut [f64]) {
84        let jac = self.jacobian(x, params);
85        out[..4].copy_from_slice(&jac);
86    }
87
88    fn param_names(&self) -> Vec<std::borrow::Cow<'static, str>> {
89        vec![
90            "amplitude".into(),
91            "center".into(),
92            "sigma".into(),
93            "gamma".into(),
94        ]
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use approx::assert_relative_eq;
102
103    #[test]
104    fn peak_height_is_amplitude() {
105        let m = TrueVoigt;
106        assert_relative_eq!(m.eval(&[1.5], &[4.0, 1.5, 1.0, 0.7]), 4.0, epsilon = 1e-9);
107    }
108
109    #[test]
110    fn gamma_to_zero_is_gaussian() {
111        // With no Lorentzian width the Voigt is a Gaussian:
112        // Re[w((x-c)/(σ√2), 0)] = exp(-(x-c)²/(2σ²)) and Re[w(0)] = 1.
113        let m = TrueVoigt;
114        let (a, c, sigma) = (3.0, 0.4, 1.3);
115        for i in -30..=30 {
116            let x = c + f64::from(i) * 0.15;
117            let got = m.eval(&[x], &[a, c, sigma, 0.0]);
118            let gauss = a * (-0.5 * ((x - c) / sigma) * ((x - c) / sigma)).exp();
119            assert_relative_eq!(got, gauss, epsilon = 0.0, max_relative = 1e-14);
120        }
121    }
122
123    #[test]
124    fn sigma_to_zero_is_lorentzian() {
125        // For σ ≪ γ the Voigt tends to the Lorentzian γ²/((x-c)² + γ²), with a
126        // relative correction of order (σ/γ)²; σ/γ = 1e-4 leaves ~1e-8.
127        let m = TrueVoigt;
128        let (a, c, gamma) = (2.0, -0.3, 0.8);
129        let sigma = 1e-4 * gamma;
130        for i in -20..=20 {
131            let x = c + f64::from(i) * 0.25;
132            let got = m.eval(&[x], &[a, c, sigma, gamma]);
133            let lorentz = a * gamma * gamma / ((x - c) * (x - c) + gamma * gamma);
134            assert_relative_eq!(got, lorentz, epsilon = 0.0, max_relative = 1e-7);
135        }
136    }
137
138    #[test]
139    fn symmetric_about_center() {
140        let m = TrueVoigt;
141        let p = [2.0, 0.5, 1.1, 0.6];
142        assert_relative_eq!(
143            m.eval(&[0.5 + 1.3], &p),
144            m.eval(&[0.5 - 1.3], &p),
145            epsilon = 1e-9
146        );
147    }
148
149    #[test]
150    fn jacobian_matches_central_difference_across_regimes() {
151        // Central difference is O(h^2); with h = 1e-6·max(|p|, 1) its truncation
152        // and rounding errors stay well below the 1e-7 bound used for the exact
153        // closed-form kernels (cauchy_dispersion, doniach, skewed_gaussian).
154        // The Faddeeva value and derivative are full double precision, so the
155        // sweep covers the wings out to |x-c| = 8σ.
156        let m = TrueVoigt;
157        let param_sets = [
158            [4.0, 0.5, 1.0, 0.7],    // nominal
159            [1e-3, 0.0, 0.05, 0.05], // small amplitude, width and Lorentzian HWHM
160            [5.0, -2.0, 3.0, -1.2],  // offset centre, wide, negative gamma
161            [1.5, 0.3, 0.2, 4.0],    // Lorentzian-dominated: z₀ deep on the imaginary axis
162        ];
163        for p in param_sets {
164            let (center, sigma) = (p[1], p[2]);
165            for &mult in &[
166                -8.0_f64, -4.0, -2.0, -1.0, -0.1, 0.0, 0.1, 1.0, 2.0, 4.0, 8.0,
167            ] {
168                let x = center + mult * sigma;
169                let j = m.jacobian(&[x], &p);
170                for i in 0..p.len() {
171                    let h = 1e-6 * p[i].abs().max(1.0);
172                    let (mut a, mut b) = (p, p);
173                    a[i] += h;
174                    b[i] -= h;
175                    let fd = (m.eval(&[x], &a) - m.eval(&[x], &b)) / (2.0 * h);
176                    // Absolute floor scaled to the profile height for entries
177                    // that vanish by symmetry (e.g. ∂f/∂c at x = c).
178                    assert_relative_eq!(j[i], fd, epsilon = 1e-7 * p[0].abs(), max_relative = 1e-7);
179                }
180            }
181        }
182    }
183}