1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
//! Typed contracts shared by CPU and accelerator finite-difference stencils.
use aequitas::systems::si::{quantities::Length, units::Meter};
use eunomia::{FloatElement, NumericElement, UnitScalar};
use thiserror::Error;
/// Boundary condition applied by a Cartesian finite-difference stencil.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BoundaryCondition {
/// Homogeneous Dirichlet: `u = 0` on boundaries.
Dirichlet,
/// Homogeneous Neumann: `∂u/∂n = 0` on boundaries.
Neumann,
/// Periodic wrapping across domain boundaries.
Periodic,
}
impl From<BoundaryCondition> for u32 {
#[inline]
fn from(value: BoundaryCondition) -> Self {
match value {
BoundaryCondition::Dirichlet => 0,
BoundaryCondition::Neumann => 1,
BoundaryCondition::Periodic => 2,
}
}
}
/// Sign convention for a Laplacian operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LaplacianPolarity {
/// The differential operator `∇²`.
Laplacian,
/// The positive-semidefinite operator `-∇²`.
NegativeLaplacian,
}
/// Typed Laplacian contract failure.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum LaplacianError {
/// An axis is too short for the boundary stencil.
#[error("Laplacian grid axes must contain at least two points: nx={nx}, ny={ny}")]
GridTooSmall {
/// Number of x-axis points.
nx: usize,
/// Number of y-axis points.
ny: usize,
},
/// The flattened grid size does not fit in `usize`.
#[error("Laplacian grid size overflows usize: nx={nx}, ny={ny}")]
GridSizeOverflow {
/// Number of x-axis points.
nx: usize,
/// Number of y-axis points.
ny: usize,
},
/// A physical grid spacing is non-finite or non-positive.
#[error("Laplacian spacing must be finite and positive: dx={dx}, dy={dy}")]
InvalidSpacing {
/// Debug representation of x spacing in meters.
dx: String,
/// Debug representation of y spacing in meters.
dy: String,
},
/// Signed inverse squared spacings are non-finite, zero, or of mixed sign,
/// so they describe neither polarity of a valid grid.
#[error(
"Laplacian signed inverse squared spacings must be finite, non-zero, and share one sign: x={x}, y={y}"
)]
InvalidInverseSpacing {
/// Debug representation of the signed x value in m⁻².
x: String,
/// Debug representation of the signed y value in m⁻².
y: String,
},
/// The input array length does not match the flattened grid.
#[error("Laplacian input length mismatch: expected {expected}, actual {actual}")]
InputLength {
/// Required flattened length.
expected: usize,
/// Supplied input length.
actual: usize,
},
/// The output array length does not match the flattened grid.
#[error("Laplacian output length mismatch: expected {expected}, actual {actual}")]
OutputLength {
/// Required flattened length.
expected: usize,
/// Supplied output length.
actual: usize,
},
}
/// Validated two-dimensional Cartesian Laplacian contract.
///
/// Spacing crosses the boundary as [`Length`] and is reduced once to inverse
/// squared SI spacing in the native precision of `T`. The same contract drives
/// Leto CPU evaluation and Hephaestus accelerator dispatch.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Laplacian2D<T> {
nx: usize,
ny: usize,
len: usize,
inverse_spacing_squared: [T; 2],
boundary: BoundaryCondition,
polarity: LaplacianPolarity,
}
impl<T> Laplacian2D<T>
where
T: FloatElement + UnitScalar,
{
/// Validate a uniform endpoint-inclusive Cartesian grid.
///
/// # Errors
///
/// Returns [`LaplacianError`] when an axis has fewer than two points, the
/// flattened size overflows, or either spacing is non-finite or non-positive.
pub fn new(
nx: usize,
ny: usize,
dx: Length<T>,
dy: Length<T>,
boundary: BoundaryCondition,
) -> Result<Self, LaplacianError> {
let len = Self::validated_len(nx, ny)?;
let dx_m = dx.in_unit::<Meter>();
let dy_m = dy.in_unit::<Meter>();
if !dx_m.is_finite()
|| dx_m <= <T as NumericElement>::ZERO
|| !dy_m.is_finite()
|| dy_m <= <T as NumericElement>::ZERO
{
return Err(LaplacianError::InvalidSpacing {
dx: format!("{dx_m:?} m"),
dy: format!("{dy_m:?} m"),
});
}
Ok(Self {
nx,
ny,
len,
inverse_spacing_squared: [dx_m.recip().powi(2), dy_m.recip().powi(2)],
boundary,
polarity: LaplacianPolarity::Laplacian,
})
}
/// Rebuild the contract from the value [`Self::signed_inverse_spacing_squared`]
/// returns, as carried by an accelerator parameter block.
///
/// The polarity is the shared sign of the two values, so for every contract
/// `c`, rebuilding from `c.signed_inverse_spacing_squared()` with
/// `c.boundary()` yields `c` exactly: no spacing is recomputed through a
/// square root.
///
/// # Errors
///
/// Returns [`LaplacianError::GridTooSmall`] or
/// [`LaplacianError::GridSizeOverflow`] as [`Self::new`] does, and
/// [`LaplacianError::InvalidInverseSpacing`] when a value is non-finite or
/// zero, or the two differ in sign.
pub fn from_signed_inverse_spacing_squared(
nx: usize,
ny: usize,
signed_inverse_spacing_squared: [T; 2],
boundary: BoundaryCondition,
) -> Result<Self, LaplacianError> {
let len = Self::validated_len(nx, ny)?;
let [x, y] = signed_inverse_spacing_squared;
let zero = <T as NumericElement>::ZERO;
let valid = |value: T| value.is_finite() && value != zero;
let polarity = if valid(x) && valid(y) && (x > zero) == (y > zero) {
if x > zero {
LaplacianPolarity::Laplacian
} else {
LaplacianPolarity::NegativeLaplacian
}
} else {
return Err(LaplacianError::InvalidInverseSpacing {
x: format!("{x:?}"),
y: format!("{y:?}"),
});
};
let magnitude = |value: T| if value > zero { value } else { zero - value };
Ok(Self {
nx,
ny,
len,
inverse_spacing_squared: [magnitude(x), magnitude(y)],
boundary,
polarity,
})
}
/// Validate the grid axes and return the flattened length.
fn validated_len(nx: usize, ny: usize) -> Result<usize, LaplacianError> {
if nx < 2 || ny < 2 {
return Err(LaplacianError::GridTooSmall { nx, ny });
}
nx.checked_mul(ny)
.ok_or(LaplacianError::GridSizeOverflow { nx, ny })
}
/// Select the operator sign convention.
#[must_use]
pub const fn with_polarity(mut self, polarity: LaplacianPolarity) -> Self {
self.polarity = polarity;
self
}
/// Number of x-axis points.
#[must_use]
pub const fn nx(&self) -> usize {
self.nx
}
/// Number of y-axis points.
#[must_use]
pub const fn ny(&self) -> usize {
self.ny
}
/// Required flattened array length.
#[must_use]
pub const fn len(&self) -> usize {
self.len
}
/// Whether the flattened grid is empty.
#[must_use]
pub const fn is_empty(&self) -> bool {
self.len == 0
}
/// Boundary condition encoded by this stencil.
#[must_use]
pub const fn boundary(&self) -> BoundaryCondition {
self.boundary
}
/// Operator sign convention.
#[must_use]
pub const fn polarity(&self) -> LaplacianPolarity {
self.polarity
}
/// Signed inverse squared spacing for x and y.
#[must_use]
pub fn signed_inverse_spacing_squared(&self) -> [T; 2] {
match self.polarity {
LaplacianPolarity::Laplacian => self.inverse_spacing_squared,
LaplacianPolarity::NegativeLaplacian => [
<T as NumericElement>::ZERO - self.inverse_spacing_squared[0],
<T as NumericElement>::ZERO - self.inverse_spacing_squared[1],
],
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_non_positive_spacing() {
let error = Laplacian2D::new(
4,
4,
Length::from_unit::<Meter>(0.0f32),
Length::from_unit::<Meter>(1.0f32),
BoundaryCondition::Dirichlet,
)
.expect_err("zero spacing must be rejected");
assert!(matches!(error, LaplacianError::InvalidSpacing { .. }));
}
/// Rebuilding from the signed inverse squared spacings reproduces the
/// contract exactly, for both polarities and a spacing (0.3 m) whose
/// inverse square is inexact in binary.
#[test]
fn signed_inverse_spacing_round_trips_exactly() {
for polarity in [
LaplacianPolarity::Laplacian,
LaplacianPolarity::NegativeLaplacian,
] {
let contract = Laplacian2D::new(
5,
3,
Length::from_unit::<Meter>(0.3f32),
Length::from_unit::<Meter>(0.7f32),
BoundaryCondition::Neumann,
)
.expect("valid grid")
.with_polarity(polarity);
let rebuilt = Laplacian2D::from_signed_inverse_spacing_squared(
5,
3,
contract.signed_inverse_spacing_squared(),
BoundaryCondition::Neumann,
)
.expect("round trip");
assert_eq!(rebuilt, contract);
}
}
#[test]
fn rejects_zero_non_finite_or_mixed_sign_inverse_spacing() {
for signed in [
[0.0f32, 1.0],
[1.0, f32::INFINITY],
[f32::NAN, 1.0],
[1.0, -1.0],
[-4.0, 4.0],
] {
let error = Laplacian2D::from_signed_inverse_spacing_squared(
4,
4,
signed,
BoundaryCondition::Periodic,
)
.expect_err("must be rejected");
assert!(
matches!(error, LaplacianError::InvalidInverseSpacing { .. }),
"{signed:?}: {error}"
);
}
}
#[test]
fn inverse_spacing_constructor_validates_the_grid() {
let error = Laplacian2D::from_signed_inverse_spacing_squared(
1,
4,
[1.0f32, 1.0],
BoundaryCondition::Dirichlet,
)
.expect_err("a one-point axis must be rejected");
assert_eq!(error, LaplacianError::GridTooSmall { nx: 1, ny: 4 });
}
}