lib_jsl_integration/
sampled.rs1use lib_jsl_core::ErrorsJSL;
8
9#[derive(Clone, Copy, Debug)]
11pub enum Spacing<'a> {
12 Uniform(f64),
14 Points(&'a [f64]),
16}
17
18fn steps(y: &[f64], spacing: Spacing) -> Result<Vec<f64>, ErrorsJSL> {
19 match spacing {
20 Spacing::Uniform(dx) => Ok(vec![dx; y.len().saturating_sub(1)]),
21 Spacing::Points(x) => {
22 if x.len() != y.len() {
23 return Err(ErrorsJSL::IncompatibleArraySizes((x.len(), y.len())));
24 }
25 Ok(x.windows(2).map(|w| w[1] - w[0]).collect())
26 }
27 }
28}
29
30pub fn trapezoid(y: &[f64], spacing: Spacing) -> Result<f64, ErrorsJSL> {
32 let h = steps(y, spacing)?;
33 Ok(y.windows(2).zip(&h).map(|(w, hi)| 0.5 * hi * (w[0] + w[1])).sum())
34}
35
36pub fn cumulative_trapezoid(y: &[f64], spacing: Spacing, initial: Option<f64>) -> Result<Vec<f64>, ErrorsJSL> {
40 let h = steps(y, spacing)?;
41 let mut out = Vec::with_capacity(y.len());
42 let mut acc = initial.unwrap_or(0.0);
43 if initial.is_some() {
44 out.push(acc);
45 }
46 for (w, hi) in y.windows(2).zip(&h) {
47 acc += 0.5 * hi * (w[0] + w[1]);
48 out.push(acc);
49 }
50 Ok(out)
51}
52
53pub fn simpson(y: &[f64], spacing: Spacing) -> Result<f64, ErrorsJSL> {
59 let n = y.len();
60 let h = steps(y, spacing)?;
61 if n < 2 {
62 return Ok(0.0);
63 }
64 if n == 2 {
65 return Ok(0.5 * h[0] * (y[0] + y[1]));
66 }
67 let pair = |i: usize| -> f64 {
68 let (h0, h1) = (h[i], h[i + 1]);
69 let (hs, hp, r) = (h0 + h1, h0 * h1, h0 / h1);
70 hs / 6.0 * (y[i] * (2.0 - 1.0 / r) + y[i + 1] * hs * hs / hp + y[i + 2] * (2.0 - r))
71 };
72 if n % 2 == 1 {
73 return Ok((0..n - 2).step_by(2).map(pair).sum());
74 }
75 let mut result: f64 = (0..n - 3).step_by(2).map(pair).sum();
76 let (h0, h1) = (h[n - 3], h[n - 2]);
77 let alpha = (2.0 * h1 * h1 + 3.0 * h0 * h1) / (6.0 * (h1 + h0));
78 let beta = (h1 * h1 + 3.0 * h0 * h1) / (6.0 * h0);
79 let eta = h1.powi(3) / (6.0 * h0 * (h0 + h1));
80 result += alpha * y[n - 1] + beta * y[n - 2] - eta * y[n - 3];
81 Ok(result)
82}
83pub fn cumulative_simpson(y: &[f64], spacing: Spacing, initial: Option<f64>) -> Result<Vec<f64>, ErrorsJSL> {
89 let n = y.len();
90 if n < 3 {
91 return cumulative_trapezoid(y, spacing, initial);
92 }
93 let h = steps(y, spacing)?;
94 let forward = |f1: f64, f2: f64, f3: f64, x21: f64, x32: f64| {
96 let x31 = x21 + x32;
97 let (a, b) = (x21 / x31, x21 / x32);
98 x21 / 6.0 * ((3.0 - a) * f1 + (3.0 + a * b + a) * f2 - a * b * f3)
99 };
100 let h1: Vec<f64> = (0..n - 2).map(|i| forward(y[i], y[i + 1], y[i + 2], h[i], h[i + 1])).collect();
101 let h2: Vec<f64> = (0..n - 2).map(|i| forward(y[i + 2], y[i + 1], y[i], h[i + 1], h[i])).collect();
103 let mut sub = vec![0.0; n - 1];
104 for i in 0..n - 1 {
105 sub[i] = if i == n - 2 {
106 h2[n - 3]
107 } else if i % 2 == 0 {
108 h1[i]
109 } else {
110 h2[i - 1]
111 };
112 }
113 let mut out = Vec::with_capacity(n);
114 let mut acc = initial.unwrap_or(0.0);
115 if initial.is_some() {
116 out.push(acc);
117 }
118 for s in sub {
119 acc += s;
120 out.push(acc);
121 }
122 Ok(out)
123}
124
125pub fn romb(y: &[f64], dx: f64) -> Result<f64, ErrorsJSL> {
130 let intervals = y.len().saturating_sub(1);
131 if intervals == 0 || !intervals.is_power_of_two() {
132 return Err(ErrorsJSL::InvalidInputRange("romb needs 2^k + 1 samples"));
133 }
134 let k = intervals.trailing_zeros() as usize;
135 let mut h = intervals as f64 * dx;
136 let mut prev = vec![(y[0] + y[intervals]) / 2.0 * h];
137 let (mut start, mut step) = (intervals, intervals);
138 for i in 1..=k {
139 start >>= 1;
140 let s: f64 = (start..intervals).step_by(step).map(|j| y[j]).sum();
141 step >>= 1;
142 let mut row = vec![0.5 * (prev[0] + h * s)];
143 for j in 1..=i {
144 let p = row[j - 1];
145 row.push(p + (p - prev[j - 1]) / ((1u64 << (2 * j)) - 1) as f64);
146 }
147 prev = row;
148 h /= 2.0;
149 }
150 Ok(prev[k])
151}
152#[cfg(test)]
155mod tests {
156 use super::*;
157
158 #[test]
159 fn simpson_is_exact_for_cubics_and_romb_for_high_degree() {
160 let x: Vec<f64> = (0..=8).map(|i| i as f64 * 0.25).collect();
161 let y: Vec<f64> = x.iter().map(|v| v * v * v - 2.0 * v).collect();
162 assert!((simpson(&y, Spacing::Uniform(0.25)).unwrap() - (4.0 - 4.0)).abs() < 1e-14);
163 let x: Vec<f64> = (0..=7).map(|i| i as f64 * 0.25).collect();
165 let y: Vec<f64> = x.iter().map(|v| v * v).collect();
166 assert!((simpson(&y, Spacing::Points(&x)).unwrap() - 1.75f64.powi(3) / 3.0).abs() < 1e-13);
167 let y: Vec<f64> = x.iter().map(|v| v * v * v).collect();
168 assert!((simpson(&y, Spacing::Points(&x)).unwrap() - 2.345703125).abs() < 1e-13);
169 let x: Vec<f64> = (0..=16).map(|i| i as f64 / 16.0).collect();
170 let y: Vec<f64> = x.iter().map(|v| v.powi(8)).collect();
171 assert!((romb(&y, 1.0 / 16.0).unwrap() - 1.0 / 9.0).abs() < 1e-12);
172 }
173
174 #[test]
175 fn cumulative_rules_end_at_the_full_integral() {
176 let x: Vec<f64> = (0..11).map(|i| (i as f64 * 0.3).powf(1.2)).collect();
177 let y: Vec<f64> = x.iter().map(|v| v * v).collect();
178 let c = cumulative_simpson(&y, Spacing::Points(&x), Some(0.0)).unwrap();
179 for (ci, xi) in c.iter().zip(&x) {
180 assert!((ci - xi.powi(3) / 3.0).abs() < 1e-12, "{ci} vs {}", xi.powi(3) / 3.0);
181 }
182 let t = cumulative_trapezoid(&y, Spacing::Points(&x), None).unwrap();
183 assert!((t.last().unwrap() - trapezoid(&y, Spacing::Points(&x)).unwrap()).abs() < 1e-14);
184 }
185}