Skip to main content

gam_math/
nested_dual.rs

1//! Nested second-order forward-AD dual for FD-free high-order cross-checks (#932).
2//!
3//! [`Dual2<S>`] is a single-direction second-order jet (`value`, first and second
4//! derivative in ONE direction) over a scalar field `S`. Because the field is
5//! generic, it composes with itself: `Dual2<Dual2<f64>>` carries every mixed
6//! partial `∂^i_a ∂^j_b` for `i, j ∈ {0, 1, 2}`, i.e. the full `2 + 2 = 4`th-order
7//! bidirectional derivative in two INDEPENDENT directions `a`, `b`.
8//!
9//! Why this exists: the flexible survival marginal-slope Jet4 tower (the
10//! moving-boundary implicit-intercept path, gam#932) is the last derivative
11//! surface whose fourth-order channel is verified only by a finite-difference
12//! stencil — the hand reference is provably incomplete there, and a 4th-order
13//! FD probes a 6th derivative, so the truncation floor sits far above machine
14//! precision (the same pathology as gam#979). A nested dual evaluates the SAME
15//! single-source program by a DIFFERENT composition ordering (two nested
16//! second-order sweeps instead of one fourth-order sweep), so its
17//! `∂²_a ∂²_b` channel is a truncation-free, hand-oracle-free cross-check of the
18//! Jet4 bidirectional block.
19//!
20//! The construction is standard forward-over-forward automatic differentiation;
21//! its correctness is pinned channel-for-channel against the engine
22//! [`crate::jet_tower::Tower4`] on smooth programs (see the module tests).
23
24/// Minimal scalar field a [`Dual2`] can be built over. Implemented by `f64` (the
25/// base case) and by [`Dual2`] itself (the nesting case). Every operation mirrors
26/// the [`crate::jet_tower::Tower4`] / [`crate::jet_scalar::JetScalar`] Faà di
27/// Bruno convention exactly, so a program written against `JetField` evaluates
28/// identically on the engine tower and on a nested dual.
29///
30/// This is the SHARED scalar-field algebra base of the #932 tower: the
31/// const-`K` packed [`crate::jet_scalar::JetScalar`] and the runtime-`p`
32/// Vec-backed flex jets (`survival::marginal_slope::timepoint_exact::FlexJet`)
33/// both EXTEND it, so the field ops and the single Faà di Bruno composition are
34/// declared exactly ONCE here. It is deliberately NOT `Copy` (the Vec-backed
35/// flex jets are `Clone`, not `Copy`) and carries no constructor (a Vec-backed
36/// constant needs a primary count) — the `Copy`, `from_f64`-carrying nested-dual
37/// oracle path adds those through [`JetFieldConst`].
38pub trait JetField: Clone {
39    /// The real value channel (recurses through any nesting to the `f64` leaf).
40    fn value(&self) -> f64;
41    fn add(&self, o: &Self) -> Self;
42    fn sub(&self, o: &Self) -> Self;
43    fn mul(&self, o: &Self) -> Self;
44    fn neg(&self) -> Self;
45    /// Multiply every channel by a plain `f64`.
46    fn scale(&self, s: f64) -> Self;
47    /// Faà di Bruno composition `f ∘ self` given the OUTER real function's
48    /// derivative stack `d = [f(u), f′(u), f″(u), f‴(u), f⁗(u)]` evaluated at
49    /// `u = self.value()` — the identical `[f64; 5]` stack shape
50    /// [`crate::jet_tower::Tower4::compose_unary`] consumes.
51    fn compose_unary(&self, d: [f64; 5]) -> Self;
52
53    /// A constant carrying THIS element's shape: real value `v`, every
54    /// derivative channel zero.
55    ///
56    /// [`JetField`] deliberately has no dimensionless constructor (a Vec-backed
57    /// runtime-width constant needs a primary count), so a shape has to come
58    /// from an existing element. The default routes through [`Self::compose_unary`]
59    /// with a zero-derivative stack, which is correct for every implementor but
60    /// walks the whole Faa di Bruno partition sum to write a constant — at
61    /// `Dual2<Order2<K>>` that is three inner compositions plus four products,
62    /// all of whose channels are known zero ahead of time. Implementors on a hot
63    /// path override it with the direct construction. (#932)
64    fn constant_like(&self, v: f64) -> Self {
65        self.compose_unary([v, 0.0, 0.0, 0.0, 0.0])
66    }
67
68    /// `self` with its real value channel replaced by `v`, every derivative
69    /// channel untouched.
70    ///
71    /// This is the explicit form of the "anchor the value, keep the
72    /// derivatives" idiom that a row program uses to hold a previously computed
73    /// f64 result bitwise while lifting it into a jet. Expressing it as a
74    /// primitive (rather than as subtract-a-constant-then-add-a-constant) makes
75    /// the bitwise contract exact by construction instead of emergent from
76    /// floating-point cancellation. (#932)
77    fn with_value(&self, v: f64) -> Self {
78        self.sub(&self.constant_like(self.value()))
79            .add(&self.constant_like(v))
80    }
81}
82
83/// A [`JetField`] that is `Copy` and can be built from a real constant with
84/// every derivative channel zero. The nested-dual oracle (`Dual2` over a `Copy`
85/// leaf) needs a dimensionless constructor; the runtime-`p` Vec-backed flex jets
86/// deliberately do NOT satisfy this (their constant needs a primary count), so
87/// it lives on this subtrait rather than the shared algebra base.
88pub trait JetFieldConst: JetField + Copy {
89    /// A constant field element with value `x` and every derivative channel zero.
90    fn from_f64(x: f64) -> Self;
91}
92
93impl JetField for f64 {
94    #[inline]
95    fn value(&self) -> f64 {
96        *self
97    }
98    #[inline]
99    fn add(&self, o: &Self) -> Self {
100        *self + *o
101    }
102    #[inline]
103    fn sub(&self, o: &Self) -> Self {
104        *self - *o
105    }
106    #[inline]
107    fn mul(&self, o: &Self) -> Self {
108        *self * *o
109    }
110    #[inline]
111    fn neg(&self) -> Self {
112        -*self
113    }
114    #[inline]
115    fn scale(&self, s: f64) -> Self {
116        *self * s
117    }
118    #[inline]
119    fn compose_unary(&self, d: [f64; 5]) -> Self {
120        // The stack is already evaluated at `u = *self`; `f(u)` is `d[0]`.
121        d[0]
122    }
123    #[inline]
124    fn constant_like(&self, v: f64) -> Self {
125        v
126    }
127    #[inline]
128    fn with_value(&self, v: f64) -> Self {
129        v
130    }
131}
132
133impl JetFieldConst for f64 {
134    #[inline]
135    fn from_f64(x: f64) -> Self {
136        x
137    }
138}
139
140/// A single-direction second-order jet over the field `S`: value `v`, first
141/// derivative `g`, second derivative `h`, all with respect to ONE seeded
142/// direction. Nest it (`Dual2<Dual2<f64>>`) for a second, independent direction.
143#[derive(Clone, Copy, Debug)]
144pub struct Dual2<S: JetField> {
145    /// Value channel.
146    pub v: S,
147    /// First derivative in this dual's direction.
148    pub g: S,
149    /// Second derivative in this dual's direction.
150    pub h: S,
151}
152
153impl<S: JetFieldConst> Dual2<S> {
154    /// A constant (value `v`, zero derivatives) — carries no dependence on this
155    /// dual's direction (but `v` may still depend on an inner nested direction).
156    #[inline]
157    pub fn constant(v: S) -> Self {
158        Self {
159            v,
160            g: S::from_f64(0.0),
161            h: S::from_f64(0.0),
162        }
163    }
164
165    /// The seeded variable at `v`: unit first derivative in this dual's
166    /// direction, zero second derivative.
167    #[inline]
168    pub fn variable(v: S) -> Self {
169        Self {
170            v,
171            g: S::from_f64(1.0),
172            h: S::from_f64(0.0),
173        }
174    }
175}
176
177impl<S: JetField> JetField for Dual2<S> {
178    #[inline]
179    fn value(&self) -> f64 {
180        self.v.value()
181    }
182    #[inline]
183    fn add(&self, o: &Self) -> Self {
184        Self {
185            v: self.v.add(&o.v),
186            g: self.g.add(&o.g),
187            h: self.h.add(&o.h),
188        }
189    }
190    #[inline]
191    fn sub(&self, o: &Self) -> Self {
192        Self {
193            v: self.v.sub(&o.v),
194            g: self.g.sub(&o.g),
195            h: self.h.sub(&o.h),
196        }
197    }
198    #[inline]
199    fn mul(&self, o: &Self) -> Self {
200        // Leibniz in one direction: (uv)′ = u′v + uv′,
201        // (uv)″ = u″v + 2u′v′ + uv″.
202        Self {
203            v: self.v.mul(&o.v),
204            g: self.v.mul(&o.g).add(&self.g.mul(&o.v)),
205            h: self
206                .v
207                .mul(&o.h)
208                .add(&self.g.mul(&o.g).scale(2.0))
209                .add(&self.h.mul(&o.v)),
210        }
211    }
212    #[inline]
213    fn neg(&self) -> Self {
214        Self {
215            v: self.v.neg(),
216            g: self.g.neg(),
217            h: self.h.neg(),
218        }
219    }
220    #[inline]
221    fn scale(&self, s: f64) -> Self {
222        Self {
223            v: self.v.scale(s),
224            g: self.g.scale(s),
225            h: self.h.scale(s),
226        }
227    }
228    #[inline]
229    fn compose_unary(&self, d: [f64; 5]) -> Self {
230        // f∘self in one direction: with u = self, φ = f,
231        //   value  = φ(u)
232        //   first  = φ′(u)·u′
233        //   second = φ′(u)·u″ + φ″(u)·(u′)²
234        // φ(u), φ′(u), φ″(u) are field-valued: compose the SHIFTED real stacks
235        // with the inner value `self.v`, which propagates any nested direction.
236        let f0 = self.v.compose_unary([d[0], d[1], d[2], d[3], d[4]]);
237        let f1 = self.v.compose_unary([d[1], d[2], d[3], d[4], 0.0]);
238        let f2 = self.v.compose_unary([d[2], d[3], d[4], 0.0, 0.0]);
239        Self {
240            v: f0,
241            g: f1.mul(&self.g),
242            h: f1.mul(&self.h).add(&f2.mul(&self.g).mul(&self.g)),
243        }
244    }
245    #[inline]
246    fn constant_like(&self, v: f64) -> Self {
247        // The default's `g`/`h` are `compose_unary([0;5]).mul(..)` products of a
248        // zero jet, i.e. structurally zero: build them directly.
249        Self {
250            v: self.v.constant_like(v),
251            g: self.v.constant_like(0.0),
252            h: self.v.constant_like(0.0),
253        }
254    }
255    #[inline]
256    fn with_value(&self, v: f64) -> Self {
257        // Only the real value channel lives in `self.v`; this dual's own
258        // derivative channels are untouched.
259        Self {
260            v: self.v.with_value(v),
261            g: self.g.clone(),
262            h: self.h.clone(),
263        }
264    }
265}
266
267impl<S: JetFieldConst> JetFieldConst for Dual2<S> {
268    #[inline]
269    fn from_f64(x: f64) -> Self {
270        Self::constant(S::from_f64(x))
271    }
272}
273
274/// A `Dual2<Dual2<f64>>` seeded with independent directions `a` (outer) and `b`
275/// (inner): value `x`, unit first derivative along both requested directions.
276/// `p0` should be seeded `(a=1, b=0)` and `p1` `(a=0, b=1)` for a two-primary
277/// program (mirrors `Tower4::variable(x, 0)` / `Tower4::variable(x, 1)`).
278pub type Dual22 = Dual2<Dual2<f64>>;
279
280impl Dual22 {
281
282    /// The nine channels this nested dual represents, keyed to the two-primary
283    /// [`crate::jet_tower::Tower4`] indices `0` (outer `a`) and `1` (inner `b`):
284    /// `(value, ∂a, ∂b, ∂aa, ∂ab, ∂bb, ∂aab, ∂abb, ∂aabb)`.
285    #[inline]
286    pub fn channels(&self) -> [f64; 9] {
287        [
288            self.v.v, self.g.v, self.v.g, self.h.v, self.g.g, self.v.h, self.h.g, self.g.h,
289            self.h.h,
290        ]
291    }
292}
293
294#[cfg(test)]
295mod nested_dual_tower4_oracle_tests {
296    use super::*;
297    use crate::jet_tower::Tower4;
298
299    // `Tower4` is a production `JetField` (its `JetScalar` impl in `jet_scalar.rs`
300    // now rides the shared base), so the SAME `program` runs on both `Tower4<2>`
301    // and `Dual2<Dual2<f64>>` with no test-only bridge. The oracle path adds only
302    // the `Copy` constructor through `JetFieldConst`.
303    impl<const K: usize> JetFieldConst for Tower4<K> {
304        fn from_f64(x: f64) -> Self {
305            Tower4::constant(x)
306        }
307    }
308
309}