Skip to main content

gam_math/
jet_partitions.rs

1//! Bitmask-coefficient multi-directional jets used by marginal-slope and
2//! latent-survival row kernels.
3//!
4//! The layout stores one coefficient per direction mask. The calculus itself
5//! lives in [`crate::jet_algebra`]: that module owns the layout-agnostic
6//! Leibniz / Faà di Bruno *combinatorics* once, and the scalar (`n_dirs <= 1`)
7//! path here still routes through it so a fix to the rule is a fix to both
8//! representations.
9//!
10//! ## Why this layout is special (and how the hot path exploits it)
11//!
12//! Each direction is seeded *linearly* (one first-derivative slot), so every
13//! direction variable squares to zero. The coefficients therefore form the
14//! commutative **multilinear / set-function algebra**: `coeffs[mask]` is the
15//! coefficient of `Π_{i ∈ mask} ε_i`. In that algebra two facts collapse the
16//! generic combinatorial walkers into tight branch-free arithmetic:
17//!
18//! * **`mul` is the subset (zeta-style) convolution**
19//!   `out[mask] = Σ_{sub ⊆ mask} a[sub] · b[mask \ sub]`.
20//!   The shared `leibniz_product` walker rebuilds two `SlotBuf`s and folds bit
21//!   lists back into masks (`mask_of`) *per subset*; here we enumerate the
22//!   submasks of `mask` directly — `mask \ sub == mask ^ sub` because
23//!   `sub ⊆ mask` — in the **same ascending order** the walker used, so the
24//!   floating-point accumulation is bit-for-bit identical while every
25//!   `SlotBuf`/closure/`mask_of` allocation and indirection disappears
26//!   (`3^K` pure FMAs, no heap, no `dyn`).
27//!
28//! * **`compose_unary` is the truncated Faà di Bruno composition**, computed
29//!   here by the exact **truncated-Taylor reassociation** rather than a direct
30//!   set-partition sum. Let `v` be the non-constant part of `self`
31//!   (`v[0] = 0`, `v[mask] = self[mask]`) and let `v^{⊛k}` be the `k`-fold
32//!   *subset convolution* (the multilinear power). The ordered-tuple identity
33//!   `v^{⊛k}[mask] = k! · Σ_{π ⊢ mask, |π| = k} Π_{B ∈ π} v[B]` turns the
34//!   set-partition sum into a degree-4 polynomial in `v`:
35//!
36//!   ```text
37//!   f(self)[mask] = Σ_{k=0}^{4} (f^{(k)} / k!) · v^{⊛k}[mask]      (mask ≠ 0)
38//!   f(self)[0]    = f^{(0)}
39//!   ```
40//!
41//!   so a composition is just **three subset convolutions** (`v²`, `v³=v²⊛v`,
42//!   `v⁴=v²⊛v²` — the Motzkin floor for a quartic) plus a five-term combine.
43//!   That is ~3× fewer FLOPs than the per-mask partition gather; each
44//!   convolution is a four-lane compensated dot product (Ogita–Rump–Oishi
45//!   Dot2, FMA-split products + TwoSum carry) so the result is computed in
46//!   ~double the working precision and the rounding of `v²` cannot compound
47//!   through `v³`/`v⁴`; the final per-mask combine is Neumaier-compensated and
48//!   `wide::f64x4`-vectorised; and the whole call runs on reused thread-local
49//!   scratch with no per-call heap traffic. The reassociation is algebraically
50//!   exact; accuracy-vs-truth (a double-double oracle) is the test gate and is
51//!   strictly ≤ the old partition sum's error (see `tests`).
52use std::cell::RefCell;
53use std::sync::atomic::{AtomicU64, Ordering};
54use wide::{CmpGe, f64x4};
55
56pub static COMPOSE_UNARY_CALLS: AtomicU64 = AtomicU64::new(0);
57pub static MUL_CALLS: AtomicU64 = AtomicU64::new(0);
58
59/// Length of the unary derivative stack `[f, f', f'', f''', f'''']`: composition
60/// is exact through order 4, partitions into `>= 5` blocks are truncated.
61const DERIVS: usize = 5;
62
63#[derive(Clone)]
64pub struct MultiDirJet {
65    pub coeffs: Vec<f64>,
66}
67
68impl MultiDirJet {
69    pub fn zero(n_dirs: usize) -> Self {
70        Self {
71            coeffs: vec![0.0; 1usize << n_dirs],
72        }
73    }
74
75    pub fn constant(n_dirs: usize, value: f64) -> Self {
76        let mut out = Self::zero(n_dirs);
77        out.coeffs[0] = value;
78        out
79    }
80
81    pub fn linear(n_dirs: usize, base: f64, first: &[f64]) -> Self {
82        let mut out = Self::constant(n_dirs, base);
83        for (idx, &value) in first.iter().take(n_dirs).enumerate() {
84            out.coeffs[1usize << idx] = value;
85        }
86        out
87    }
88
89    pub fn with_coeffs(n_dirs: usize, coeffs: &[(usize, f64)]) -> Self {
90        let mut out = Self::zero(n_dirs);
91        for &(mask, value) in coeffs {
92            if mask < out.coeffs.len() {
93                out.coeffs[mask] = value;
94            }
95        }
96        out
97    }
98
99    #[inline]
100    pub fn coeff(&self, mask: usize) -> f64 {
101        self.coeffs[mask]
102    }
103
104    pub fn add(&self, other: &Self) -> Self {
105        Self {
106            coeffs: self
107                .coeffs
108                .iter()
109                .zip(other.coeffs.iter())
110                .map(|(lhs, rhs)| lhs + rhs)
111                .collect(),
112        }
113    }
114
115    pub fn scale(&self, scalar: f64) -> Self {
116        Self {
117            coeffs: self.coeffs.iter().map(|value| scalar * value).collect(),
118        }
119    }
120
121    /// Subset-convolution product `out[mask] = Σ_{sub ⊆ mask} a[sub]·b[mask^sub]`.
122    ///
123    /// Bit-identical to the shared [`crate::jet_algebra::leibniz_product`] walker
124    /// (the submasks are enumerated in the same ascending order — the walker's
125    /// compacted subset index is a monotone bit-deposit of the submask) while
126    /// dropping its per-subset `SlotBuf`/closure/`mask_of` overhead. The scalar
127    /// `n_dirs == 0` case keeps the shared walker live as its reference.
128    pub fn mul(&self, other: &Self) -> Self {
129        MUL_CALLS.fetch_add(1, Ordering::Relaxed);
130        let count = self.coeffs.len();
131        if count <= 1 {
132            return self.mul_reference(other);
133        }
134        let a = &self.coeffs;
135        let b = &other.coeffs;
136        let mut out = vec![0.0; count];
137        for (mask, slot) in out.iter_mut().enumerate() {
138            // Walk every submask of `mask` in ascending numeric order — the same
139            // order `leibniz_product` accumulates — via the classic gap-fill
140            // increment `next = ((sub | !mask) + 1) & mask`.
141            let mut acc = 0.0;
142            let mut sub = 0usize;
143            loop {
144                acc += a[sub] * b[mask ^ sub];
145                if sub == mask {
146                    break;
147                }
148                sub = (sub | !mask).wrapping_add(1) & mask;
149            }
150            *slot = acc;
151        }
152        Self { coeffs: out }
153    }
154
155    /// The pre-#perf shared-walker product, retained verbatim as the scalar-case
156    /// implementation and as the bit-exact reference for `mul`.
157    fn mul_reference(&self, other: &Self) -> Self {
158        let count = self.coeffs.len();
159        let mut out = vec![0.0; count];
160        for (mask, slot) in out.iter_mut().enumerate() {
161            let bits = bit_positions(mask);
162            *slot = crate::jet_algebra::leibniz_product(
163                bits.as_slice(),
164                |t| self.coeffs[mask_of(t)],
165                |c| other.coeffs[mask_of(c)],
166            );
167        }
168        Self { coeffs: out }
169    }
170
171    /// Exact (order-4 truncated) unary composition `f(self)` from the Taylor
172    /// stack `[f, f', f'', f''', f'''']` at `self.coeff(0)`.
173    ///
174    /// Computed by the truncated-Taylor reassociation (see the module note):
175    /// `f(self) = Σ_{k=0}^{4} (f^{(k)}/k!)·v^{⊛k}` with `v` the non-constant
176    /// part of `self`. The three subset-convolution powers `v²`, `v³`, `v⁴`
177    /// are compensated (Dot2) and the per-mask combine is Neumaier-compensated
178    /// and vectorised, so the result is *more* accurate vs. the true
179    /// real-arithmetic value than the prior naive partition sum (proven against
180    /// a double-double oracle in `tests`). The scalar `n_dirs == 0` case keeps
181    /// the shared Faà di Bruno walker live as its reference.
182    pub fn compose_unary(&self, derivs: [f64; DERIVS]) -> Self {
183        COMPOSE_UNARY_CALLS.fetch_add(1, Ordering::Relaxed);
184        let count = self.coeffs.len();
185        if count <= 1 {
186            return <Self as crate::jet_algebra::JetAlgebra<DERIVS>>::compose_unary(self, derivs);
187        }
188        // Per-block Taylor coefficients c_k = f^{(k)} / k!  (k = 1..=4): the
189        // `1/k!` undoes the ordered-tuple overcount of the subset-convolution
190        // power v^{⊛k} relative to the unordered set-partition sum.
191        let c1 = derivs[1];
192        let c2 = derivs[2] * 0.5;
193        let c3 = derivs[3] * (1.0 / 6.0);
194        let c4 = derivs[4] * (1.0 / 24.0);
195
196        let mut out = vec![0.0; count];
197        COMPOSE_SCRATCH.with(|cell| {
198            let mut buf = cell.borrow_mut();
199            // Four contiguous scratch lanes: v, p2 = v², p3 = v³, p4 = v⁴.
200            buf.clear();
201            buf.resize(4 * count, 0.0);
202            let (vbuf, rest) = buf.split_at_mut(count);
203            let (p2, rest) = rest.split_at_mut(count);
204            let (p3, p4) = rest.split_at_mut(count);
205
206            // v = non-constant part of self (the constant channel squares to a
207            // 0-block, which the k = 0 term carries separately).
208            vbuf.copy_from_slice(&self.coeffs);
209            vbuf[0] = 0.0;
210
211            // Powers via compensated subset convolution, pruned by output
212            // popcount: v^{⊛k}[mask] = 0 whenever popcount(mask) < k.
213            subset_conv_into(vbuf, vbuf, p2, 2);
214            subset_conv_into(p2, vbuf, p3, 3);
215            subset_conv_into(p2, p2, p4, 4);
216
217            // out[mask] = c1·v + c2·v² + c3·v³ + c4·v⁴ (mask ≠ 0), Neumaier-
218            // compensated and f64x4-vectorised over masks. out[0] = f^{(0)}.
219            combine_powers(vbuf, p2, p3, p4, [c1, c2, c3, c4], &mut out);
220            out[0] = derivs[0];
221        });
222        Self { coeffs: out }
223    }
224}
225
226thread_local! {
227    /// Reused composition scratch (`4·count` f64s: v, v², v³, v⁴). Sized up on
228    /// demand and never freed, so a steady-state `compose_unary` does zero heap
229    /// work beyond the owned output `Vec`.
230    static COMPOSE_SCRATCH: RefCell<Vec<f64>> = const { RefCell::new(Vec::new()) };
231}
232
233/// Branchless TwoSum: returns `(s, e)` with `s = fl(a+b)` and `a+b = s+e`
234/// exactly (Knuth/Møller). Used by the compensated convolution and combine.
235#[inline(always)]
236fn two_sum(a: f64, b: f64) -> (f64, f64) {
237    let s = a + b;
238    let bb = s - a;
239    let e = (a - (s - bb)) + (b - bb);
240    (s, e)
241}
242
243/// Subset (zeta-style) convolution `out[mask] = Σ_{sub ⊆ mask} a[sub]·b[mask^sub]`,
244/// evaluated as a **compensated dot product** (Ogita–Rump–Oishi Dot2): each
245/// product is split into head + FMA error (`mul_add`) and the running sum
246/// carries a TwoSum error term, so the result is accurate as if computed in
247/// ~twice the working precision. This stops the rounding of `v²` from
248/// compounding through `v³`/`v⁴`, which a single-rounding accumulation does
249/// not. Output masks with `popcount < min_pop` are left at zero: the
250/// multilinear power `v^{⊛k}` vanishes below popcount `k`, so the prune is exact
251/// and skips the low-order masks entirely.
252#[inline]
253fn subset_conv_into(a: &[f64], b: &[f64], out: &mut [f64], min_pop: u32) {
254    for (mask, slot) in out.iter_mut().enumerate() {
255        if (mask as u64).count_ones() < min_pop {
256            *slot = 0.0;
257            continue;
258        }
259        // Descending submask enumeration `sub = (sub-1) & mask`, terminating
260        // after `sub == 0` (the classic Gosper-style submask walk). The Dot2 is
261        // spread across FOUR independent named accumulators (a 4-way unroll) so
262        // the FMA/TwoSum latency chains overlap — the loop becomes throughput-
263        // rather than latency-bound — then the lanes are merged with a final
264        // compensated reduction. Every non-pruned mask has popcount ≥ 2, so its
265        // `2^popcount` submask count is a multiple of 4 and the unroll is exact
266        // (the all-zero submask always lands in the fourth lane). Reassociation
267        // only; the value is the same real sum, in ~double the working precision.
268        #[inline(always)]
269        fn dot2_step(s: &mut f64, c: &mut f64, x: f64, y: f64) {
270            let prod = x * y;
271            let prod_err = x.mul_add(y, -prod); // exact: prod + prod_err == x*y
272            let (t, sum_err) = two_sum(*s, prod);
273            *s = t;
274            *c += prod_err + sum_err;
275        }
276        let (mut s0, mut s1, mut s2, mut s3) = (0.0f64, 0.0f64, 0.0f64, 0.0f64);
277        let (mut c0, mut c1, mut c2, mut c3) = (0.0f64, 0.0f64, 0.0f64, 0.0f64);
278        let mut sub = mask;
279        loop {
280            dot2_step(&mut s0, &mut c0, a[sub], b[mask ^ sub]);
281            sub = (sub - 1) & mask;
282            dot2_step(&mut s1, &mut c1, a[sub], b[mask ^ sub]);
283            sub = (sub - 1) & mask;
284            dot2_step(&mut s2, &mut c2, a[sub], b[mask ^ sub]);
285            sub = (sub - 1) & mask;
286            dot2_step(&mut s3, &mut c3, a[sub], b[mask ^ sub]);
287            if sub == 0 {
288                break;
289            }
290            sub = (sub - 1) & mask;
291        }
292        // Merge the four lanes, compensated.
293        let (s01, e01) = two_sum(s0, s1);
294        let (s23, e23) = two_sum(s2, s3);
295        let (total, etot) = two_sum(s01, s23);
296        *slot = total + (etot + e01 + e23 + c0 + c1 + c2 + c3);
297    }
298}
299
300/// `out[mask] = c[0]·p1 + c[1]·p2 + c[2]·p3 + c[3]·p4` for `mask ≥ 1`, with a
301/// Neumaier-compensated four-term accumulation (the powers span growing
302/// magnitudes, so the compensation recovers the bits a naive `+=` would drop)
303/// and a `wide::f64x4` body over four masks at a time. `out[0]` is overwritten
304/// by the caller with the value channel.
305#[inline]
306fn combine_powers(p1: &[f64], p2: &[f64], p3: &[f64], p4: &[f64], c: [f64; 4], out: &mut [f64]) {
307    let n = out.len();
308    let (c1, c2, c3, c4) = (c[0], c[1], c[2], c[3]);
309    let (v1, v2, v3, v4) = (
310        f64x4::splat(c1),
311        f64x4::splat(c2),
312        f64x4::splat(c3),
313        f64x4::splat(c4),
314    );
315    let mut mask = 0usize;
316    // Vector body: four contiguous masks per step. Neumaier compensation is
317    // applied lane-wise; pick the larger magnitude to subtract first.
318    while mask + 4 <= n {
319        let load = |p: &[f64]| f64x4::new([p[mask], p[mask + 1], p[mask + 2], p[mask + 3]]);
320        let mut s = v1 * load(p1);
321        let mut comp = f64x4::splat(0.0);
322        for (cv, pv) in [(v2, p2), (v3, p3), (v4, p4)] {
323            let term = cv * load(pv);
324            let t = s + term;
325            let big_s = s.abs().cmp_ge(term.abs());
326            let lost = big_s.blend((s - t) + term, (term - t) + s);
327            comp += lost;
328            s = t;
329        }
330        let res = s + comp;
331        out[mask..mask + 4].copy_from_slice(&res.to_array());
332        mask += 4;
333    }
334    // Scalar tail (and the small-K path where `n < 4`).
335    while mask < n {
336        let mut s = c1 * p1[mask];
337        let mut comp = 0.0f64;
338        for (cv, pv) in [(c2, p2), (c3, p3), (c4, p4)] {
339            let term = cv * pv[mask];
340            let (t, e) = two_sum(s, term);
341            comp += e;
342            s = t;
343        }
344        out[mask] = s + comp;
345        mask += 1;
346    }
347}
348
349impl crate::jet_algebra::JetAlgebra<DERIVS> for MultiDirJet {
350    #[inline]
351    fn derivative(&self, slots: &[usize]) -> f64 {
352        self.coeffs[mask_of(slots)]
353    }
354
355    fn map_derivatives<F>(&self, mut f: F) -> Self
356    where
357        F: FnMut(&[usize]) -> f64,
358    {
359        let mut out = vec![0.0; self.coeffs.len()];
360        for (mask, value) in out.iter_mut().enumerate() {
361            let bits = bit_positions(mask);
362            *value = f(bits.as_slice());
363        }
364        Self { coeffs: out }
365    }
366}
367
368/// A flattened set-partition table for a fixed slot count. `parts[i] = (off,
369/// order)` describes one partition: its `order` block submasks (compacted) are
370/// `flat[off .. off + order]`.
371///
372/// This direct set-partition sum is the previous production `compose_unary`
373/// implementation, retained (test-gated) as the **accuracy reference** the new
374/// truncated-Taylor path is graded against: a double-double oracle is the
375/// truth, and the test asserts the new path's error-vs-truth is `≤` this naive
376/// partition sum's error-vs-truth on every randomised program.
377#[cfg(test)]
378struct PartTable {
379    flat: Vec<u32>,
380    parts: Vec<(usize, u8)>,
381}
382
383#[cfg(test)]
384thread_local! {
385    /// Cached set-partition tables, indexed by slot count `m`. Entry `m` holds
386    /// every partition of `{0..m}` into `< DERIVS` blocks, in the shared
387    /// walker's recursion order, each block a compacted submask. Pure function
388    /// of `m`, so caching is sound and deterministic.
389    static PARTITION_TABLES: RefCell<Vec<std::rc::Rc<PartTable>>> =
390        const { RefCell::new(Vec::new()) };
391}
392
393/// Return cached partition tables for slot counts `0..=n_dirs`.
394#[cfg(test)]
395fn partition_tables(n_dirs: usize) -> Vec<std::rc::Rc<PartTable>> {
396    PARTITION_TABLES.with(|cell| {
397        let mut tables = cell.borrow_mut();
398        while tables.len() <= n_dirs {
399            let m = tables.len();
400            tables.push(std::rc::Rc::new(build_partitions(m)));
401        }
402        (0..=n_dirs).map(|m| std::rc::Rc::clone(&tables[m])).collect()
403    })
404}
405
406/// The previous production `compose_unary`: a direct set-partition (Faà di
407/// Bruno) sum per output mask, retained test-gated as the accuracy reference.
408#[cfg(test)]
409fn compose_unary_partition_reference(coeffs: &[f64], derivs: [f64; DERIVS]) -> Vec<f64> {
410    let count = coeffs.len();
411    let n_dirs = count.trailing_zeros() as usize;
412    let tables = partition_tables(n_dirs);
413    let mut out = vec![0.0; count];
414    let mut remap = vec![0usize; count];
415    let mut pos = [0usize; usize::BITS as usize];
416    for (mask, slot) in out.iter_mut().enumerate() {
417        if mask == 0 {
418            *slot = derivs[0];
419            continue;
420        }
421        let mut npos = 0usize;
422        let mut m = mask;
423        while m != 0 {
424            pos[npos] = m.trailing_zeros() as usize;
425            npos += 1;
426            m &= m - 1;
427        }
428        remap[0] = 0;
429        for cb in 1usize..(1usize << npos) {
430            let low = cb.trailing_zeros() as usize;
431            remap[cb] = remap[cb & (cb - 1)] | (1usize << pos[low]);
432        }
433        let table = &tables[npos];
434        let flat = &table.flat;
435        let mut total = 0.0;
436        for &(off, order) in table.parts.iter() {
437            let order = order as usize;
438            let mut prod = derivs[order];
439            for &cb in &flat[off..off + order] {
440                prod *= coeffs[remap[cb as usize]];
441            }
442            total += prod;
443        }
444        *slot = total;
445    }
446    out
447}
448
449/// Enumerate the set-partitions of `{0..m}` with fewer than `DERIVS` blocks, in
450/// the exact DFS order of [`crate::jet_algebra`]'s `for_each_partition`
451/// recursion ("place each element into an existing block, else open a new one"),
452/// each block recorded as a compacted submask of `{0..m}`, flattened.
453#[cfg(test)]
454fn build_partitions(m: usize) -> PartTable {
455    fn recurse(elem: usize, m: usize, blocks: &mut [u32; 8], n_blocks: usize, out: &mut PartTable) {
456        // Partitions with `>= DERIVS` blocks are truncated (their `f^{(order)}`
457        // is beyond the stack); the block count never decreases, so the whole
458        // subtree contributes nothing and is pruned — matching the walker's
459        // per-partition `order >= derivs.len()` skip.
460        if n_blocks >= DERIVS {
461            return;
462        }
463        if elem == m {
464            let off = out.flat.len();
465            out.flat.extend_from_slice(&blocks[..n_blocks]);
466            out.parts.push((off, n_blocks as u8));
467            return;
468        }
469        for b in 0..n_blocks {
470            blocks[b] |= 1u32 << elem;
471            recurse(elem + 1, m, blocks, n_blocks, out);
472            blocks[b] &= !(1u32 << elem);
473        }
474        blocks[n_blocks] = 1u32 << elem;
475        recurse(elem + 1, m, blocks, n_blocks + 1, out);
476    }
477    let mut out = PartTable {
478        flat: Vec::new(),
479        parts: Vec::new(),
480    };
481    let mut blocks = [0u32; 8];
482    recurse(0, m, &mut blocks, 0, &mut out);
483    out
484}
485
486/// The set-bit positions of `mask`, low to high — the differentiation slots of
487/// that coefficient.
488fn bit_positions(mask: usize) -> crate::jet_algebra::SlotBuf {
489    let mut out = crate::jet_algebra::SlotBuf::new();
490    let mut m = mask;
491    while m != 0 {
492        let bit = m.trailing_zeros() as usize;
493        out.push_slot(bit);
494        m &= m - 1;
495    }
496    out
497}
498
499/// Combine a slot-group (list of bit positions) back into a sub-mask.
500fn mask_of(slots: &[usize]) -> usize {
501    slots.iter().fold(0usize, |acc, &b| acc | (1usize << b))
502}
503
504// #932-2 cutover: `MultiDirJet::bilinear` (the 4-coeff `[base, d1, d2, d12]`
505// constructor) and `MultiDirJet::sub` are consumed ONLY by the now test-only hand
506// survival directional/bidirectional oracle (the production flex jet path uses the
507// `flex_jet` runtime jet algebra, not `MultiDirJet`). After the #1521 crate split
508// moved `MultiDirJet` into `gam-math`, those oracle tests live in the dependent
509// `gam` crate, where a `#[cfg(test)]` gate in *this* crate is inactive — so the
510// methods must be plain `pub` inherent methods to be reachable cross-crate. They
511// carry no dead-code cost because `pub` items are part of the crate's public API.
512// Bodies are byte-identical to their former gated form.
513impl MultiDirJet {
514    pub fn bilinear(base: f64, d1: f64, d2: f64, d12: f64) -> Self {
515        Self {
516            coeffs: vec![base, d1, d2, d12],
517        }
518    }
519
520    pub fn sub(&self, other: &Self) -> Self {
521        Self {
522            coeffs: self
523                .coeffs
524                .iter()
525                .zip(other.coeffs.iter())
526                .map(|(lhs, rhs)| lhs - rhs)
527                .collect(),
528        }
529    }
530}
531
532#[cfg(test)]
533mod tests {
534    use super::*;
535
536    // ── constructors ─────────────────────────────────────────────────────────
537
538    #[test]
539    fn zero_has_correct_length_and_all_zero_coefficients() {
540        let j = MultiDirJet::zero(3);
541        assert_eq!(j.coeffs.len(), 8);
542        assert!(j.coeffs.iter().all(|&v| v == 0.0));
543    }
544
545    #[test]
546    fn constant_has_value_at_mask_zero_and_zeros_elsewhere() {
547        let j = MultiDirJet::constant(2, 5.0);
548        assert_eq!(j.coeffs.len(), 4);
549        assert_eq!(j.coeff(0), 5.0);
550        assert_eq!(j.coeff(1), 0.0);
551        assert_eq!(j.coeff(2), 0.0);
552        assert_eq!(j.coeff(3), 0.0);
553    }
554
555    #[test]
556    fn linear_sets_base_and_per_direction_slots() {
557        let j = MultiDirJet::linear(2, 1.0, &[2.0, 3.0]);
558        assert_eq!(j.coeff(0), 1.0); // constant
559        assert_eq!(j.coeff(1), 2.0); // mask 0b01 — direction 0
560        assert_eq!(j.coeff(2), 3.0); // mask 0b10 — direction 1
561        assert_eq!(j.coeff(3), 0.0); // cross term is zero
562    }
563
564    #[test]
565    fn bilinear_sets_all_four_slots() {
566        let j = MultiDirJet::bilinear(1.0, 2.0, 3.0, 4.0);
567        assert_eq!(j.coeff(0), 1.0);
568        assert_eq!(j.coeff(1), 2.0);
569        assert_eq!(j.coeff(2), 3.0);
570        assert_eq!(j.coeff(3), 4.0);
571    }
572
573    #[test]
574    fn with_coeffs_sets_only_specified_entries() {
575        let j = MultiDirJet::with_coeffs(2, &[(0, 9.0), (3, -1.0)]);
576        assert_eq!(j.coeff(0), 9.0);
577        assert_eq!(j.coeff(1), 0.0);
578        assert_eq!(j.coeff(2), 0.0);
579        assert_eq!(j.coeff(3), -1.0);
580    }
581
582    // ── elementwise arithmetic ────────────────────────────────────────────────
583
584    #[test]
585    fn add_is_elementwise() {
586        let a = MultiDirJet::linear(2, 1.0, &[2.0, 3.0]);
587        let b = MultiDirJet::linear(2, 4.0, &[5.0, 6.0]);
588        let c = a.add(&b);
589        assert_eq!(c.coeff(0), 5.0);
590        assert_eq!(c.coeff(1), 7.0);
591        assert_eq!(c.coeff(2), 9.0);
592        assert_eq!(c.coeff(3), 0.0);
593    }
594
595    #[test]
596    fn scale_multiplies_all_coefficients() {
597        let j = MultiDirJet::linear(2, 1.0, &[2.0, 3.0]);
598        let s = j.scale(2.0);
599        assert_eq!(s.coeff(0), 2.0);
600        assert_eq!(s.coeff(1), 4.0);
601        assert_eq!(s.coeff(2), 6.0);
602        assert_eq!(s.coeff(3), 0.0);
603    }
604
605    #[test]
606    fn sub_is_elementwise_difference() {
607        let a = MultiDirJet::constant(2, 5.0);
608        let b = MultiDirJet::constant(2, 3.0);
609        let c = a.sub(&b);
610        assert_eq!(c.coeff(0), 2.0);
611        assert_eq!(c.coeff(1), 0.0);
612        assert_eq!(c.coeff(2), 0.0);
613        assert_eq!(c.coeff(3), 0.0);
614    }
615
616    // ── mul (subset-convolution) ──────────────────────────────────────────────
617
618    #[test]
619    fn mul_of_constants_is_scalar_product() {
620        let a = MultiDirJet::constant(2, 2.0);
621        let b = MultiDirJet::constant(2, 3.0);
622        let c = a.mul(&b);
623        assert_eq!(c.coeff(0), 6.0);
624        assert_eq!(c.coeff(1), 0.0);
625        assert_eq!(c.coeff(2), 0.0);
626        assert_eq!(c.coeff(3), 0.0);
627    }
628
629    #[test]
630    fn mul_satisfies_leibniz_rule_single_direction() {
631        // (1 + ε) * (1 + ε) = 1 + 2ε
632        let x = MultiDirJet::linear(1, 1.0, &[1.0]);
633        let y = MultiDirJet::linear(1, 1.0, &[1.0]);
634        let z = x.mul(&y);
635        assert_eq!(z.coeff(0), 1.0);
636        assert_eq!(z.coeff(1), 2.0);
637    }
638
639    #[test]
640    fn mul_cross_term_two_independent_directions() {
641        // (1 + ε₁)(1 + ε₂) = 1 + ε₁ + ε₂ + ε₁ε₂
642        let x = MultiDirJet::linear(2, 1.0, &[1.0, 0.0]);
643        let y = MultiDirJet::linear(2, 1.0, &[0.0, 1.0]);
644        let z = x.mul(&y);
645        assert_eq!(z.coeff(0), 1.0);
646        assert_eq!(z.coeff(1), 1.0);
647        assert_eq!(z.coeff(2), 1.0);
648        assert_eq!(z.coeff(3), 1.0);
649    }
650
651    // ── compose_unary: truncated-Taylor reassociation ─────────────────────────
652    //
653    // The new `compose_unary` reassociates the per-mask Faà di Bruno set-partition
654    // sum into a degree-4 polynomial in the subset-convolution power of the
655    // non-constant part. These tests are the accuracy gate: a double-double
656    // oracle is the truth, and the new path's error-vs-truth must be `≤` the old
657    // naive partition sum's error-vs-truth on every randomised program.
658
659    /// Deterministic xorshift64* — no `rand` dependency in the test.
660    struct Rng(u64);
661    impl Rng {
662        fn next_u64(&mut self) -> u64 {
663            let mut x = self.0;
664            x ^= x >> 12;
665            x ^= x << 25;
666            x ^= x >> 27;
667            self.0 = x;
668            x.wrapping_mul(0x2545F4914F6CDD1D)
669        }
670        /// Uniform in `[-scale, scale]`.
671        fn signed(&mut self, scale: f64) -> f64 {
672            let u = (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64; // [0,1)
673            (2.0 * u - 1.0) * scale
674        }
675    }
676
677    // ── A double-double oracle for the exact (order-4 truncated) composition ──
678
679    #[inline]
680    fn two_prod(a: f64, b: f64) -> (f64, f64) {
681        let p = a * b;
682        (p, a.mul_add(b, -p))
683    }
684    #[inline]
685    fn dd_two_sum(a: f64, b: f64) -> (f64, f64) {
686        let s = a + b;
687        let bb = s - a;
688        (s, (a - (s - bb)) + (b - bb))
689    }
690    #[derive(Clone, Copy)]
691    struct Dd {
692        hi: f64,
693        lo: f64,
694    }
695    impl Dd {
696        fn from(x: f64) -> Self {
697            Self { hi: x, lo: 0.0 }
698        }
699        fn mul_f64(self, b: f64) -> Self {
700            let (p, e) = two_prod(self.hi, b);
701            let lo = self.lo.mul_add(b, e);
702            let s = p + lo;
703            Self {
704                hi: s,
705                lo: (p - s) + lo,
706            }
707        }
708        fn add(self, o: Self) -> Self {
709            let (s, e) = dd_two_sum(self.hi, o.hi);
710            let (s2, e2) = dd_two_sum(self.lo, o.lo);
711            let lo = e + s2;
712            let h1 = s + lo;
713            let l1 = (s - h1) + lo;
714            let lo2 = l1 + e2;
715            let h = h1 + lo2;
716            Self {
717                hi: h,
718                lo: (h1 - h) + lo2,
719            }
720        }
721        /// `|self - x|` to ~double precision in the residual (Sterbenz: `x` and
722        /// `hi` agree to ~53 bits, so `x - hi` is essentially exact).
723        fn abs_err_to(self, x: f64) -> f64 {
724            ((x - self.hi) - self.lo).abs()
725        }
726    }
727
728    /// High-precision truth for `compose_unary` via the set-partition reference,
729    /// every product and sum carried in double-double.
730    fn compose_truth(coeffs: &[f64], derivs: [f64; DERIVS]) -> Vec<Dd> {
731        let count = coeffs.len();
732        let n_dirs = count.trailing_zeros() as usize;
733        let tables = partition_tables(n_dirs);
734        let mut out = vec![Dd::from(0.0); count];
735        let mut remap = vec![0usize; count];
736        let mut pos = [0usize; 64];
737        for (mask, slot) in out.iter_mut().enumerate() {
738            if mask == 0 {
739                *slot = Dd::from(derivs[0]);
740                continue;
741            }
742            let mut npos = 0usize;
743            let mut m = mask;
744            while m != 0 {
745                pos[npos] = m.trailing_zeros() as usize;
746                npos += 1;
747                m &= m - 1;
748            }
749            remap[0] = 0;
750            for cb in 1usize..(1usize << npos) {
751                let low = cb.trailing_zeros() as usize;
752                remap[cb] = remap[cb & (cb - 1)] | (1usize << pos[low]);
753            }
754            let table = &tables[npos];
755            let mut total = Dd::from(0.0);
756            for &(off, order) in table.parts.iter() {
757                let order = order as usize;
758                let mut prod = Dd::from(derivs[order]);
759                for &cb in &table.flat[off..off + order] {
760                    prod = prod.mul_f64(coeffs[remap[cb as usize]]);
761                }
762                total = total.add(prod);
763            }
764            *slot = total;
765        }
766        out
767    }
768
769    /// Build a random composite jet so the composition input is a realistic
770    /// non-trivial multilinear element (not just seeded directions).
771    fn random_inner(n_dirs: usize, rng: &mut Rng) -> MultiDirJet {
772        let base = rng.signed(0.8);
773        let first: Vec<f64> = (0..n_dirs).map(|_| rng.signed(0.6)).collect();
774        let a = MultiDirJet::linear(n_dirs, base, &first);
775        let b = MultiDirJet::linear(
776            n_dirs,
777            rng.signed(0.7),
778            &(0..n_dirs).map(|_| rng.signed(0.5)).collect::<Vec<_>>(),
779        );
780        // a*b + a populates the full cross-mask spectrum.
781        a.mul(&b).add(&a)
782    }
783
784    #[test]
785    fn compose_unary_matches_partition_reference_simple() {
786        // exp-like stack on a 2-direction cross jet: every coeff agrees with the
787        // direct set-partition reference to a tight tolerance.
788        let j = MultiDirJet::linear(2, 0.3, &[0.5, -0.4])
789            .mul(&MultiDirJet::linear(2, -0.2, &[0.1, 0.7]));
790        let d = [0.9_f64, 1.1, -0.7, 0.4, -0.25];
791        let got = j.compose_unary(d);
792        let want = compose_unary_partition_reference(&j.coeffs, d);
793        for (mask, (&g, &w)) in got.coeffs.iter().zip(want.iter()).enumerate() {
794            let tol = 1e-13 * w.abs().max(1.0);
795            assert!(
796                (g - w).abs() <= tol,
797                "mask {mask}: got={g:.17e} want={w:.17e}"
798            );
799        }
800    }
801
802    #[test]
803    fn compose_unary_accuracy_beats_partition_sum_vs_double_double() {
804        // The accuracy gate. Over many random programs at every K used in
805        // production, the new path's error-vs-truth is never worse than the old
806        // naive partition sum's, and is a strict improvement in aggregate.
807        let mut rng = Rng(0x1234_5678_9abc_def0);
808        let mut sum_new = 0.0f64;
809        let mut sum_old = 0.0f64;
810        for &n_dirs in &[2usize, 3, 4, 6, 8] {
811            for _ in 0..200 {
812                let inner = random_inner(n_dirs, &mut rng);
813                let d = [
814                    rng.signed(1.5),
815                    rng.signed(1.5),
816                    rng.signed(2.0),
817                    rng.signed(3.0),
818                    rng.signed(4.0),
819                ];
820                let new = inner.compose_unary(d);
821                let old = compose_unary_partition_reference(&inner.coeffs, d);
822                let truth = compose_truth(&inner.coeffs, d);
823                for mask in 0..inner.coeffs.len() {
824                    let en = truth[mask].abs_err_to(new.coeffs[mask]);
825                    let eo = truth[mask].abs_err_to(old[mask]);
826                    sum_new += en;
827                    sum_old += eo;
828                    // Per-coefficient: new is never materially worse. The 4 ULP
829                    // slack absorbs the rare tie where a differently-grouped but
830                    // equally-valid rounding lands one ULP either way.
831                    let scale = truth[mask].hi.abs().max(1.0);
832                    assert!(
833                        en <= eo + 4.0 * f64::EPSILON * scale,
834                        "K={n_dirs} mask={mask}: new_err={en:.3e} old_err={eo:.3e}"
835                    );
836                }
837            }
838        }
839        // Aggregate: the compensated reassociation is a real improvement.
840        assert!(
841            sum_new <= sum_old,
842            "aggregate error regressed: new={sum_new:.6e} old={sum_old:.6e}"
843        );
844        eprintln!(
845            "compose_unary accuracy: total |err| new={sum_new:.6e} old={sum_old:.6e} \
846             (improvement {:.2}x)",
847            sum_old / sum_new.max(f64::MIN_POSITIVE)
848        );
849    }
850
851    #[test]
852    fn compose_unary_speedup_over_partition_sum() {
853        // Measure ns/call new vs. the previous partition-sum implementation
854        // across the production K range. Prints the multiple; asserts a
855        // conservative floor so CI noise can't make it flaky.
856        use std::time::Instant;
857        let mut rng = Rng(0xfeed_face_dead_beef);
858        for &n_dirs in &[2usize, 4, 6, 8] {
859            let n_inputs = 256usize;
860            let inputs: Vec<(MultiDirJet, [f64; DERIVS])> = (0..n_inputs)
861                .map(|_| {
862                    (
863                        random_inner(n_dirs, &mut rng),
864                        [
865                            rng.signed(1.5),
866                            rng.signed(1.5),
867                            rng.signed(2.0),
868                            rng.signed(3.0),
869                            rng.signed(4.0),
870                        ],
871                    )
872                })
873                .collect();
874            let iters = 200usize;
875            // Warm the scratch / partition tables.
876            for (j, d) in &inputs {
877                std::hint::black_box(j.compose_unary(*d));
878                std::hint::black_box(compose_unary_partition_reference(&j.coeffs, *d));
879            }
880            let t0 = Instant::now();
881            for _ in 0..iters {
882                for (j, d) in &inputs {
883                    std::hint::black_box(j.compose_unary(*d));
884                }
885            }
886            let new_ns = t0.elapsed().as_nanos() as f64 / (iters * inputs.len()) as f64;
887            let t1 = Instant::now();
888            for _ in 0..iters {
889                for (j, d) in &inputs {
890                    std::hint::black_box(compose_unary_partition_reference(&j.coeffs, *d));
891                }
892            }
893            let old_ns = t1.elapsed().as_nanos() as f64 / (iters * inputs.len()) as f64;
894            eprintln!(
895                "compose_unary K={n_dirs}: new={new_ns:.1} ns/call  old={old_ns:.1} ns/call  \
896                 speedup={:.2}x",
897                old_ns / new_ns
898            );
899            // Guard only where the algorithmic win is robust: an optimised build
900            // at the production-dominant K (the partition sum's `Σ_π |π|` work
901            // grows steeply with K, while the new path is three convolutions).
902            // Debug builds and tiny K are dominated by fixed per-call overhead
903            // and the ratio there is not a meaningful guard, so it is printed
904            // but not asserted (and timing asserts must not flake on CI).
905            if !cfg!(debug_assertions) && n_dirs >= 6 {
906                assert!(
907                    new_ns < old_ns,
908                    "K={n_dirs} new path slower: new={new_ns:.1}ns old={old_ns:.1}ns"
909                );
910            }
911        }
912    }
913}