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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
//! `Killing2ndChernoff<C, K, F>` — order-2 soft killing via symmetric Strang split.
//!
//! Approximates the Feynman-Kac semigroup `e^{t(L−κ)}` via:
//!
//! ```text
//! F(τ)f = e^{−τκ/2} · C(τ) · e^{−τκ/2}
//! ```
//!
//! where `κ(x) ≥ 0` is a smooth bounded killing-rate field and `C(τ)` is a
//! Chernoff function for the generator `L`. The palindrome achieves **global
//! order 2** when `[L, κ] ≠ 0` (verified in `scripts/verify_killing_order2_preflight.py`,
//! 2026-06-05; ADR-0126; math.md §21.8).
//!
//! ## Contrast with `KillingChernoff` (v2.6, §21.3)
//!
//! This type and `KillingChernoff` solve DIFFERENT problems:
//!
//! - `Killing2ndChernoff` — **soft killing**, `L_κ = L − κ`, order-2.
//! Rate field `κ(x) ≥ 0`, killed generator is `L − κ` on all of `ℝ`.
//! - `KillingChernoff` — **hard absorbing wall**, order-1.
//! Indicator `𝟙_R` (post-multiply); forced `u|_{∂R} = 0` Dirichlet BC.
//!
//! Users needing absorbing Dirichlet boundaries MUST use `KillingChernoff`.
//! `Killing2ndChernoff` does NOT implement the absorbing-wall problem at
//! higher order (see ADR-0126 §Decision for why the hard wall is irreducibly
//! order-1).
//!
//! ## Validity guard
//!
//! `new` verifies `κ(x) ≥ 0` at every grid node. A negative rate corresponds
//! to mass creation (not killing) and violates the Feynman-Kac formula;
//! the constructor returns `Err(DomainViolation)` fail-closed.
//!
//! ## Mathematical references
//!
//! - Butko 2018, §5 — open conjecture that motivated the rate-formulation reading.
//! - Strang 1968, SIAM J. Numer. Anal. 5:3 — palindromic operator splitting.
//! - `scripts/verify_killing_order2_preflight.py` — sympy verification of
//! τ¹, τ² coefficient cancellation for `[L, κ] ≠ 0`.
use core::marker::PhantomData;
use crate::{
chernoff::{ChernoffFunction, Growth},
error::SemiflowError,
float::{half, SemiflowFloat},
grid::Grid1D,
grid_fn::GridFn1D,
scratch::ScratchPool,
};
// ---------------------------------------------------------------------------
// KillingRate<F> — trait
// ---------------------------------------------------------------------------
/// Smooth bounded killing-rate field `κ(x) ≥ 0`.
///
/// Required by `Killing2ndChernoff<C, K, F>`.
///
/// ## Contract
///
/// Implementations MUST return `κ(x) ≥ 0` for all `x`. A negative value
/// corresponds to mass creation (not killing) and the caller SHOULD validate
/// at construction time. `Killing2ndChernoff::new` validates at every grid node
/// and returns `Err(DomainViolation)` if any node has `κ < 0`.
///
/// ## Implementing for constant rates
///
/// The simplest implementation wraps a constant `c ≥ 0`:
///
/// ```rust
/// use semiflow::killing_soft::KillingRate;
///
/// struct ConstRate(f64);
///
/// impl KillingRate<f64> for ConstRate {
/// fn kappa(&self, _x: f64) -> f64 { self.0 }
/// }
/// ```
pub trait KillingRate<F: SemiflowFloat = f64> {
/// Killing rate at position `x`. Must return `≥ 0`.
fn kappa(&self, x: F) -> F;
}
// ---------------------------------------------------------------------------
// ClosureKillingRate<F> — blanket impl for closures
// ---------------------------------------------------------------------------
/// `KillingRate<F>` adapter for `Fn(F) -> F` closures.
///
/// Allows constructing `Killing2ndChernoff` directly from a closure without
/// defining a named struct.
///
/// # Example
///
/// ```rust
/// use semiflow::killing_soft::{ClosureKillingRate, KillingRate};
///
/// let rate = ClosureKillingRate::new(|x: f64| 0.3 * x * x);
/// assert!((rate.kappa(1.0) - 0.3).abs() < 1e-15);
/// ```
#[derive(Clone, Copy)]
pub struct ClosureKillingRate<F, Kfn>
where
F: SemiflowFloat,
Kfn: Fn(F) -> F,
{
kfn: Kfn,
_f: PhantomData<F>,
}
impl<F: SemiflowFloat, Kfn: Fn(F) -> F> ClosureKillingRate<F, Kfn> {
/// Wrap a closure as a `KillingRate<F>`.
pub fn new(kfn: Kfn) -> Self {
Self {
kfn,
_f: PhantomData,
}
}
}
impl<F: SemiflowFloat, Kfn: Fn(F) -> F> KillingRate<F> for ClosureKillingRate<F, Kfn> {
fn kappa(&self, x: F) -> F {
(self.kfn)(x)
}
}
// ---------------------------------------------------------------------------
// Killing2ndChernoff<C, K, F> — wrapper
// ---------------------------------------------------------------------------
/// Order-2 soft-killing Chernoff function (ADR-0126, math.md §21.8).
///
/// `F(τ)f = e^{−τκ/2} · C(τ)f · e^{−τκ/2}` (pointwise scalar factors).
///
/// ## Type parameters
///
/// - `C`: inner `ChernoffFunction<F>` for the generator `L` (e.g.
/// `DiffusionChernoff<F>`). Must have `S = GridFn1D<F>`.
/// - `K`: killing-rate field, implementing `KillingRate<F>`.
/// - `F`: float type (`f64` default).
///
/// ## Construction
///
/// Use `Killing2ndChernoff::new(inner, rate, grid)`. The constructor validates
/// `κ(x_i) ≥ 0` at every node `i = 0..grid.n`.
///
/// ## Growth bound
///
/// `e^{−τκ/2} ≤ 1` pointwise (κ ≥ 0, τ ≥ 0) ⟹ `‖F(τ)‖ ≤ ‖C(τ)‖`. Growth
/// is inherited from the inner Chernoff.
#[derive(Clone)]
pub struct Killing2ndChernoff<C, K, F: SemiflowFloat = f64> {
inner: C,
rate: K,
grid: Grid1D<F>,
_f: PhantomData<F>,
}
impl<C, K, F> Killing2ndChernoff<C, K, F>
where
F: SemiflowFloat,
C: ChernoffFunction<F, S = GridFn1D<F>>,
K: KillingRate<F>,
{
/// Construct a `Killing2ndChernoff` with validated non-negative rate field.
///
/// Validates `κ(x_i) ≥ 0` at every grid node `i = 0..grid.n`. Returns
/// `Err(DomainViolation)` at the first negative value found.
///
/// # Errors
///
/// - `DomainViolation` if `κ(x_i) < 0` for any `i`.
/// - `DomainViolation` if `κ(x_i)` is non-finite for any `i`.
pub fn new(inner: C, rate: K, grid: Grid1D<F>) -> Result<Self, SemiflowError> {
for i in 0..grid.n {
let x = grid.x_at(i);
let k = rate.kappa(x);
if !k.is_finite() {
return Err(SemiflowError::DomainViolation {
what: "Killing2ndChernoff: kappa(x) must be finite",
value: k.to_f64().unwrap_or(f64::NAN),
});
}
if k < F::zero() {
return Err(SemiflowError::DomainViolation {
what:
"Killing2ndChernoff: kappa(x) must be >= 0 (negative rate = mass creation)",
value: k.to_f64().unwrap_or(f64::NAN),
});
}
}
Ok(Self {
inner,
rate,
grid,
_f: PhantomData,
})
}
}
// ---------------------------------------------------------------------------
// ChernoffFunction<F> impl
// ---------------------------------------------------------------------------
impl<C, K, F> ChernoffFunction<F> for Killing2ndChernoff<C, K, F>
where
F: SemiflowFloat,
C: ChernoffFunction<F, S = GridFn1D<F>>,
K: KillingRate<F>,
{
type S = GridFn1D<F>;
/// Symmetric Strang split: `e^{−τκ/2} · C(τ) · e^{−τκ/2}`.
///
/// Three stages:
/// 1. Half-step kill: `tmp[i] = src[i] · e^{−τ·κ(xᵢ)/2}`.
/// 2. Inner Chernoff step: `mid = C(τ) tmp`.
/// 3. Half-step kill: `dst[i] = mid[i] · e^{−τ·κ(xᵢ)/2}`.
fn apply_into(
&self,
tau: F,
src: &Self::S,
dst: &mut Self::S,
scratch: &mut ScratchPool<F>,
) -> Result<(), SemiflowError> {
let half_tau = half::<F>() * tau;
let n = self.grid.n;
// Stage 1: half-step kill → tmp
let mut tmp = src.zeroed_like();
for i in 0..n {
let x = self.grid.x_at(i);
let w = (-half_tau * self.rate.kappa(x)).libm_exp();
tmp.values[i] = src.values[i] * w;
}
// Stage 2: inner Chernoff step → mid
let mut mid = src.zeroed_like();
self.inner.apply_into(tau, &tmp, &mut mid, scratch)?;
// Stage 3: half-step kill → dst
for i in 0..n {
let x = self.grid.x_at(i);
let w = (-half_tau * self.rate.kappa(x)).libm_exp();
dst.values[i] = mid.values[i] * w;
}
Ok(())
}
/// Order-2 (Strang palindrome, ADR-0126 / math.md §21.8).
///
/// The symmetric split cancels the τ¹ and τ² commutator terms in
/// `F(τ) − e^{τ(L−κ)}` when `[L, κ] ≠ 0` (pre-flight sympy, 2026-06-05).
fn order(&self) -> u32 {
2
}
/// Growth bound inherited from inner (soft killing is sub-Markov: `e^{−τκ} ≤ 1`).
fn growth(&self) -> Growth<F> {
self.inner.growth()
}
}
// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::{ClosureKillingRate, KillingRate};
use crate::{
chernoff::ChernoffFunction, diffusion::DiffusionChernoff, error::SemiflowError,
grid::Grid1D, grid_fn::GridFn1D, killing_soft::Killing2ndChernoff as K2,
scratch::ScratchPool,
};
// --- KillingRate contract ---
#[test]
fn closure_killing_rate_basic() {
let r = ClosureKillingRate::new(|x: f64| x.abs());
assert!((r.kappa(2.0) - 2.0).abs() < 1e-15);
assert!((r.kappa(0.0)).abs() < 1e-15);
}
// --- Constructor validation ---
#[test]
fn negative_kappa_is_rejected() {
let grid = Grid1D::new(0.0_f64, 1.0, 8).unwrap();
let diff = DiffusionChernoff::new(|_| 0.5, |_| 0.0, |_| 0.0, 0.5, grid);
// κ(x) = -0.1 everywhere → DomainViolation
let rate = ClosureKillingRate::new(|_: f64| -0.1_f64);
let result = K2::new(diff, rate, grid);
assert!(result.is_err(), "expected Err for κ < 0");
match result {
Err(SemiflowError::DomainViolation { .. }) => {}
Err(other) => panic!("expected DomainViolation, got {other:?}"),
Ok(_) => unreachable!(),
}
}
#[test]
fn zero_kappa_returns_inner() {
// κ = 0 everywhere → F(τ) = C(τ), so Killing2ndChernoff == DiffusionChernoff.
let grid = Grid1D::new(-1.0_f64, 1.0, 16).unwrap();
let diff_ref = DiffusionChernoff::new(|_| 0.5, |_| 0.0, |_| 0.0, 0.5, grid);
let diff = DiffusionChernoff::new(|_| 0.5, |_| 0.0, |_| 0.0, 0.5, grid);
let rate = ClosureKillingRate::new(|_: f64| 0.0_f64);
let k2 = K2::new(diff, rate, grid).unwrap();
let u0 = GridFn1D::from_fn(grid, |x| (-x * x).exp());
let mut dst_k2 = u0.zeroed_like();
let mut dst_ref = u0.zeroed_like();
let mut scratch = ScratchPool::new();
k2.apply_into(0.01, &u0, &mut dst_k2, &mut scratch).unwrap();
diff_ref
.apply_into(0.01, &u0, &mut dst_ref, &mut scratch)
.unwrap();
let max_diff = dst_k2
.values
.iter()
.zip(dst_ref.values.iter())
.map(|(a, b)| (a - b).abs())
.fold(0.0_f64, f64::max);
assert!(
max_diff < 1e-14,
"zero-kappa: K2 and DiffusionChernoff should be bit-level close, diff={max_diff:.3e}"
);
}
#[test]
fn positive_kappa_attenuates() {
// κ > 0 must reduce the sup-norm vs κ = 0 (mass is killed, not created).
let grid = Grid1D::new(-2.0_f64, 2.0, 32).unwrap();
let diff_k2 = DiffusionChernoff::new(|_| 0.5, |_| 0.0, |_| 0.0, 0.5, grid);
let diff_ref = DiffusionChernoff::new(|_| 0.5, |_| 0.0, |_| 0.0, 0.5, grid);
let rate = ClosureKillingRate::new(|_: f64| 1.0_f64);
let k2 = K2::new(diff_k2, rate, grid).unwrap();
let u0 = GridFn1D::from_fn(grid, |x| (-x * x).exp());
let mut dst_killed = u0.zeroed_like();
let mut dst_plain = u0.zeroed_like();
let mut scratch = ScratchPool::new();
k2.apply_into(0.1, &u0, &mut dst_killed, &mut scratch)
.unwrap();
diff_ref
.apply_into(0.1, &u0, &mut dst_plain, &mut scratch)
.unwrap();
let norm_killed: f64 = dst_killed
.values
.iter()
.map(|v| v.abs())
.fold(0.0_f64, f64::max);
let norm_plain: f64 = dst_plain
.values
.iter()
.map(|v| v.abs())
.fold(0.0_f64, f64::max);
assert!(
norm_killed < norm_plain,
"killing must reduce sup-norm: killed={norm_killed:.6}, plain={norm_plain:.6}"
);
}
#[test]
fn order_is_two() {
let grid = Grid1D::new(0.0_f64, 1.0, 8).unwrap();
let diff = DiffusionChernoff::new(|_| 0.5, |_| 0.0, |_| 0.0, 0.5, grid);
let rate = ClosureKillingRate::new(|_: f64| 0.5_f64);
let k2 = K2::new(diff, rate, grid).unwrap();
assert_eq!(k2.order(), 2);
}
}