Skip to main content

nereids_physics/
lattice_doppler.rs

1//! Doppler broadening by nuclei bound in a harmonic crystal.
2//!
3//! Lamb's incoherent harmonic model: a neutron of energy `E` absorbed by a
4//! nucleus of mass ratio `A` leaves an energy `ε` to the lattice, drawn from
5//!
6//! ```text
7//! P(ε) = (1/2π) ∫ e^{iεt} Φ(t) dt,   Φ(t) = exp(R·[G(t) − G(0)]),
8//! G(t) = ∫ ρ(ω)/ω · [coth(ω/2kT)·cos ωt − i·sin ωt] dω,   R = E/A,
9//! ```
10//!
11//! `ρ` the phonon density of states, so the cross section is
12//!
13//! ```text
14//! σ_L(E) = e^{−2W}·σ(E + R) + ∫ P_c(ε)·σ(E + R − ε) dε,   2W = R·G(0),
15//! ```
16//!
17//! the first term the zero-phonon line and `P_c = P − e^{−2W}·δ`.  `P` has
18//! mean `R` and variance `2R·kT_eff = Δ²/2`, `kT_eff = ½∫ρ·ω·coth(ω/2kT) dω`
19//! and `Δ` the Doppler width of a free gas at `T_eff` (Fröhner Eq. 241).
20//!
21//! SAMMY's crystal-lattice model takes `R = E/(A + 1)`, which gives
22//! `A/(A + 1)` of this variance.
23//!
24//! `σ` is sampled once on a uniform grid of step `h`, the integral is the
25//! trapezoid rule on that grid, and `P_c` comes on the grid's nodes from a
26//! fast Fourier transform of `Φ − e^{−2W}`, sampled at `t = j·dt` up to
27//! `100/ω_max`.  Over the second half of that span the samples roll off by a
28//! raised cosine, which damps the ripple of the spectrum's cutoff.  Structure
29//! in `σ` or in the spectrum finer than about `ω_max/100` is not resolved,
30//! and no check detects it.  A resonance of total width `Γ`
31//! makes the trapezoid rule's error `≈ e^{−πΓ/h}`, so `h ≤ πΓ/30` for every
32//! resonance the kernel reaches, `h ≤ π·ω_max/100`, and `h` is a tenth of
33//! every File-3 knot interval within reach.
34//!
35//! # References
36//! - W. E. Lamb, Phys. Rev. 55, 190 (1939).
37//! - A. Courcelle and J. Rowlands, arXiv:0709.2767 (2007), Eqs. (8)–(10).
38//! - F. H. Fröhner, JEFF Report 18, OECD/NEA (2000), Eqs. (241)–(243).
39
40use std::f64::consts::PI;
41
42use nereids_core::constants::BOLTZMANN_EV_PER_K;
43use nereids_endf::resonance::ResonanceData;
44use num_complex::Complex64;
45use rayon::prelude::*;
46
47use crate::continuous_doppler::{Channel, TierOneBroadening};
48use crate::doppler::{DopplerError, DopplerParams, validate_doppler_grid};
49use crate::reich_moore::CrossSectionPlan;
50
51/// Standard deviations of the kernel, and phonon energies beyond them, its
52/// window spans on each side of its mean.
53const KERNEL_SIGMAS: f64 = 8.0;
54const KERNEL_PHONONS: f64 = 10.0;
55
56/// Most points of the cross section's grid, or of one transform.
57const MAX_POINTS: usize = 1 << 22;
58
59/// Most terms of the phonon sums and the transforms together.
60const MAX_WORK: f64 = 1e10;
61
62/// Most departure from 1 of a kernel's weights: the zero-phonon line's and
63/// `h` times its sampled values over its window.
64const MASS_TOLERANCE: f64 = 1e-7;
65
66/// Grid steps per File-3 knot interval within the kernel's reach.
67const STEPS_PER_KNOT: f64 = 10.0;
68
69/// Gauss–Legendre 8-point nodes and weights on `[−1, 1]`, non-negative half.
70const GAUSS_LEGENDRE_8: [(f64, f64); 4] = [
71    (0.183_434_642_495_649_8, 0.362_683_783_378_362),
72    (0.525_532_409_916_329, 0.313_706_645_877_887_3),
73    (0.796_666_477_413_626_7, 0.222_381_034_453_374_5),
74    (0.960_289_856_497_536_3, 0.101_228_536_290_376_26),
75];
76
77/// Errors from lattice broadening.
78#[derive(Debug)]
79pub enum LatticeError {
80    /// The phonon spectrum is not a valid density of states.
81    InvalidSpectrum(String),
82    /// The temperature is not finite and positive.
83    InvalidTemperature(f64),
84    /// The energy grid is invalid.
85    Grid(DopplerError),
86    /// The kernel reaches energies at or below zero.
87    BelowZero(f64),
88    /// File 3 jumps at this energy, within the kernel's reach.
89    Jump(f64),
90    /// The kernel at this energy is not resolved: its weights sum to `mass`.
91    Unresolved {
92        /// The target energy, eV.
93        energy_ev: f64,
94        /// The kernel's weights' sum.
95        mass: f64,
96    },
97    /// The cross section's grid or a transform would exceed 2²² points.
98    TooManyPoints(usize),
99    /// The phonon sums and transforms would take more than 10¹⁰ terms.
100    TooMuchWork(f64),
101}
102
103impl std::fmt::Display for LatticeError {
104    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105        match self {
106            Self::InvalidSpectrum(message) => write!(f, "invalid phonon spectrum: {message}"),
107            Self::InvalidTemperature(t) => {
108                write!(f, "the temperature must be finite and positive, got {t} K")
109            }
110            Self::Grid(error) => write!(f, "{error}"),
111            Self::BelowZero(e) => {
112                write!(
113                    f,
114                    "the lattice kernel reaches {e} eV, at or below zero energy"
115                )
116            }
117            Self::TooManyPoints(n) => {
118                write!(
119                    f,
120                    "lattice broadening needs at least {n} points, more than {MAX_POINTS}"
121                )
122            }
123            Self::Jump(e) => write!(
124                f,
125                "File 3 jumps at {e} eV, within the lattice kernel's reach"
126            ),
127            Self::Unresolved { energy_ev, mass } => write!(
128                f,
129                "the lattice kernel at {energy_ev} eV is not resolved: its weights sum to {mass}"
130            ),
131            Self::TooMuchWork(work) => {
132                write!(f, "lattice broadening needs {work:e} terms, more than 1e10")
133            }
134        }
135    }
136}
137
138impl std::error::Error for LatticeError {}
139
140impl From<DopplerError> for LatticeError {
141    fn from(error: DopplerError) -> Self {
142        Self::Grid(error)
143    }
144}
145
146/// A crystal's phonon density of states `ρ(ω)`, `ω` in eV: the values
147/// `ρ_i` at `ω = i·step`, `ρ_0 = 0`, quadratic in `ω` up to the first
148/// point, linear between the others and zero beyond the last, scaled to
149/// unit area.
150#[derive(Debug, Clone, PartialEq)]
151pub struct PhononSpectrum {
152    step_ev: f64,
153    density: Vec<f64>,
154}
155
156impl PhononSpectrum {
157    /// The spectrum with values `density` every `step_ev` from 0.
158    ///
159    /// # Errors
160    /// [`LatticeError::InvalidSpectrum`] unless `step_ev` is finite and
161    /// positive, `density` holds at least two finite values, 0 or more, the
162    /// first 0 and another positive, and the scaled values are finite.
163    pub fn new(step_ev: f64, mut density: Vec<f64>) -> Result<Self, LatticeError> {
164        if !(step_ev.is_finite() && step_ev > 0.0)
165            || density.len() < 2
166            || density[0] != 0.0
167            || !density.iter().all(|r| r.is_finite() && *r >= 0.0)
168            || !density.iter().any(|r| *r > 0.0)
169        {
170            return Err(LatticeError::InvalidSpectrum(format!(
171                "needs a finite positive step and at least two finite values, 0 or more, the \
172                 first 0 and another positive; got step {step_ev} and {} values",
173                density.len()
174            )));
175        }
176        let peak = density.iter().fold(0.0_f64, |m, &r| m.max(r));
177        for r in &mut density {
178            *r /= peak;
179        }
180        let area = step_ev * density[1] / 3.0
181            + step_ev
182                * density[1..]
183                    .windows(2)
184                    .map(|w| 0.5 * (w[0] + w[1]))
185                    .sum::<f64>();
186        for r in &mut density {
187            *r /= area;
188        }
189        if !(area.is_finite() && area > 0.0 && density.iter().all(|r| r.is_finite())) {
190            return Err(LatticeError::InvalidSpectrum(format!(
191                "its area {area} eV after scaling to a peak of 1 leaves values that are not finite"
192            )));
193        }
194        Ok(Self { step_ev, density })
195    }
196
197    /// Debye's spectrum `3ω²/ω_D³` up to `ω_D = k·θ_D`, on `points` values.
198    ///
199    /// # Errors
200    /// [`LatticeError::InvalidSpectrum`] unless `theta_k` is finite and
201    /// positive and `points` is at least 2.
202    pub fn debye(theta_k: f64, points: usize) -> Result<Self, LatticeError> {
203        let cutoff = BOLTZMANN_EV_PER_K * theta_k;
204        if !(cutoff.is_finite() && cutoff > 0.0) || points < 2 {
205            return Err(LatticeError::InvalidSpectrum(format!(
206                "Debye needs a finite positive temperature and at least 2 points, got {theta_k} K \
207                 and {points}"
208            )));
209        }
210        let step = cutoff / (points - 1) as f64;
211        Self::new(
212            step,
213            (0..points)
214                .map(|i| (i as f64 * step / cutoff).powi(2))
215                .collect(),
216        )
217    }
218
219    /// The highest phonon energy, eV.
220    #[must_use]
221    pub fn max_ev(&self) -> f64 {
222        self.step_ev * (self.density.len() - 1) as f64
223    }
224
225    /// The spacing of the spectrum's values, eV.
226    #[must_use]
227    pub fn step_ev(&self) -> f64 {
228        self.step_ev
229    }
230
231    /// The spectrum's values at `ω = i·step`, scaled to unit area, 1/eV.
232    #[must_use]
233    pub fn density(&self) -> &[f64] {
234        &self.density
235    }
236
237    /// `T_eff` at `temperature_k`, `k·T_eff = ½∫ρ·ω·coth(ω/2kT) dω`: the kernel's
238    /// variance is `Δ²/2`, `Δ` the Doppler width of a free gas at `T_eff`.
239    #[must_use]
240    pub fn effective_temperature_k(&self, temperature_k: f64) -> f64 {
241        Phonons::new(&self.nodes(0.0), temperature_k, 0.0, 0).kt_eff / BOLTZMANN_EV_PER_K
242    }
243
244    /// How far in energy, eV, the kernel of a nucleus of mass ratio `awr` at
245    /// `energy_ev` and `temperature_k` reaches on either side of `E`: the
246    /// span [`broaden_in_lattice`] reads the cross section over.
247    #[must_use]
248    pub fn reach_ev(&self, energy_ev: f64, temperature_k: f64, awr: f64) -> f64 {
249        let kt_eff = BOLTZMANN_EV_PER_K * self.effective_temperature_k(temperature_k);
250        reach(energy_ev / awr, kt_eff, self.max_ev())
251    }
252
253    /// The number of quadrature nodes [`Self::nodes`] gives for `t_max`.
254    fn node_count(&self, t_max: f64) -> f64 {
255        (self.density.len() - 1) as f64 * (self.step_ev * t_max).ceil().max(1.0) * 16.0
256    }
257
258    /// Quadrature nodes `(ω, w·ρ(ω))` over the spectrum, each panel spanning
259    /// at most one radian of `ω·t` up to `t_max`.
260    fn nodes(&self, t_max: f64) -> Vec<(f64, f64)> {
261        let mut nodes = Vec::new();
262        let h = self.step_ev;
263        let pieces = ((h * t_max).ceil() as usize).max(1);
264        for i in 0..self.density.len() - 1 {
265            let (r0, r1) = (self.density[i], self.density[i + 1]);
266            let at = |omega: f64| {
267                if i == 0 {
268                    r1 * (omega / h).powi(2)
269                } else {
270                    r0 + (r1 - r0) * (omega / h - i as f64)
271                }
272            };
273            let width = h / pieces as f64;
274            for p in 0..pieces {
275                let centre = i as f64 * h + (p as f64 + 0.5) * width;
276                for &(x, w) in &GAUSS_LEGENDRE_8 {
277                    for omega in [centre - 0.5 * width * x, centre + 0.5 * width * x] {
278                        nodes.push((omega, 0.5 * width * w * at(omega)));
279                    }
280                }
281            }
282        }
283        nodes
284    }
285}
286
287/// The kernel's reach on either side of its mean, eV, at recoil `r`.
288fn reach(r: f64, kt_eff: f64, omega_max: f64) -> f64 {
289    KERNEL_SIGMAS * (2.0 * r * kt_eff).sqrt() + KERNEL_PHONONS * omega_max
290}
291
292/// The spectrum's sums at one temperature: `G(t_j)` and `∂G/∂T` at
293/// `t_j = j·dt`, `j = 0..=half`, and `kT_eff`.
294struct Phonons {
295    g: Vec<Complex64>,
296    g_slope: Vec<f64>,
297    kt_eff: f64,
298}
299
300impl Phonons {
301    fn new(nodes: &[(f64, f64)], temperature_k: f64, dt: f64, half: usize) -> Self {
302        let kt = BOLTZMANN_EV_PER_K * temperature_k;
303        let terms: Vec<(f64, f64, f64, f64)> = nodes
304            .iter()
305            .map(|&(omega, weight)| {
306                let x = omega / (2.0 * kt);
307                let coth = 1.0 / x.tanh();
308                let slope = x / (temperature_k * x.sinh().powi(2));
309                (omega, weight / omega, coth, slope)
310            })
311            .collect();
312        let kt_eff = 0.5
313            * terms
314                .iter()
315                .map(|&(omega, a, coth, _)| a * omega * omega * coth)
316                .sum::<f64>();
317        let (g, g_slope) = (0..=half)
318            .into_par_iter()
319            .map(|j| {
320                let t = j as f64 * dt;
321                let (mut g, mut slope) = (Complex64::new(0.0, 0.0), 0.0);
322                for &(omega, a, coth, dcoth) in &terms {
323                    let (sin, cos) = (omega * t).sin_cos();
324                    g += a * Complex64::new(coth * cos, -sin);
325                    slope += a * dcoth * cos;
326                }
327                (g, slope)
328            })
329            .unzip();
330        Self { g, g_slope, kt_eff }
331    }
332}
333
334/// `values` replaced by its discrete Fourier transform,
335/// `values[m] ← Σ_j values[j]·e^{−2πi·mj/N}`, `N` a power of 2.
336fn dft(values: &mut [Complex64]) {
337    let n = values.len();
338    let mut j = 0;
339    for i in 1..n {
340        let mut bit = n >> 1;
341        while j & bit != 0 {
342            j ^= bit;
343            bit >>= 1;
344        }
345        j |= bit;
346        if i < j {
347            values.swap(i, j);
348        }
349    }
350    let mut len = 2;
351    while len <= n {
352        let step = Complex64::from_polar(1.0, -2.0 * PI / len as f64);
353        for start in (0..n).step_by(len) {
354            let mut w = Complex64::new(1.0, 0.0);
355            for k in 0..len / 2 {
356                let (a, b) = (values[start + k], values[start + k + len / 2] * w);
357                values[start + k] = a + b;
358                values[start + k + len / 2] = a - b;
359                w *= step;
360            }
361        }
362        len <<= 1;
363    }
364}
365
366/// Value and temperature derivative of `channel` at every target energy,
367/// broadened by nuclei bound in a harmonic crystal with phonon spectrum
368/// `spectrum` at `temperature_k`.  `negative_values` counts the negative
369/// values; nothing is roundoff-limited.
370///
371/// # Errors
372/// [`LatticeError::InvalidTemperature`]; [`LatticeError::Grid`] for an empty
373/// or invalid grid or a mass ratio that is not finite and positive;
374/// [`LatticeError::BelowZero`]; [`LatticeError::Jump`] for a File-3 jump
375/// within a kernel's reach; [`LatticeError::TooManyPoints`] and
376/// [`LatticeError::TooMuchWork`]; [`LatticeError::Unresolved`] for a kernel
377/// whose weights do not sum to 1 within 1e-7.
378pub fn broaden_in_lattice(
379    energies: &[f64],
380    data: &ResonanceData,
381    temperature_k: f64,
382    spectrum: &PhononSpectrum,
383    channel: Channel,
384) -> Result<TierOneBroadening, LatticeError> {
385    if !(temperature_k.is_finite() && temperature_k > 0.0) {
386        return Err(LatticeError::InvalidTemperature(temperature_k));
387    }
388    DopplerParams::new(temperature_k, data.awr).map_err(DopplerError::from)?;
389    validate_doppler_grid(energies)?;
390    if energies.is_empty() {
391        return Err(DopplerError::EmptyGrid.into());
392    }
393    let recoil = |energy: f64| energy / data.awr;
394    let omega_max = spectrum.max_ev();
395    let kt_eff = BOLTZMANN_EV_PER_K * spectrum.effective_temperature_k(temperature_k);
396    let reach_at = |energy: f64| reach(recoil(energy), kt_eff, omega_max);
397    let lowest = energies
398        .iter()
399        .map(|&e| e - reach_at(e))
400        .fold(f64::INFINITY, f64::min);
401    let highest = energies
402        .iter()
403        .map(|&e| e + reach_at(e))
404        .fold(f64::NEG_INFINITY, f64::max);
405    if lowest <= 0.0 {
406        return Err(LatticeError::BelowZero(lowest));
407    }
408    let narrowest = data
409        .ranges
410        .iter()
411        .filter(|range| range.is_evaluable())
412        .flat_map(|range| range.levels())
413        .filter(|&(energy, _)| energy >= lowest - 1.0 && energy <= highest + 1.0)
414        .map(|(_, width)| width)
415        .filter(|&width| width > 0.0)
416        .fold(f64::INFINITY, f64::min);
417    let mut h = (PI * narrowest / 30.0).min(PI * omega_max / 100.0);
418    for table in data.smooth.tables() {
419        let start = table.points.partition_point(|&(e, _)| e < lowest);
420        let stop = table.points.partition_point(|&(e, _)| e <= highest);
421        let around = &table.points[start.saturating_sub(1)..(stop + 1).min(table.points.len())];
422        for pair in around.windows(2) {
423            let spacing = pair[1].0 - pair[0].0;
424            if spacing == 0.0 {
425                return Err(LatticeError::Jump(pair[0].0));
426            }
427            h = h.min(spacing / STEPS_PER_KNOT);
428        }
429    }
430    let widest = energies.iter().map(|&e| reach_at(e)).fold(0.0, f64::max);
431    let span = ((2.0 * widest / h).ceil() as usize).saturating_add(1);
432    let origin = lowest - 2.0 * h;
433    if origin <= 0.0 {
434        return Err(LatticeError::BelowZero(origin));
435    }
436    let grid_points = (((highest - origin) / h).ceil() as usize).saturating_add(3);
437    for needed in [span, grid_points] {
438        if needed > MAX_POINTS {
439            return Err(LatticeError::TooManyPoints(needed));
440        }
441    }
442    // MAX_POINTS is a power of 2, so the transform fits when its span does.
443    let transform = span.next_power_of_two();
444    let half = transform / 2;
445    let dt = 2.0 * PI / (transform as f64 * h);
446    let t_max = (100.0 / omega_max).min(PI / h);
447    let samples = half.min((t_max / dt).ceil() as usize);
448    let t_end = (samples.max(2) - 1) as f64 * dt;
449    let work = spectrum.node_count(t_max) * (samples + 1) as f64
450        + energies.len() as f64 * transform as f64 * (transform as f64).log2();
451    if work > MAX_WORK {
452        return Err(LatticeError::TooMuchWork(work));
453    }
454    let phonons = Phonons::new(&spectrum.nodes(t_max), temperature_k, dt, samples);
455    let plan = CrossSectionPlan::new(data);
456    let sigma = |energy: f64| channel.pick(&plan.evaluate_one(energy));
457    let grid: Vec<f64> = (0..grid_points)
458        .into_par_iter()
459        .map(|m| sigma(origin + m as f64 * h))
460        .collect();
461    let g0 = phonons.g[0].re;
462    let g0_slope = phonons.g_slope[0];
463    let results: Vec<Result<(f64, f64), LatticeError>> = energies
464        .par_iter()
465        .map(|&energy| {
466            let r = recoil(energy);
467            let zero = (-r * g0).exp();
468            let zero_slope = -zero * r * g0_slope;
469            let shift = energy + r - origin;
470            let mut buffer = vec![Complex64::new(0.0, 0.0); transform];
471            for j in 0..samples {
472                let t = j as f64 * dt;
473                let roll = (2.0 * t / t_end - 1.0).clamp(0.0, 1.0);
474                let taper = 0.5 * (1.0 + (PI * roll).cos());
475                let phi = (r * (phonons.g[j] - g0)).exp();
476                let value = taper * (phi - zero);
477                let slope = taper * (phi * r * (phonons.g_slope[j] - g0_slope) - zero_slope);
478                let rotate = Complex64::from_polar(dt / (2.0 * PI), shift * t);
479                buffer[j] = rotate * (value + Complex64::i() * slope);
480                if j > 0 {
481                    let back = rotate.conj() * (value.conj() + Complex64::i() * slope.conj());
482                    buffer[transform - j] = back;
483                }
484            }
485            dft(&mut buffer);
486            let own = reach_at(energy);
487            let first = ((energy - own - origin) / h).floor().max(0.0) as usize;
488            let last = (((energy + own - origin) / h).ceil() as usize).min(grid_points - 1);
489            let (mut mass, mut value, mut slope) = (zero, 0.0, 0.0);
490            for (m, &s) in grid.iter().enumerate().take(last + 1).skip(first) {
491                let kernel = buffer[m % transform];
492                mass += h * kernel.re;
493                value += kernel.re * s;
494                slope += kernel.im * s;
495            }
496            if (mass - 1.0).abs() > MASS_TOLERANCE {
497                return Err(LatticeError::Unresolved {
498                    energy_ev: energy,
499                    mass,
500                });
501            }
502            let at_recoil = sigma(energy + r);
503            Ok((
504                h * value + zero * at_recoil,
505                h * slope + zero_slope * at_recoil,
506            ))
507        })
508        .collect();
509    let (values, derivatives): (Vec<f64>, Vec<f64>) = results
510        .into_iter()
511        .collect::<Result<Vec<_>, _>>()?
512        .into_iter()
513        .unzip();
514    if let Some((k, &value)) = values
515        .iter()
516        .chain(&derivatives)
517        .enumerate()
518        .find(|(_, v)| !v.is_finite())
519    {
520        return Err(DopplerError::NonFiniteIntegral {
521            energy_ev: energies[k % energies.len()],
522            value,
523            derivative: k >= energies.len(),
524        }
525        .into());
526    }
527    let negative_values = values.iter().filter(|&&v| v < 0.0).count();
528    Ok(TierOneBroadening {
529        values,
530        derivatives,
531        negative_values,
532        roundoff_limited: 0,
533    })
534}
535
536#[cfg(test)]
537mod tests {
538    use super::*;
539
540    #[test]
541    fn the_transform_is_the_discrete_fourier_transform() {
542        let n = 32;
543        let values: Vec<Complex64> = (0..n)
544            .map(|j| Complex64::new((0.7 * j as f64).sin(), (1.3 * j as f64).cos() - 0.2))
545            .collect();
546        let mut fast = values.clone();
547        dft(&mut fast);
548        for (m, fast) in fast.iter().enumerate() {
549            let direct: Complex64 = values
550                .iter()
551                .enumerate()
552                .map(|(j, v)| v * Complex64::from_polar(1.0, -2.0 * PI * (m * j) as f64 / n as f64))
553                .sum();
554            assert!((fast - direct).norm() <= 1e-12, "{m}: {fast} {direct}");
555        }
556    }
557}