Skip to main content

nereids_pipeline/
beam.rs

1//! The beam before the sample: neutrons per µs of flight time.
2
3/// `ln φ(u)`, the logarithm of the beam per µs at flight time `u`, as a
4/// uniform cubic B-spline in `x = ln u` over
5/// [`knot_span_us`](Self::knot_span_us).  Faster than that span, `ln φ`
6/// continues from the spline's value and slope at the first knot with the
7/// spline's mean curvature over the span, so a beam whose curvature changes
8/// across the span is continued with its mean; slower, the last interval's
9/// cubic continues.  The curve is the beam only over the flight times a fit
10/// integrates.
11#[derive(Debug, Clone, PartialEq)]
12pub struct BeamSpline {
13    x_low: f64,
14    x_high: f64,
15    coefficients: Vec<f64>,
16    floor: f64,
17}
18
19impl BeamSpline {
20    pub(crate) fn constant(u_low: f64, u_high: f64, per_us: f64) -> Self {
21        Self {
22            x_low: u_low.ln(),
23            x_high: u_high.ln(),
24            coefficients: vec![per_us.ln(); 4],
25            floor: f64::NEG_INFINITY,
26        }
27    }
28
29    /// The spline whose fitted coefficients stay at or above `floor`.
30    pub(crate) fn above(self, floor: f64) -> Self {
31        Self { floor, ..self }
32    }
33
34    /// The lowest value a fit lets a coefficient take.
35    pub(crate) fn floor(&self) -> f64 {
36        self.floor
37    }
38
39    pub(crate) fn with_coefficients(&self, coefficients: &[f64]) -> Self {
40        Self {
41            coefficients: coefficients.to_vec(),
42            ..self.clone()
43        }
44    }
45
46    pub(crate) fn refined(&self) -> Self {
47        let c = &self.coefficients;
48        let coefficients = (0..2 * c.len() - 3)
49            .map(|p| {
50                let i = p / 2;
51                if p % 2 == 0 {
52                    0.5 * (c[i] + c[i + 1])
53                } else {
54                    (c[i] + 6.0 * c[i + 1] + c[i + 2]) / 8.0
55                }
56            })
57            .collect();
58        Self {
59            coefficients,
60            ..self.clone()
61        }
62    }
63
64    /// Number of spline intervals; there are three more coefficients.
65    #[must_use]
66    pub fn intervals(&self) -> usize {
67        self.coefficients.len() - 3
68    }
69
70    /// The spline's coefficients.
71    #[must_use]
72    pub fn coefficients(&self) -> &[f64] {
73        &self.coefficients
74    }
75
76    /// The flight times, in µs, the knots span.
77    #[must_use]
78    pub fn knot_span_us(&self) -> (f64, f64) {
79        (self.x_low.exp(), self.x_high.exp())
80    }
81
82    /// `(index, weight)` pairs with `ln φ(u) = Σ weight · coefficients[index]`,
83    /// for `u_us > 0`; an index may appear more than once.
84    #[must_use]
85    pub fn basis(&self, u_us: f64) -> [(usize, f64); 5] {
86        let n = self.intervals();
87        let h = (self.x_high - self.x_low) / n as f64;
88        let s = (u_us.ln() - self.x_low) / h;
89        if s < 0.0 {
90            let mean_curvature = s * s / (4.0 * n as f64);
91            return [
92                (0, 1.0 / 6.0 - s / 2.0 + mean_curvature),
93                (1, 2.0 / 3.0),
94                (2, 1.0 / 6.0 + s / 2.0 - mean_curvature),
95                (n, -mean_curvature),
96                (n + 2, mean_curvature),
97            ];
98        }
99        let first = (s.floor() as usize).min(n - 1);
100        let t = s - first as f64;
101        [
102            (first, (1.0 - t).powi(3) / 6.0),
103            (first + 1, (3.0 * t.powi(3) - 6.0 * t * t + 4.0) / 6.0),
104            (
105                first + 2,
106                (-3.0 * t.powi(3) + 3.0 * t * t + 3.0 * t + 1.0) / 6.0,
107            ),
108            (first + 3, t.powi(3) / 6.0),
109            (first, 0.0),
110        ]
111    }
112
113    /// `(index, weight)` pairs with `d ln φ/du = Σ weight · coefficients[index]`
114    /// at `u_us > 0`, in 1/µs; the derivative of [`Self::basis`].
115    #[must_use]
116    pub fn basis_slope(&self, u_us: f64) -> [(usize, f64); 5] {
117        let n = self.intervals();
118        let h = (self.x_high - self.x_low) / n as f64;
119        let ds_du = 1.0 / (h * u_us);
120        let s = (u_us.ln() - self.x_low) / h;
121        if s < 0.0 {
122            let curvature_slope = s / (2.0 * n as f64);
123            return [
124                (0, (-0.5 + curvature_slope) * ds_du),
125                (1, 0.0),
126                (2, (0.5 - curvature_slope) * ds_du),
127                (n, -curvature_slope * ds_du),
128                (n + 2, curvature_slope * ds_du),
129            ];
130        }
131        let first = (s.floor() as usize).min(n - 1);
132        let t = s - first as f64;
133        [
134            (first, -(1.0 - t).powi(2) / 2.0 * ds_du),
135            (first + 1, (3.0 * t * t - 4.0 * t) / 2.0 * ds_du),
136            (first + 2, (-3.0 * t * t + 2.0 * t + 1.0) / 2.0 * ds_du),
137            (first + 3, t * t / 2.0 * ds_du),
138            (first, 0.0),
139        ]
140    }
141
142    /// The beam per µs at flight time `u_us > 0`.
143    #[must_use]
144    pub fn per_us(&self, u_us: f64) -> f64 {
145        self.basis(u_us)
146            .iter()
147            .map(|&(i, w)| w * self.coefficients[i])
148            .sum::<f64>()
149            .exp()
150    }
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156
157    fn wavy() -> BeamSpline {
158        let spline = BeamSpline::constant(280.0, 470.0, 1.0).refined().refined();
159        let c: Vec<f64> = (0..spline.coefficients().len())
160            .map(|i| (i as f64 * 0.7).sin())
161            .collect();
162        spline.with_coefficients(&c)
163    }
164
165    fn ln_beam(spline: &BeamSpline, u: f64) -> f64 {
166        spline.per_us(u).ln()
167    }
168
169    #[test]
170    fn the_basis_slope_is_the_derivative_of_ln_beam() {
171        let spline = wavy();
172        for u in [250.0, 279.0, 300.0, 333.3, 400.0, 469.0, 500.0] {
173            let h = 1e-4;
174            let central = (ln_beam(&spline, u + h) - ln_beam(&spline, u - h)) / (2.0 * h);
175            let slope: f64 = spline
176                .basis_slope(u)
177                .iter()
178                .map(|&(i, w)| w * spline.coefficients()[i])
179                .sum();
180            assert!(
181                (slope - central).abs() <= 1e-8 * central.abs().max(1e-3),
182                "{u}: {slope} vs {central}"
183            );
184        }
185    }
186
187    #[test]
188    fn the_coefficients_of_a_cubic_in_ln_u_reproduce_it() {
189        let (u_low, u_high) = (280.0, 470.0);
190        let [a, b, c, d] = [3.0, -0.7, 1.9, -2.3];
191        let coefficients = [-1.0, 0.0, 1.0, 2.0]
192            .map(|k: f64| a + b * k + c * (k * k - 1.0 / 3.0) + d * (k.powi(3) - k));
193        let beam = BeamSpline::constant(u_low, u_high, 1.0).with_coefficients(&coefficients);
194        for step in 0..=40 {
195            let u = u_low * (u_high / u_low).powf(f64::from(step) / 40.0);
196            let t = (u / u_low).ln() / (u_high / u_low).ln();
197            let expected = a + b * t + c * t * t + d * t.powi(3);
198            assert!((ln_beam(&beam, u) - expected).abs() < 1e-12, "{u}");
199        }
200    }
201
202    #[test]
203    fn refining_keeps_the_curve_inside_and_below_the_knots() {
204        let spline = wavy();
205        let refined = spline.refined();
206        assert_eq!(refined.intervals(), 2 * spline.intervals());
207        for k in 0..400 {
208            let u = 150.0 * (600.0_f64 / 150.0).powf(f64::from(k) / 399.0);
209            let (a, b) = (ln_beam(&spline, u), ln_beam(&refined, u));
210            assert!((a - b).abs() < 1e-12, "at {u} µs: {a} became {b}");
211        }
212    }
213
214    fn slope_at_first_node(f: &dyn Fn(f64) -> f64, nodes: [f64; 4]) -> f64 {
215        let mut d = nodes.map(f);
216        for k in 1..4 {
217            for i in (k..4).rev() {
218                d[i] = (d[i] - d[i - 1]) / (nodes[i] - nodes[i - k]);
219            }
220        }
221        d[1] + (nodes[0] - nodes[1]) * (d[2] + d[3] * (nodes[0] - nodes[2]))
222    }
223
224    #[test]
225    fn below_the_knots_the_curve_continues_with_the_mean_curvature() {
226        let (x_low, x_high) = (280.0_f64.ln(), 470.0_f64.ln());
227        let mut spline = BeamSpline::constant(280.0, 470.0, 1.0);
228        for _ in 0..3 {
229            let c: Vec<f64> = (0..spline.coefficients().len())
230                .map(|i| (i as f64 * 0.7).sin())
231                .collect();
232            let wavy = spline.with_coefficients(&c);
233            let f = |x: f64| ln_beam(&wavy, x.exp());
234            let h = (x_high - x_low) / wavy.intervals() as f64;
235            let within = |end: f64, toward: f64| {
236                [0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0].map(|k| end + toward * k * h)
237            };
238            let slope_low = slope_at_first_node(&f, within(x_low, 1.0));
239            let slope_high = slope_at_first_node(&f, within(x_high, -1.0));
240            let curvature = (slope_high - slope_low) / (x_high - x_low);
241            for dx in [-0.05, -0.2, -0.4] {
242                let expected = f(x_low) + slope_low * dx + curvature * dx * dx / 2.0;
243                assert!(
244                    (f(x_low + dx) - expected).abs() < 1e-9 * (1.0 + expected.abs()),
245                    "{} intervals, {dx}: {} vs {expected}",
246                    wavy.intervals(),
247                    f(x_low + dx)
248                );
249            }
250            spline = spline.refined();
251        }
252    }
253}