leto_ops/application/diff/three_dimensional/leapfrog/operator.rs
1//! Staggered leapfrog operator type, constructors, and entry points.
2
3use eunomia::{NumericElement, RealField};
4use leto::{ArrayView3, ArrayViewMut3, LetoError, Result};
5
6use super::super::coefficients::{staggered_first_derivative_coefficients, TapCoefficients};
7use super::kernels;
8
9/// The spatial axis a gradient or divergence differentiates along.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum Axis {
12 /// The outermost (slowest-varying) axis of a row-major `Array3`.
13 X,
14 /// The middle axis.
15 Y,
16 /// The innermost (contiguous) axis.
17 Z,
18}
19
20impl Axis {
21 /// Position of this axis in a `[nx, ny, nz]` shape.
22 #[must_use]
23 #[inline]
24 pub fn index(self) -> usize {
25 match self {
26 Self::X => 0,
27 Self::Y => 1,
28 Self::Z => 2,
29 }
30 }
31}
32
33/// Staggered gradient/divergence pair at accuracy order `2N`.
34///
35/// Both operators are grid-shaped in and out: the face `i+½` is stored at index
36/// `i`, so a velocity field and a pressure field share one allocation shape.
37///
38/// # Examples
39///
40/// ```
41/// use leto::Array3;
42/// use leto_ops::{Axis, StaggeredLeapfrog3D};
43///
44/// let op = StaggeredLeapfrog3D::<f64>::new(4, 1.0, 1.0, 1.0).unwrap();
45/// assert_eq!(op.order(), 4);
46/// assert_eq!(op.halo_width(), 2);
47///
48/// // A constant field has zero gradient everywhere, walls included.
49/// let field = Array3::from_elem([6, 6, 6], 2.5);
50/// let mut dst = Array3::zeros([6, 6, 6]);
51/// op.gradient_into(Axis::Z, field.view(), &mut dst.view_mut()).unwrap();
52/// assert!(dst.as_slice().unwrap().iter().all(|&v| v == 0.0));
53/// ```
54#[derive(Debug, Clone, Copy, PartialEq)]
55pub struct StaggeredLeapfrog3D<T> {
56 coefficients: TapCoefficients<T>,
57 spacing: [T; 3],
58 /// `1/Δ` per axis, the factor the kernels apply, reduced once here.
59 inverse_spacing: [T; 3],
60}
61
62impl<T: RealField> StaggeredLeapfrog3D<T> {
63 /// Build the pair for an even accuracy `order` on a grid of the given
64 /// spacings.
65 ///
66 /// # Errors
67 ///
68 /// Returns [`LetoError::InvalidInput`] for an odd or zero order, an order
69 /// beyond the coefficient derivation's verified range
70 /// ([`MAX_HALF_ORDER`](super::super::coefficients::MAX_HALF_ORDER) tap pairs), and
71 /// spacings that are not finite and positive.
72 pub fn new(order: usize, dx: T, dy: T, dz: T) -> Result<Self> {
73 if order == 0 || !order.is_multiple_of(2) {
74 return Err(LetoError::InvalidInput(format!(
75 "StaggeredLeapfrog3D needs an even, non-zero order, got {order}"
76 )));
77 }
78 let spacing = [dx, dy, dz];
79 require_finite_positive(spacing, "dx, dy, dz")?;
80 Ok(Self {
81 coefficients: staggered_first_derivative_coefficients(order / 2)?,
82 spacing,
83 inverse_spacing: spacing.map(T::recip),
84 })
85 }
86
87 /// Build the pair from given taps and reciprocal spacings, as an
88 /// accelerator parameter block carries them.
89 ///
90 /// The kernels apply `inverse_spacing` exactly as given, so a reference
91 /// evaluating a device's parameters reproduces the device's arithmetic
92 /// rather than a round trip through `1/(1/Δ)`; for every operator `op`
93 /// from [`Self::new`], `from_parts(*op.coefficients(),` its reciprocal
94 /// spacings`)` sweeps bitwise identically. [`Self::spacing`] then reports
95 /// the reciprocals of `inverse_spacing`.
96 ///
97 /// # Errors
98 ///
99 /// Returns [`LetoError::InvalidInput`] unless every reciprocal spacing is
100 /// finite and positive.
101 pub fn from_parts(coefficients: TapCoefficients<T>, inverse_spacing: [T; 3]) -> Result<Self> {
102 require_finite_positive(inverse_spacing, "1/dx, 1/dy, 1/dz")?;
103 Ok(Self {
104 coefficients,
105 spacing: inverse_spacing.map(T::recip),
106 inverse_spacing,
107 })
108 }
109
110 /// Accuracy order `2N`.
111 #[must_use]
112 #[inline]
113 pub fn order(&self) -> usize {
114 self.coefficients.order()
115 }
116
117 /// Half-width of the stencil in cells — the halo a domain decomposition
118 /// must exchange for this order.
119 #[must_use]
120 #[inline]
121 pub fn halo_width(&self) -> usize {
122 self.coefficients.half_order()
123 }
124
125 /// The derived tap coefficients.
126 #[must_use]
127 #[inline]
128 pub fn coefficients(&self) -> &TapCoefficients<T> {
129 &self.coefficients
130 }
131
132 /// Per-axis grid spacing `(dx, dy, dz)`.
133 #[must_use]
134 #[inline]
135 pub fn spacing(&self) -> (T, T, T) {
136 (self.spacing[0], self.spacing[1], self.spacing[2])
137 }
138
139 /// Courant limit as a multiple of `Δx/c`, for `dimensions` spatial axes.
140 ///
141 /// # Derivation
142 ///
143 /// The staggered symbol along one axis is `S(θ) = 2 Σ_n c_n sin((n−½)θ)`,
144 /// whose magnitude is bounded by `S_max = 2 Σ_n |c_n|`. Leapfrog stability
145 /// needs `(c·Δt/2)·|k_eff| ≤ 1` with `|k_eff| = S_max·√D/Δx` in `D`
146 /// dimensions, so
147 ///
148 /// ```text
149 /// Δt ≤ 2Δx / (c · S_max · √D) = Δx / (c · √D · Σ_n |c_n|)
150 /// ```
151 ///
152 /// At order 2 the sum is 1 and this recovers the familiar `1/√3` in 3-D.
153 ///
154 /// # Why this differs from the collocated limit
155 ///
156 /// The collocated central-difference table (`1/√3`, `1/√15`, `1/√27`) is a
157 /// different scheme's limit. The two agree at order 2 and diverge
158 /// immediately after: at order 4 the staggered limit is 0.495 against the
159 /// collocated 0.258. Using the collocated number for a staggered run costs
160 /// roughly half the achievable step for no accuracy gain.
161 #[must_use]
162 pub fn cfl_limit(&self, dimensions: usize) -> T {
163 let dimensions = T::from_count(dimensions);
164 (dimensions.sqrt() * self.coefficients.absolute_sum()).recip()
165 }
166
167 /// Gradient along `axis`: cell-centred `field` to face-centred `dst`, with
168 /// face `i+½` stored at index `i`. Both are grid-shaped.
169 ///
170 /// # Errors
171 ///
172 /// Returns [`LetoError::InvalidInput`] when `dst` does not have the same
173 /// shape as `field`.
174 pub fn gradient_into(
175 &self,
176 axis: Axis,
177 field: ArrayView3<'_, T>,
178 dst: &mut ArrayViewMut3<'_, T>,
179 ) -> Result<()> {
180 let shape = field.shape();
181 assert_grid_shaped(dst.shape(), shape, "gradient")?;
182 kernels::gradient(self, axis, field, dst, shape);
183 Ok(())
184 }
185
186 /// Divergence along `axis`: face-centred `field` back to cell-centred
187 /// `dst`. This is `−Gᵀ` applied directly.
188 ///
189 /// # Errors
190 ///
191 /// Returns [`LetoError::InvalidInput`] when `dst` does not have the same
192 /// shape as `field`.
193 pub fn divergence_into(
194 &self,
195 axis: Axis,
196 field: ArrayView3<'_, T>,
197 dst: &mut ArrayViewMut3<'_, T>,
198 ) -> Result<()> {
199 let shape = field.shape();
200 assert_grid_shaped(dst.shape(), shape, "divergence")?;
201 kernels::divergence(self, axis, field, dst, shape);
202 Ok(())
203 }
204
205 /// Axis index, extent along it, and the reciprocal spacing.
206 pub(super) fn axis_geometry(&self, axis: Axis, shape: [usize; 3]) -> (usize, isize, T) {
207 let index = axis.index();
208 let extent = isize::try_from(shape[index]).unwrap_or(isize::MAX);
209 (index, extent, self.inverse_spacing[index])
210 }
211}
212
213/// Reject a spacing triple unless every value is finite and positive; a
214/// `NaN` passes a bare `<= 0` test and would poison every swept value.
215fn require_finite_positive<T: RealField>(values: [T; 3], names: &str) -> Result<()> {
216 let zero = <T as NumericElement>::ZERO;
217 if values
218 .iter()
219 .all(|&value| value.is_finite() && value > zero)
220 {
221 Ok(())
222 } else {
223 Err(LetoError::InvalidInput(format!(
224 "StaggeredLeapfrog3D: {names} must all be finite and positive"
225 )))
226 }
227}
228
229/// Both operators keep the grid shape; a mismatch is a caller error, reported
230/// rather than left to a debug-only assertion that would corrupt in release.
231#[inline]
232pub(super) fn assert_grid_shaped(
233 actual: [usize; 3],
234 expected: [usize; 3],
235 what: &str,
236) -> Result<()> {
237 if actual != expected {
238 return Err(LetoError::InvalidInput(format!(
239 "StaggeredLeapfrog3D {what}: dst shape {actual:?} does not match field shape {expected:?}"
240 )));
241 }
242 Ok(())
243}