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
//! Characteristic 1D and product kernels with Piecewise Separable (PS) and
//! Almost Piecewise Separable (APS) decompositions.
//!
//! Reference: Choi, Pandey, & Sarkar (2026), Section 3.3-3.4 & Appendix C (arXiv:2612.05470).
//!
//! Supported 1D kernels (all unit-peak $k(x, x) = 1$):
//! - `Laplace`:   $k(x, y) = \exp(-|x - y| / \lambda)$, exact $(1, 0)$-PS.
//! - `Matern32`:  $k(x, y) = (1 + \sqrt{3} r) \exp(-\sqrt{3} r)$, $r = |x - y| / \lambda$, exact $(2, 0)$-PS.
//! - `Matern52`:  $k(x, y) = (1 + \sqrt{5} r + \frac{5}{3} r^2) \exp(-\sqrt{5} r)$, exact $(3, 0)$-PS.
//! - `Gaussian`:  $k(x, y) = \exp(-(x - y)^2 / \lambda^2)$, $(2L + 1, \delta)$-APS via the
//!   exponentially convergent trapezoidal rule (Lemma 2 & Lemma 3 of arXiv:2612.05470).

use std::f64::consts::PI;

/// A single piecewise separable (PS) 1D kernel component:
/// `k(x, y) = f_minus(x) * g_minus(y)` for `y <= x`, and
/// `k(x, y) = f_plus(x) * g_plus(y)` for `y > x`.
#[derive(Debug, Clone)]
pub enum PsTerm1D {
    /// `coeff * exp(-alpha * |x - y|)` with polynomial powers:
    /// For `y <= x`: `f_minus(x) = exp(-alpha * x) * poly_minus(x)`, `g_minus(y) = exp(alpha * y) * y^pow`
    /// For `y > x`:  `f_plus(x)  = exp(alpha * x) * (-x)^pow`,       `g_plus(y)  = exp(-alpha * y) * poly_plus(y)`
    ExponentialPoly {
        alpha: f64,
        /// Polynomial coefficients `c[k]` for `sum_k c[k] x^k` on `f_minus(x)` (y <= x).
        poly_minus: [f64; 3],
        /// Polynomial coefficients `d[k]` for `sum_k d[k] y^k` on `g_plus(y)` (y > x).
        poly_plus: [f64; 3],
        /// Power `ell` on `y^ell` (for `g_minus`) and `(-x)^ell` (for `f_plus`).
        power: u8,
    },
    /// Cosine term from Gaussian trapezoidal expansion (Eq. in Appendix C.2):
    /// `A_j * exp(-2 a |x - y|) * cos(2 u_j (a - |x - y|))` split into cos-part and sin-part.
    GaussianCos {
        two_a: f64,
        two_u: f64,
        two_u_a: f64,
        amp: f64,
    },
    GaussianSin {
        two_a: f64,
        two_u: f64,
        two_u_a: f64,
        amp: f64,
    },
}

impl PsTerm1D {
    #[inline]
    fn eval_poly(c: &[f64; 3], x: f64) -> f64 {
        c[0] + x * (c[1] + x * c[2])
    }

    #[inline]
    fn pow_u8(x: f64, p: u8) -> f64 {
        match p {
            0 => 1.0,
            1 => x,
            2 => x * x,
            _ => x.powi(p as i32),
        }
    }

    /// Evaluate `(f_minus(x), g_minus(x))` for the `y <= x` (`s = -`) branch.
    #[inline]
    pub fn eval_minus(&self, x: f64) -> (f64, f64) {
        match *self {
            Self::ExponentialPoly {
                alpha,
                poly_minus,
                power,
                ..
            } => {
                let em = (-alpha * x).exp();
                let ep = (alpha * x).exp();
                (em * Self::eval_poly(&poly_minus, x), ep * Self::pow_u8(x, power))
            }
            Self::GaussianCos {
                two_a,
                two_u,
                two_u_a,
                amp,
            } => {
                let em = (-two_a * x).exp();
                let ep = (two_a * x).exp();
                let f = amp * em * (two_u_a - two_u * x).cos();
                let g = ep * (two_u * x).cos();
                (f, g)
            }
            Self::GaussianSin {
                two_a,
                two_u,
                two_u_a,
                amp,
            } => {
                let em = (-two_a * x).exp();
                let ep = (two_a * x).exp();
                let f = -amp * em * (two_u_a - two_u * x).sin();
                let g = ep * (two_u * x).sin();
                (f, g)
            }
        }
    }

    /// Evaluate `(f_plus(x), g_plus(x))` for the `y > x` (`s = +`) branch.
    #[inline]
    pub fn eval_plus(&self, x: f64) -> (f64, f64) {
        match *self {
            Self::ExponentialPoly {
                alpha,
                poly_plus,
                power,
                ..
            } => {
                let ep = (alpha * x).exp();
                let em = (-alpha * x).exp();
                (ep * Self::pow_u8(-x, power), em * Self::eval_poly(&poly_plus, x))
            }
            Self::GaussianCos {
                two_a,
                two_u,
                two_u_a,
                amp,
            } => {
                let ep = (two_a * x).exp();
                let em = (-two_a * x).exp();
                let f = amp * ep * (two_u_a + two_u * x).cos();
                let g = em * (two_u * x).cos();
                (f, g)
            }
            Self::GaussianSin {
                two_a,
                two_u,
                two_u_a,
                amp,
            } => {
                let ep = (two_a * x).exp();
                let em = (-two_a * x).exp();
                let f = amp * ep * (two_u_a + two_u * x).sin();
                let g = em * (two_u * x).sin();
                (f, g)
            }
        }
    }

    /// Maximum exponential rate `alpha` (used for overflow safety check).
    #[inline]
    pub fn exp_rate(&self) -> f64 {
        match *self {
            Self::ExponentialPoly { alpha, .. } => alpha,
            Self::GaussianCos { two_a, .. } | Self::GaussianSin { two_a, .. } => two_a,
        }
    }
}

/// 1D characteristic kernel specification.
#[derive(Debug, Clone)]
pub enum Kernel1D {
    /// $k(x, y) = \exp(-|x - y| / \lambda)$ (exact $(1, 0)$-PS).
    Laplace { bandwidth: f64 },
    /// $k(x, y) = (1 + \sqrt{3} r) \exp(-\sqrt{3} r)$, $r = |x - y| / \lambda$ (exact $(2, 0)$-PS).
    Matern32 { bandwidth: f64 },
    /// $k(x, y) = (1 + \sqrt{5} r + \frac{5}{3} r^2) \exp(-\sqrt{5} r)$, $r = |x - y| / \lambda$ (exact $(3, 0)$-PS).
    Matern52 { bandwidth: f64 },
    /// $k(x, y) = \exp(-(x - y)^2 / \lambda^2)$ approximated via trapezoidal rule (Lemma 3).
    /// `tol` controls uniform pointwise error $\delta \le \text{tol}$ (default `1e-4`).
    Gaussian { bandwidth: f64, tol: f64 },
}

impl Kernel1D {
    pub fn bandwidth(&self) -> f64 {
        match *self {
            Self::Laplace { bandwidth }
            | Self::Matern32 { bandwidth }
            | Self::Matern52 { bandwidth }
            | Self::Gaussian { bandwidth, .. } => bandwidth,
        }
    }

    /// Exact pointwise 1D kernel evaluation `k(x, y)`.
    #[inline]
    pub fn eval_exact(&self, x: f64, y: f64) -> f64 {
        let r = (x - y).abs() / self.bandwidth();
        match *self {
            Self::Laplace { .. } => (-r).exp(),
            Self::Matern32 { .. } => {
                let t = 3.0_f64.sqrt() * r;
                (1.0 + t) * (-t).exp()
            }
            Self::Matern52 { .. } => {
                let t = 5.0_f64.sqrt() * r;
                (1.0 + t + t * t / 3.0) * (-t).exp()
            }
            Self::Gaussian { .. } => (-r * r).exp(),
        }
    }

    /// Theoretical uniform 1D APS error bound $\delta_i$ (0.0 for exact PS kernels).
    pub fn aps_error_bound(&self) -> f64 {
        match *self {
            Self::Laplace { .. } | Self::Matern32 { .. } | Self::Matern52 { .. } => 0.0,
            Self::Gaussian { tol, .. } => {
                let (t_param, _l) = gaussian_trapezoidal_params(tol);
                4.0 * (-0.5 * PI * PI * t_param * t_param).exp()
            }
        }
    }

    /// Expand this 1D kernel into its list of exact `PsTerm1D` terms (operating on scaled
    /// coordinates `x / bandwidth`, already centered).
    pub fn ps_terms(&self) -> Vec<PsTerm1D> {
        match *self {
            Self::Laplace { .. } => vec![PsTerm1D::ExponentialPoly {
                alpha: 1.0,
                poly_minus: [1.0, 0.0, 0.0],
                poly_plus: [1.0, 0.0, 0.0],
                power: 0,
            }],
            Self::Matern32 { .. } => {
                // k(x, y) = (1 + lam |x - y|) exp(-lam |x - y|), lam = sqrt(3)
                // y <= x: (1 + lam*x)*1 + (-lam)*y
                // y > x:  1*(1 + lam*y) + (-x)*(lam)
                let lam = 3.0_f64.sqrt();
                vec![
                    PsTerm1D::ExponentialPoly {
                        alpha: lam,
                        poly_minus: [1.0, lam, 0.0],
                        poly_plus: [1.0, lam, 0.0],
                        power: 0,
                    },
                    PsTerm1D::ExponentialPoly {
                        alpha: lam,
                        poly_minus: [-lam, 0.0, 0.0],
                        poly_plus: [lam, 0.0, 0.0],
                        power: 1,
                    },
                ]
            }
            Self::Matern52 { .. } => {
                // k(x, y) = (1 + lam |x - y| + lam^2 |x - y|^2 / 3) exp(-lam |x - y|), lam = sqrt(5)
                // Verified in Dafny lemma Matern52AlgebraicSeparability:
                // ell=0: f_- = 1 + lam*x + (lam^2/3)*x^2, g_- = 1;       f_+ = 1,   g_+ = 1 + lam*y + (lam^2/3)*y^2
                // ell=1: f_- = -lam - (2*lam^2/3)*x,      g_- = y;       f_+ = -x,  g_+ = lam + (2*lam^2/3)*y
                // ell=2: f_- = lam^2/3,                   g_- = y^2;     f_+ = x^2, g_+ = lam^2/3
                let lam = 5.0_f64.sqrt();
                let lam2_3 = (lam * lam) / 3.0;
                vec![
                    PsTerm1D::ExponentialPoly {
                        alpha: lam,
                        poly_minus: [1.0, lam, lam2_3],
                        poly_plus: [1.0, lam, lam2_3],
                        power: 0,
                    },
                    PsTerm1D::ExponentialPoly {
                        alpha: lam,
                        poly_minus: [-lam, -2.0 * lam2_3, 0.0],
                        poly_plus: [lam, 2.0 * lam2_3, 0.0],
                        power: 1,
                    },
                    PsTerm1D::ExponentialPoly {
                        alpha: lam,
                        poly_minus: [lam2_3, 0.0, 0.0],
                        poly_plus: [lam2_3, 0.0, 0.0],
                        power: 2,
                    },
                ]
            }
            Self::Gaussian { tol, .. } => {
                // Lemma 3 (arXiv:2612.05470):
                // a = pi * T / 4, M = 3 * pi * T / 4, L = ceil(M * T), u_j = j / T
                // I_{T,M}(rho) = A_0 e^{-2a rho} + sum_{j=1}^L A_j e^{-2a rho} cos(2 u_j (a - rho))
                let (t_param, l_max) = gaussian_trapezoidal_params(tol);
                let a = PI * t_param / 4.0;
                let two_a = 2.0 * a;
                let inv_t_sqrt_pi = 1.0 / (t_param * PI.sqrt());
                let exp_a2 = (a * a).exp();

                let mut terms = Vec::with_capacity(2 * l_max + 1);
                // j = 0 term: A_0 * exp(-2a |x - y|)
                let a0 = exp_a2 * inv_t_sqrt_pi;
                terms.push(PsTerm1D::ExponentialPoly {
                    alpha: two_a,
                    poly_minus: [a0, 0.0, 0.0],
                    poly_plus: [a0, 0.0, 0.0],
                    power: 0,
                });
                // j = 1..=L terms: h_{j,c} + h_{j,s}
                for j in 1..=l_max {
                    let u_j = (j as f64) / t_param;
                    let amp = 2.0 * (a * a - u_j * u_j).exp() * inv_t_sqrt_pi;
                    let two_u = 2.0 * u_j;
                    let two_u_a = two_u * a;
                    terms.push(PsTerm1D::GaussianCos {
                        two_a,
                        two_u,
                        two_u_a,
                        amp,
                    });
                    terms.push(PsTerm1D::GaussianSin {
                        two_a,
                        two_u,
                        two_u_a,
                        amp,
                    });
                }
                terms
            }
        }
    }
}

/// Compute `(T, L)` for Lemma 3 so that `4 * exp(-pi^2 * T^2 / 2) <= tol` and `L = ceil(3*pi*T^2 / 4)`.
pub fn gaussian_trapezoidal_params(tol: f64) -> (f64, usize) {
    let clamped_tol = tol.clamp(1e-12, 0.5);
    let t_needed = ((2.0 / (PI * PI)) * (4.0 / clamped_tol).ln()).max(1.0).sqrt();
    let t_param = t_needed.max(1.0);
    let l_max = (0.75 * PI * t_param * t_param).ceil() as usize;
    (t_param, l_max.max(1))
}

/// Product kernel $k(x, y) = \prod_{\ell=1}^d k_\ell(x_\ell, y_\ell)$.
#[derive(Debug, Clone)]
pub struct ProductKernel {
    pub factors: Vec<Kernel1D>,
}

impl ProductKernel {
    pub fn new(factors: Vec<Kernel1D>) -> Result<Self, String> {
        if factors.is_empty() {
            return Err("ProductKernel requires at least one 1D factor".to_string());
        }
        for (idx, f) in factors.iter().enumerate() {
            let bw = f.bandwidth();
            if !bw.is_finite() || bw <= 0.0 {
                return Err(format!("factor {idx} has non-positive or non-finite bandwidth {bw}"));
            }
            if let Kernel1D::Gaussian { tol, .. } = *f {
                if !tol.is_finite() || tol <= 0.0 {
                    return Err(format!("factor {idx} has invalid Gaussian tolerance {tol}"));
                }
            }
        }
        Ok(Self { factors })
    }

    pub fn laplace(bandwidths: &[f64]) -> Result<Self, String> {
        Self::new(
            bandwidths
                .iter()
                .map(|&bandwidth| Kernel1D::Laplace { bandwidth })
                .collect(),
        )
    }

    pub fn matern32(bandwidths: &[f64]) -> Result<Self, String> {
        Self::new(
            bandwidths
                .iter()
                .map(|&bandwidth| Kernel1D::Matern32 { bandwidth })
                .collect(),
        )
    }

    pub fn matern52(bandwidths: &[f64]) -> Result<Self, String> {
        Self::new(
            bandwidths
                .iter()
                .map(|&bandwidth| Kernel1D::Matern52 { bandwidth })
                .collect(),
        )
    }

    pub fn gaussian(bandwidths: &[f64], tol: f64) -> Result<Self, String> {
        Self::new(
            bandwidths
                .iter()
                .map(|&bandwidth| Kernel1D::Gaussian { bandwidth, tol })
                .collect(),
        )
    }

    pub fn dim(&self) -> usize {
        self.factors.len()
    }

    /// Exact pointwise evaluation $k(x, y) = \prod_{\ell=1}^d k_\ell(x_\ell, y_\ell)$.
    #[inline]
    pub fn eval_exact(&self, x: &[f64], y: &[f64]) -> f64 {
        let mut prod = 1.0;
        for (l, f) in self.factors.iter().enumerate() {
            prod *= f.eval_exact(x[l], y[l]);
        }
        prod
    }

    /// Theorem 1 uniform AOS error bound $\delta = d (1 + \delta_{\max})^{d-1} \delta_{\max}$
    /// (since all unit-peak 1D factors have $U = 1$).
    pub fn aos_error_bound(&self) -> f64 {
        let d = self.factors.len();
        let delta_max = self
            .factors
            .iter()
            .map(Kernel1D::aps_error_bound)
            .fold(0.0_f64, f64::max);
        if delta_max == 0.0 {
            return 0.0;
        }
        (d as f64) * (1.0 + delta_max).powi((d - 1) as i32) * delta_max
    }
}