fenwick-mmd 0.2.0

Formally verified, sub-quadratic minimax-optimal kernel two-sample testing (MMD) via compressed multidimensional Fenwick trees and orthantwise separable kernels
Documentation
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Compressed multidimensional Fenwick tree (Binary Indexed Tree)
//!
//! Implements Algorithms 4, 5, and 6 (`BuildTree`, `T.update`, `T.query`) from
//! Choi, Pandey, & Sarkar (2026), Appendix E.4 (arXiv:2612.05470).
//!
//! Memory complexity for $N$ points in $k$ dimensions: $O(N \log^{k-1} N)$.
//! Query and update time complexity: $O(\log^k N)$.
//!
//! Supports zero-allocation `reset()` for fast reuse across permutation sweeps.

/// Lowest set bit of a positive 1-based Fenwick index: `lowbit(t) = t & (!t + 1)`.
#[inline]
pub fn lowbit(t: usize) -> usize {
    debug_assert!(t >= 1);
    t & t.wrapping_neg()
}

/// Compressed $k$-dimensional Fenwick tree node over integer rank coordinates.
#[derive(Debug, Clone)]
pub enum CompressedFenwick {
    Empty,
    Singleton {
        point: Vec<usize>,
        value: f64,
    },
    Leaf1D {
        coords: Vec<usize>,
        /// 1-indexed Fenwick array of length `coords.len() + 1` (slot 0 unused).
        bit: Vec<f64>,
    },
    Branch {
        coords: Vec<usize>,
        /// 1-indexed child trees of length `coords.len() + 1` (slot 0 unused).
        children: Vec<Option<CompressedFenwick>>,
    },
}

impl CompressedFenwick {
    /// Build a compressed `k`-dimensional Fenwick tree over the given possible update locations.
    ///
    /// Every element of `points` must have length `k >= 1`.
    pub fn build(points: &[Vec<usize>], k: usize) -> Self {
        assert!(k >= 1, "CompressedFenwick dimension k must be >= 1");
        if points.is_empty() {
            return Self::Empty;
        }

        let mut unique: Vec<&[usize]> = points.iter().map(Vec::as_slice).collect();
        unique.sort_unstable();
        unique.dedup();

        Self::build_from_unique(&unique, k)
    }

    fn build_from_unique(unique: &[&[usize]], k: usize) -> Self {
        if unique.is_empty() {
            return Self::Empty;
        }
        if unique.len() == 1 {
            return Self::Singleton {
                point: unique[0].to_vec(),
                value: 0.0,
            };
        }

        // Extract sorted unique first coordinates.
        // Because `unique` is already lexicographically sorted, first coordinates are non-decreasing.
        let mut coords: Vec<usize> = Vec::with_capacity(unique.len());
        for p in unique {
            let x1 = p[0];
            if coords.last().copied() != Some(x1) {
                coords.push(x1);
            }
        }
        let m = coords.len();

        if k == 1 {
            return Self::Leaf1D {
                coords,
                bit: vec![0.0; m + 1],
            };
        }

        let mut buckets: Vec<Vec<&[usize]>> = vec![Vec::new(); m + 1];
        for p in unique {
            let a = coords
                .binary_search(&p[0])
                .expect("point coordinate must exist in coords")
                + 1;
            let tail = &p[1..];
            let mut q = a;
            while q <= m {
                buckets[q].push(tail);
                q += lowbit(q);
            }
        }

        let mut children: Vec<Option<CompressedFenwick>> = Vec::with_capacity(m + 1);
        children.push(None); // 0-th slot unused (1-indexed)
        for bucket in buckets.iter_mut().skip(1) {
            if bucket.is_empty() {
                children.push(None);
            } else {
                bucket.sort_unstable();
                bucket.dedup();
                children.push(Some(Self::build_from_unique(bucket, k - 1)));
            }
        }

        Self::Branch { coords, children }
    }

    /// Zero all accumulated values in-place without reallocating tree structure.
    pub fn reset(&mut self) {
        match self {
            Self::Empty => {}
            Self::Singleton { value, .. } => {
                *value = 0.0;
            }
            Self::Leaf1D { bit, .. } => {
                bit.fill(0.0);
            }
            Self::Branch { children, .. } => {
                for child in children.iter_mut().flatten() {
                    child.reset();
                }
            }
        }
    }

    /// Add `val` at location `point` (must be in the tree's built geometry).
    pub fn update(&mut self, point: &[usize], val: f64) {
        match self {
            Self::Empty => unreachable!("update called on empty CompressedFenwick"),
            Self::Singleton { point: pt, value } => {
                debug_assert_eq!(pt.as_slice(), point);
                *value += val;
            }
            Self::Leaf1D { coords, bit } => {
                let a = coords
                    .binary_search(&point[0])
                    .expect("update coordinate not in compressed tree")
                    + 1;
                let m = coords.len();
                let mut q = a;
                while q <= m {
                    bit[q] += val;
                    q += lowbit(q);
                }
            }
            Self::Branch { coords, children } => {
                let a = coords
                    .binary_search(&point[0])
                    .expect("update coordinate not in compressed tree")
                    + 1;
                let m = coords.len();
                let tail = &point[1..];
                let mut q = a;
                while q <= m {
                    if let Some(child) = children[q].as_mut() {
                        child.update(tail, val);
                    }
                    q += lowbit(q);
                }
            }
        }
    }

    /// Query the sum of all values at locations `p` satisfying `p[l] <= bound[l]` for all `l`.
    pub fn query(&self, bound: &[usize]) -> f64 {
        match self {
            Self::Empty => 0.0,
            Self::Singleton { point, value } => {
                if point.iter().zip(bound.iter()).all(|(&p, &b)| p <= b) {
                    *value
                } else {
                    0.0
                }
            }
            Self::Leaf1D { coords, bit } => {
                let a = coords.partition_point(|&c| c <= bound[0]);
                if a == 0 {
                    return 0.0;
                }
                let mut ans = 0.0;
                let mut q = a;
                while q > 0 {
                    ans += bit[q];
                    q -= lowbit(q);
                }
                ans
            }
            Self::Branch { coords, children } => {
                let a = coords.partition_point(|&c| c <= bound[0]);
                if a == 0 {
                    return 0.0;
                }
                let tail_bound = &bound[1..];
                let mut ans = 0.0;
                let mut q = a;
                while q > 0 {
                    if let Some(child) = children[q].as_ref() {
                        ans += child.query(tail_bound);
                    }
                    q -= lowbit(q);
                }
                ans
            }
        }
    }
}

/// Multi-channel compressed $k$-dimensional Fenwick tree storing `channels` contiguous
/// `f64` values per node.
///
/// Traverses the tree structure (binary searches + Fenwick index hops) **once** per
/// update/query while accumulating all `channels` simultaneously in tight contiguous
/// slices. Inspired by the multi-channel Fenwick topology note in Choi, Pandey, &
/// Sarkar (2026) (`arXiv:2612.05470`).
#[derive(Debug, Clone)]
pub enum MultiChannelFenwick {
    Empty,
    Singleton {
        point: Vec<usize>,
        values: Vec<f64>,
    },
    Leaf1D {
        coords: Vec<usize>,
        channels: usize,
        /// Flat 1-indexed Fenwick array of length `(coords.len() + 1) * channels`.
        bit: Vec<f64>,
    },
    Branch {
        coords: Vec<usize>,
        children: Vec<Option<MultiChannelFenwick>>,
    },
}

impl MultiChannelFenwick {
    /// Build a multi-channel compressed `k`-dimensional Fenwick tree over `points`.
    pub fn build(points: &[Vec<usize>], k: usize, channels: usize) -> Self {
        assert!(k >= 1, "MultiChannelFenwick dimension k must be >= 1");
        assert!(channels >= 1, "MultiChannelFenwick channels must be >= 1");
        if points.is_empty() {
            return Self::Empty;
        }

        let mut unique: Vec<&[usize]> = points.iter().map(Vec::as_slice).collect();
        unique.sort_unstable();
        unique.dedup();

        Self::build_from_unique(&unique, k, channels)
    }

    fn build_from_unique(unique: &[&[usize]], k: usize, channels: usize) -> Self {
        if unique.is_empty() {
            return Self::Empty;
        }
        if unique.len() == 1 {
            return Self::Singleton {
                point: unique[0].to_vec(),
                values: vec![0.0; channels],
            };
        }

        let mut coords: Vec<usize> = Vec::with_capacity(unique.len());
        for p in unique {
            let x1 = p[0];
            if coords.last().copied() != Some(x1) {
                coords.push(x1);
            }
        }
        let m = coords.len();

        if k == 1 {
            return Self::Leaf1D {
                coords,
                channels,
                bit: vec![0.0; (m + 1) * channels],
            };
        }

        let mut buckets: Vec<Vec<&[usize]>> = vec![Vec::new(); m + 1];
        for p in unique {
            let a = coords
                .binary_search(&p[0])
                .expect("point coordinate must exist in coords")
                + 1;
            let tail = &p[1..];
            let mut q = a;
            while q <= m {
                buckets[q].push(tail);
                q += lowbit(q);
            }
        }

        let mut children: Vec<Option<MultiChannelFenwick>> = Vec::with_capacity(m + 1);
        children.push(None);
        for bucket in buckets.iter_mut().skip(1) {
            if bucket.is_empty() {
                children.push(None);
            } else {
                bucket.sort_unstable();
                bucket.dedup();
                children.push(Some(Self::build_from_unique(bucket, k - 1, channels)));
            }
        }

        Self::Branch { coords, children }
    }

    /// Zero all channels across all nodes in-place without reallocating.
    pub fn reset(&mut self) {
        match self {
            Self::Empty => {}
            Self::Singleton { values, .. } => values.fill(0.0),
            Self::Leaf1D { bit, .. } => bit.fill(0.0),
            Self::Branch { children, .. } => {
                for child in children.iter_mut().flatten() {
                    child.reset();
                }
            }
        }
    }

    /// Add `vals` (length `channels`) at location `point` in a single tree traversal.
    pub fn update(&mut self, point: &[usize], vals: &[f64]) {
        match self {
            Self::Empty => unreachable!("update called on empty MultiChannelFenwick"),
            Self::Singleton { point: pt, values } => {
                debug_assert_eq!(pt.as_slice(), point);
                for (dst, &v) in values.iter_mut().zip(vals.iter()) {
                    *dst += v;
                }
            }
            Self::Leaf1D {
                coords,
                channels,
                bit,
            } => {
                let c = *channels;
                let a = coords
                    .binary_search(&point[0])
                    .expect("update coordinate not in compressed tree")
                    + 1;
                let m = coords.len();
                let mut q = a;
                while q <= m {
                    let base = q * c;
                    let slot = &mut bit[base..base + c];
                    for (dst, &v) in slot.iter_mut().zip(vals.iter()) {
                        *dst += v;
                    }
                    q += lowbit(q);
                }
            }
            Self::Branch { coords, children } => {
                let a = coords
                    .binary_search(&point[0])
                    .expect("update coordinate not in compressed tree")
                    + 1;
                let m = coords.len();
                let tail = &point[1..];
                let mut q = a;
                while q <= m {
                    if let Some(child) = children[q].as_mut() {
                        child.update(tail, vals);
                    }
                    q += lowbit(q);
                }
            }
        }
    }

    /// Accumulate the box-prefix sum for `p <= bound` into `out` (length `channels`)
    /// in a single tree traversal. Caller must zero `out` before the top-level call.
    pub fn query_add(&self, bound: &[usize], out: &mut [f64]) {
        match self {
            Self::Empty => {}
            Self::Singleton { point, values } => {
                if point.iter().zip(bound.iter()).all(|(&p, &b)| p <= b) {
                    for (dst, &v) in out.iter_mut().zip(values.iter()) {
                        *dst += v;
                    }
                }
            }
            Self::Leaf1D {
                coords,
                channels,
                bit,
            } => {
                let a = coords.partition_point(|&c| c <= bound[0]);
                if a == 0 {
                    return;
                }
                let c = *channels;
                let mut q = a;
                while q > 0 {
                    let base = q * c;
                    let slot = &bit[base..base + c];
                    for (dst, &v) in out.iter_mut().zip(slot.iter()) {
                        *dst += v;
                    }
                    q -= lowbit(q);
                }
            }
            Self::Branch { coords, children } => {
                let a = coords.partition_point(|&c| c <= bound[0]);
                if a == 0 {
                    return;
                }
                let tail_bound = &bound[1..];
                let mut q = a;
                while q > 0 {
                    if let Some(child) = children[q].as_ref() {
                        child.query_add(tail_bound, out);
                    }
                    q -= lowbit(q);
                }
            }
        }
    }
}