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/// The set-bit positions of `mask`, low to high — the differentiation slots of
369/// that coefficient.
370fn bit_positions(mask: usize) -> crate::jet_algebra::SlotBuf {
371 let mut out = crate::jet_algebra::SlotBuf::new();
372 let mut m = mask;
373 while m != 0 {
374 let bit = m.trailing_zeros() as usize;
375 out.push_slot(bit);
376 m &= m - 1;
377 }
378 out
379}
380
381/// Combine a slot-group (list of bit positions) back into a sub-mask.
382fn mask_of(slots: &[usize]) -> usize {
383 slots.iter().fold(0usize, |acc, &b| acc | (1usize << b))
384}
385
386// #932-2 cutover: `MultiDirJet::bilinear` (the 4-coeff `[base, d1, d2, d12]`
387// constructor) and `MultiDirJet::sub` are consumed ONLY by the now test-only hand
388// survival directional/bidirectional oracle (the production flex jet path uses the
389// `flex_jet` runtime jet algebra, not `MultiDirJet`). After the #1521 crate split
390// moved `MultiDirJet` into `gam-math`, those oracle tests live in the dependent
391// `gam` crate, where a `#[cfg(test)]` gate in *this* crate is inactive — so the
392// methods must be plain `pub` inherent methods to be reachable cross-crate. They
393// carry no dead-code cost because `pub` items are part of the crate's public API.
394// Bodies are byte-identical to their former gated form.
395impl MultiDirJet {
396 pub fn bilinear(base: f64, d1: f64, d2: f64, d12: f64) -> Self {
397 Self {
398 coeffs: vec![base, d1, d2, d12],
399 }
400 }
401
402 pub fn sub(&self, other: &Self) -> Self {
403 Self {
404 coeffs: self
405 .coeffs
406 .iter()
407 .zip(other.coeffs.iter())
408 .map(|(lhs, rhs)| lhs - rhs)
409 .collect(),
410 }
411 }
412}
413
414#[cfg(test)]
415mod tests {
416 use super::*;
417
418 /// A flattened set-partition table for a fixed slot count. `parts[i] = (off,
419 /// order)` describes one partition: its `order` block submasks (compacted) are
420 /// `flat[off .. off + order]`.
421 ///
422 /// This direct set-partition sum is the previous production `compose_unary`
423 /// implementation, retained as the **accuracy reference** the new
424 /// truncated-Taylor path is graded against: a double-double oracle is the
425 /// truth, and the test asserts the new path's error-vs-truth is `≤` this naive
426 /// partition sum's error-vs-truth on every randomised program.
427 struct PartTable {
428 flat: Vec<u32>,
429 parts: Vec<(usize, u8)>,
430 }
431
432 thread_local! {
433 /// Cached set-partition tables, indexed by slot count `m`. Entry `m` holds
434 /// every partition of `{0..m}` into `< DERIVS` blocks, in the shared
435 /// walker's recursion order, each block a compacted submask. Pure function
436 /// of `m`, so caching is sound and deterministic.
437 static PARTITION_TABLES: RefCell<Vec<std::rc::Rc<PartTable>>> =
438 const { RefCell::new(Vec::new()) };
439 }
440
441 /// Return cached partition tables for slot counts `0..=n_dirs`.
442 fn partition_tables(n_dirs: usize) -> Vec<std::rc::Rc<PartTable>> {
443 PARTITION_TABLES.with(|cell| {
444 let mut tables = cell.borrow_mut();
445 while tables.len() <= n_dirs {
446 let m = tables.len();
447 tables.push(std::rc::Rc::new(build_partitions(m)));
448 }
449 (0..=n_dirs).map(|m| std::rc::Rc::clone(&tables[m])).collect()
450 })
451 }
452
453 /// The previous production `compose_unary`: a direct set-partition (Faà di
454 /// Bruno) sum per output mask, retained as the accuracy reference.
455 fn compose_unary_partition_reference(coeffs: &[f64], derivs: [f64; DERIVS]) -> Vec<f64> {
456 let count = coeffs.len();
457 let n_dirs = count.trailing_zeros() as usize;
458 let tables = partition_tables(n_dirs);
459 let mut out = vec![0.0; count];
460 let mut remap = vec![0usize; count];
461 let mut pos = [0usize; usize::BITS as usize];
462 for (mask, slot) in out.iter_mut().enumerate() {
463 if mask == 0 {
464 *slot = derivs[0];
465 continue;
466 }
467 let mut npos = 0usize;
468 let mut m = mask;
469 while m != 0 {
470 pos[npos] = m.trailing_zeros() as usize;
471 npos += 1;
472 m &= m - 1;
473 }
474 remap[0] = 0;
475 for cb in 1usize..(1usize << npos) {
476 let low = cb.trailing_zeros() as usize;
477 remap[cb] = remap[cb & (cb - 1)] | (1usize << pos[low]);
478 }
479 let table = &tables[npos];
480 let flat = &table.flat;
481 let mut total = 0.0;
482 for &(off, order) in table.parts.iter() {
483 let order = order as usize;
484 let mut prod = derivs[order];
485 for &cb in &flat[off..off + order] {
486 prod *= coeffs[remap[cb as usize]];
487 }
488 total += prod;
489 }
490 *slot = total;
491 }
492 out
493 }
494
495 /// Enumerate the set-partitions of `{0..m}` with fewer than `DERIVS` blocks, in
496 /// the exact DFS order of [`crate::jet_algebra`]'s `for_each_partition`
497 /// recursion ("place each element into an existing block, else open a new one"),
498 /// each block recorded as a compacted submask of `{0..m}`, flattened.
499 fn build_partitions(m: usize) -> PartTable {
500 fn recurse(elem: usize, m: usize, blocks: &mut [u32; 8], n_blocks: usize, out: &mut PartTable) {
501 // Partitions with `>= DERIVS` blocks are truncated (their `f^{(order)}`
502 // is beyond the stack); the block count never decreases, so the whole
503 // subtree contributes nothing and is pruned — matching the walker's
504 // per-partition `order >= derivs.len()` skip.
505 if n_blocks >= DERIVS {
506 return;
507 }
508 if elem == m {
509 let off = out.flat.len();
510 out.flat.extend_from_slice(&blocks[..n_blocks]);
511 out.parts.push((off, n_blocks as u8));
512 return;
513 }
514 for b in 0..n_blocks {
515 blocks[b] |= 1u32 << elem;
516 recurse(elem + 1, m, blocks, n_blocks, out);
517 blocks[b] &= !(1u32 << elem);
518 }
519 blocks[n_blocks] = 1u32 << elem;
520 recurse(elem + 1, m, blocks, n_blocks + 1, out);
521 }
522 let mut out = PartTable {
523 flat: Vec::new(),
524 parts: Vec::new(),
525 };
526 let mut blocks = [0u32; 8];
527 recurse(0, m, &mut blocks, 0, &mut out);
528 out
529 }
530
531 // ── constructors ─────────────────────────────────────────────────────────
532
533 #[test]
534 fn zero_has_correct_length_and_all_zero_coefficients() {
535 let j = MultiDirJet::zero(3);
536 assert_eq!(j.coeffs.len(), 8);
537 assert!(j.coeffs.iter().all(|&v| v == 0.0));
538 }
539
540 #[test]
541 fn constant_has_value_at_mask_zero_and_zeros_elsewhere() {
542 let j = MultiDirJet::constant(2, 5.0);
543 assert_eq!(j.coeffs.len(), 4);
544 assert_eq!(j.coeff(0), 5.0);
545 assert_eq!(j.coeff(1), 0.0);
546 assert_eq!(j.coeff(2), 0.0);
547 assert_eq!(j.coeff(3), 0.0);
548 }
549
550 #[test]
551 fn linear_sets_base_and_per_direction_slots() {
552 let j = MultiDirJet::linear(2, 1.0, &[2.0, 3.0]);
553 assert_eq!(j.coeff(0), 1.0); // constant
554 assert_eq!(j.coeff(1), 2.0); // mask 0b01 — direction 0
555 assert_eq!(j.coeff(2), 3.0); // mask 0b10 — direction 1
556 assert_eq!(j.coeff(3), 0.0); // cross term is zero
557 }
558
559 #[test]
560 fn bilinear_sets_all_four_slots() {
561 let j = MultiDirJet::bilinear(1.0, 2.0, 3.0, 4.0);
562 assert_eq!(j.coeff(0), 1.0);
563 assert_eq!(j.coeff(1), 2.0);
564 assert_eq!(j.coeff(2), 3.0);
565 assert_eq!(j.coeff(3), 4.0);
566 }
567
568 #[test]
569 fn with_coeffs_sets_only_specified_entries() {
570 let j = MultiDirJet::with_coeffs(2, &[(0, 9.0), (3, -1.0)]);
571 assert_eq!(j.coeff(0), 9.0);
572 assert_eq!(j.coeff(1), 0.0);
573 assert_eq!(j.coeff(2), 0.0);
574 assert_eq!(j.coeff(3), -1.0);
575 }
576
577 // ── elementwise arithmetic ────────────────────────────────────────────────
578
579 #[test]
580 fn add_is_elementwise() {
581 let a = MultiDirJet::linear(2, 1.0, &[2.0, 3.0]);
582 let b = MultiDirJet::linear(2, 4.0, &[5.0, 6.0]);
583 let c = a.add(&b);
584 assert_eq!(c.coeff(0), 5.0);
585 assert_eq!(c.coeff(1), 7.0);
586 assert_eq!(c.coeff(2), 9.0);
587 assert_eq!(c.coeff(3), 0.0);
588 }
589
590 #[test]
591 fn scale_multiplies_all_coefficients() {
592 let j = MultiDirJet::linear(2, 1.0, &[2.0, 3.0]);
593 let s = j.scale(2.0);
594 assert_eq!(s.coeff(0), 2.0);
595 assert_eq!(s.coeff(1), 4.0);
596 assert_eq!(s.coeff(2), 6.0);
597 assert_eq!(s.coeff(3), 0.0);
598 }
599
600 #[test]
601 fn sub_is_elementwise_difference() {
602 let a = MultiDirJet::constant(2, 5.0);
603 let b = MultiDirJet::constant(2, 3.0);
604 let c = a.sub(&b);
605 assert_eq!(c.coeff(0), 2.0);
606 assert_eq!(c.coeff(1), 0.0);
607 assert_eq!(c.coeff(2), 0.0);
608 assert_eq!(c.coeff(3), 0.0);
609 }
610
611 // ── mul (subset-convolution) ──────────────────────────────────────────────
612
613 #[test]
614 fn mul_of_constants_is_scalar_product() {
615 let a = MultiDirJet::constant(2, 2.0);
616 let b = MultiDirJet::constant(2, 3.0);
617 let c = a.mul(&b);
618 assert_eq!(c.coeff(0), 6.0);
619 assert_eq!(c.coeff(1), 0.0);
620 assert_eq!(c.coeff(2), 0.0);
621 assert_eq!(c.coeff(3), 0.0);
622 }
623
624 #[test]
625 fn mul_satisfies_leibniz_rule_single_direction() {
626 // (1 + ε) * (1 + ε) = 1 + 2ε
627 let x = MultiDirJet::linear(1, 1.0, &[1.0]);
628 let y = MultiDirJet::linear(1, 1.0, &[1.0]);
629 let z = x.mul(&y);
630 assert_eq!(z.coeff(0), 1.0);
631 assert_eq!(z.coeff(1), 2.0);
632 }
633
634 #[test]
635 fn mul_cross_term_two_independent_directions() {
636 // (1 + ε₁)(1 + ε₂) = 1 + ε₁ + ε₂ + ε₁ε₂
637 let x = MultiDirJet::linear(2, 1.0, &[1.0, 0.0]);
638 let y = MultiDirJet::linear(2, 1.0, &[0.0, 1.0]);
639 let z = x.mul(&y);
640 assert_eq!(z.coeff(0), 1.0);
641 assert_eq!(z.coeff(1), 1.0);
642 assert_eq!(z.coeff(2), 1.0);
643 assert_eq!(z.coeff(3), 1.0);
644 }
645
646 // ── compose_unary: truncated-Taylor reassociation ─────────────────────────
647 //
648 // The new `compose_unary` reassociates the per-mask Faà di Bruno set-partition
649 // sum into a degree-4 polynomial in the subset-convolution power of the
650 // non-constant part. These tests are the accuracy gate: a double-double
651 // oracle is the truth, and the new path's error-vs-truth must be `≤` the old
652 // naive partition sum's error-vs-truth on every randomised program.
653
654 /// Deterministic xorshift64* — no `rand` dependency in the test.
655 struct Rng(u64);
656 impl Rng {
657 fn next_u64(&mut self) -> u64 {
658 let mut x = self.0;
659 x ^= x >> 12;
660 x ^= x << 25;
661 x ^= x >> 27;
662 self.0 = x;
663 x.wrapping_mul(0x2545F4914F6CDD1D)
664 }
665 /// Uniform in `[-scale, scale]`.
666 fn signed(&mut self, scale: f64) -> f64 {
667 let u = (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64; // [0,1)
668 (2.0 * u - 1.0) * scale
669 }
670 }
671
672 // ── A double-double oracle for the exact (order-4 truncated) composition ──
673
674 #[inline]
675 fn two_prod(a: f64, b: f64) -> (f64, f64) {
676 let p = a * b;
677 (p, a.mul_add(b, -p))
678 }
679 #[inline]
680 fn dd_two_sum(a: f64, b: f64) -> (f64, f64) {
681 let s = a + b;
682 let bb = s - a;
683 (s, (a - (s - bb)) + (b - bb))
684 }
685 #[derive(Clone, Copy)]
686 struct Dd {
687 hi: f64,
688 lo: f64,
689 }
690 impl Dd {
691 fn from(x: f64) -> Self {
692 Self { hi: x, lo: 0.0 }
693 }
694 fn mul_f64(self, b: f64) -> Self {
695 let (p, e) = two_prod(self.hi, b);
696 let lo = self.lo.mul_add(b, e);
697 let s = p + lo;
698 Self {
699 hi: s,
700 lo: (p - s) + lo,
701 }
702 }
703 fn add(self, o: Self) -> Self {
704 let (s, e) = dd_two_sum(self.hi, o.hi);
705 let (s2, e2) = dd_two_sum(self.lo, o.lo);
706 let lo = e + s2;
707 let h1 = s + lo;
708 let l1 = (s - h1) + lo;
709 let lo2 = l1 + e2;
710 let h = h1 + lo2;
711 Self {
712 hi: h,
713 lo: (h1 - h) + lo2,
714 }
715 }
716 /// `|self - x|` to ~double precision in the residual (Sterbenz: `x` and
717 /// `hi` agree to ~53 bits, so `x - hi` is essentially exact).
718 fn abs_err_to(self, x: f64) -> f64 {
719 ((x - self.hi) - self.lo).abs()
720 }
721 }
722
723 /// High-precision truth for `compose_unary` via the set-partition reference,
724 /// every product and sum carried in double-double.
725 fn compose_truth(coeffs: &[f64], derivs: [f64; DERIVS]) -> Vec<Dd> {
726 let count = coeffs.len();
727 let n_dirs = count.trailing_zeros() as usize;
728 let tables = partition_tables(n_dirs);
729 let mut out = vec![Dd::from(0.0); count];
730 let mut remap = vec![0usize; count];
731 let mut pos = [0usize; 64];
732 for (mask, slot) in out.iter_mut().enumerate() {
733 if mask == 0 {
734 *slot = Dd::from(derivs[0]);
735 continue;
736 }
737 let mut npos = 0usize;
738 let mut m = mask;
739 while m != 0 {
740 pos[npos] = m.trailing_zeros() as usize;
741 npos += 1;
742 m &= m - 1;
743 }
744 remap[0] = 0;
745 for cb in 1usize..(1usize << npos) {
746 let low = cb.trailing_zeros() as usize;
747 remap[cb] = remap[cb & (cb - 1)] | (1usize << pos[low]);
748 }
749 let table = &tables[npos];
750 let mut total = Dd::from(0.0);
751 for &(off, order) in table.parts.iter() {
752 let order = order as usize;
753 let mut prod = Dd::from(derivs[order]);
754 for &cb in &table.flat[off..off + order] {
755 prod = prod.mul_f64(coeffs[remap[cb as usize]]);
756 }
757 total = total.add(prod);
758 }
759 *slot = total;
760 }
761 out
762 }
763
764 /// Build a random composite jet so the composition input is a realistic
765 /// non-trivial multilinear element (not just seeded directions).
766 fn random_inner(n_dirs: usize, rng: &mut Rng) -> MultiDirJet {
767 let base = rng.signed(0.8);
768 let first: Vec<f64> = (0..n_dirs).map(|_| rng.signed(0.6)).collect();
769 let a = MultiDirJet::linear(n_dirs, base, &first);
770 let b = MultiDirJet::linear(
771 n_dirs,
772 rng.signed(0.7),
773 &(0..n_dirs).map(|_| rng.signed(0.5)).collect::<Vec<_>>(),
774 );
775 // a*b + a populates the full cross-mask spectrum.
776 a.mul(&b).add(&a)
777 }
778
779 #[test]
780 fn compose_unary_matches_partition_reference_simple() {
781 // exp-like stack on a 2-direction cross jet: every coeff agrees with the
782 // direct set-partition reference to a tight tolerance.
783 let j = MultiDirJet::linear(2, 0.3, &[0.5, -0.4])
784 .mul(&MultiDirJet::linear(2, -0.2, &[0.1, 0.7]));
785 let d = [0.9_f64, 1.1, -0.7, 0.4, -0.25];
786 let got = j.compose_unary(d);
787 let want = compose_unary_partition_reference(&j.coeffs, d);
788 for (mask, (&g, &w)) in got.coeffs.iter().zip(want.iter()).enumerate() {
789 let tol = 1e-13 * w.abs().max(1.0);
790 assert!(
791 (g - w).abs() <= tol,
792 "mask {mask}: got={g:.17e} want={w:.17e}"
793 );
794 }
795 }
796
797 #[test]
798 fn compose_unary_accuracy_beats_partition_sum_vs_double_double() {
799 // The accuracy gate. Over many random programs at every K used in
800 // production, the new path's error-vs-truth is never worse than the old
801 // naive partition sum's, and is a strict improvement in aggregate.
802 let mut rng = Rng(0x1234_5678_9abc_def0);
803 let mut sum_new = 0.0f64;
804 let mut sum_old = 0.0f64;
805 for &n_dirs in &[2usize, 3, 4, 6, 8] {
806 for _ in 0..200 {
807 let inner = random_inner(n_dirs, &mut rng);
808 let d = [
809 rng.signed(1.5),
810 rng.signed(1.5),
811 rng.signed(2.0),
812 rng.signed(3.0),
813 rng.signed(4.0),
814 ];
815 let new = inner.compose_unary(d);
816 let old = compose_unary_partition_reference(&inner.coeffs, d);
817 let truth = compose_truth(&inner.coeffs, d);
818 for mask in 0..inner.coeffs.len() {
819 let en = truth[mask].abs_err_to(new.coeffs[mask]);
820 let eo = truth[mask].abs_err_to(old[mask]);
821 sum_new += en;
822 sum_old += eo;
823 // Per-coefficient: new is never materially worse. The 4 ULP
824 // slack absorbs the rare tie where a differently-grouped but
825 // equally-valid rounding lands one ULP either way.
826 let scale = truth[mask].hi.abs().max(1.0);
827 assert!(
828 en <= eo + 4.0 * f64::EPSILON * scale,
829 "K={n_dirs} mask={mask}: new_err={en:.3e} old_err={eo:.3e}"
830 );
831 }
832 }
833 }
834 // Aggregate: the compensated reassociation is a real improvement.
835 assert!(
836 sum_new <= sum_old,
837 "aggregate error regressed: new={sum_new:.6e} old={sum_old:.6e}"
838 );
839 eprintln!(
840 "compose_unary accuracy: total |err| new={sum_new:.6e} old={sum_old:.6e} \
841 (improvement {:.2}x)",
842 sum_old / sum_new.max(f64::MIN_POSITIVE)
843 );
844 }
845
846 #[test]
847 fn compose_unary_speedup_over_partition_sum() {
848 // Measure ns/call new vs. the previous partition-sum implementation
849 // across the production K range. Prints the multiple; asserts a
850 // conservative floor so CI noise can't make it flaky.
851 use std::time::Instant;
852 let mut rng = Rng(0xfeed_face_dead_beef);
853 for &n_dirs in &[2usize, 4, 6, 8] {
854 let n_inputs = 256usize;
855 let inputs: Vec<(MultiDirJet, [f64; DERIVS])> = (0..n_inputs)
856 .map(|_| {
857 (
858 random_inner(n_dirs, &mut rng),
859 [
860 rng.signed(1.5),
861 rng.signed(1.5),
862 rng.signed(2.0),
863 rng.signed(3.0),
864 rng.signed(4.0),
865 ],
866 )
867 })
868 .collect();
869 let iters = 200usize;
870 // Warm the scratch / partition tables.
871 for (j, d) in &inputs {
872 std::hint::black_box(j.compose_unary(*d));
873 std::hint::black_box(compose_unary_partition_reference(&j.coeffs, *d));
874 }
875 let t0 = Instant::now();
876 for _ in 0..iters {
877 for (j, d) in &inputs {
878 std::hint::black_box(j.compose_unary(*d));
879 }
880 }
881 let new_ns = t0.elapsed().as_nanos() as f64 / (iters * inputs.len()) as f64;
882 let t1 = Instant::now();
883 for _ in 0..iters {
884 for (j, d) in &inputs {
885 std::hint::black_box(compose_unary_partition_reference(&j.coeffs, *d));
886 }
887 }
888 let old_ns = t1.elapsed().as_nanos() as f64 / (iters * inputs.len()) as f64;
889 eprintln!(
890 "compose_unary K={n_dirs}: new={new_ns:.1} ns/call old={old_ns:.1} ns/call \
891 speedup={:.2}x",
892 old_ns / new_ns
893 );
894 // Guard only where the algorithmic win is robust: an optimised build
895 // at the production-dominant K (the partition sum's `Σ_π |π|` work
896 // grows steeply with K, while the new path is three convolutions).
897 // Debug builds and tiny K are dominated by fixed per-call overhead
898 // and the ratio there is not a meaningful guard, so it is printed
899 // but not asserted (and timing asserts must not flake on CI).
900 if !cfg!(debug_assertions) && n_dirs >= 6 {
901 assert!(
902 new_ns < old_ns,
903 "K={n_dirs} new path slower: new={new_ns:.1}ns old={old_ns:.1}ns"
904 );
905 }
906 }
907 }
908}