fenwick-mmd 0.3.0

Formally verified, sub-quadratic minimax-optimal kernel two-sample testing (MMD) via compressed multidimensional Fenwick trees and orthantwise separable kernels
Documentation
//! PyO3 Python bindings for `fenwick-mmd` with full Rust/Python API parity.

use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;

use crate::kernels::ProductKernel;
use crate::mmd::{
    aggregated_mmd_test, median_bandwidths, mmd_squared_exact_quadratic, mmd_squared_fast,
    pca_mmd_test, permutation_test, AggregatedTestResult, PermutationTestResult,
};

fn build_kernel(
    kernel: &str,
    bandwidths: &[f64],
    gaussian_tol: f64,
) -> PyResult<ProductKernel> {
    let res = match kernel {
        "laplace" => ProductKernel::laplace(bandwidths),
        "matern32" => ProductKernel::matern32(bandwidths),
        "matern52" => ProductKernel::matern52(bandwidths),
        "gaussian" => ProductKernel::gaussian(bandwidths, gaussian_tol),
        other => Err(format!(
            "unknown kernel '{other}', expected one of: laplace, matern32, matern52, gaussian"
        )),
    };
    res.map_err(PyValueError::new_err)
}

#[pyclass(name = "PermutationTestResult")]
#[derive(Clone)]
pub struct PyPermutationTestResult {
    #[pyo3(get)]
    pub mmd_squared: f64,
    #[pyo3(get)]
    pub threshold: f64,
    #[pyo3(get)]
    pub p_value: f64,
    #[pyo3(get)]
    pub reject: bool,
    #[pyo3(get)]
    pub num_permutations: usize,
    #[pyo3(get)]
    pub alpha: f64,
    #[pyo3(get)]
    pub aos_error_bound: f64,
}

impl From<PermutationTestResult> for PyPermutationTestResult {
    fn from(r: PermutationTestResult) -> Self {
        Self {
            mmd_squared: r.mmd_squared,
            threshold: r.threshold,
            p_value: r.p_value,
            reject: r.reject,
            num_permutations: r.num_permutations,
            alpha: r.alpha,
            aos_error_bound: r.aos_error_bound,
        }
    }
}

#[pymethods]
impl PyPermutationTestResult {
    fn __repr__(&self) -> String {
        format!(
            "PermutationTestResult(mmd_squared={:.6e}, threshold={:.6e}, p_value={:.4}, reject={}, B={}, alpha={}, aos_error_bound={:.2e})",
            self.mmd_squared,
            self.threshold,
            self.p_value,
            self.reject,
            self.num_permutations,
            self.alpha,
            self.aos_error_bound,
        )
    }
}

#[pyclass(name = "AggregatedTestResult")]
#[derive(Clone)]
pub struct PyAggregatedTestResult {
    #[pyo3(get)]
    pub reject: bool,
    #[pyo3(get)]
    pub min_adjusted_p_value: f64,
    #[pyo3(get)]
    pub best_kernel_index: usize,
    #[pyo3(get)]
    pub per_kernel: Vec<PyPermutationTestResult>,
}

impl From<AggregatedTestResult> for PyAggregatedTestResult {
    fn from(r: AggregatedTestResult) -> Self {
        Self {
            reject: r.reject,
            min_adjusted_p_value: r.min_adjusted_p_value,
            best_kernel_index: r.best_kernel_index,
            per_kernel: r.per_kernel.into_iter().map(Into::into).collect(),
        }
    }
}

#[pymethods]
impl PyAggregatedTestResult {
    fn __repr__(&self) -> String {
        format!(
            "AggregatedTestResult(reject={}, min_adjusted_p_value={:.4}, best_kernel_index={}, num_kernels={})",
            self.reject,
            self.min_adjusted_p_value,
            self.best_kernel_index,
            self.per_kernel.len(),
        )
    }
}

#[pyfunction]
#[pyo3(signature = (x, y, bandwidths, kernel="laplace", gaussian_tol=1e-4))]
fn py_mmd_squared(
    x: Vec<Vec<f64>>,
    y: Vec<Vec<f64>>,
    bandwidths: Vec<f64>,
    kernel: &str,
    gaussian_tol: f64,
) -> PyResult<f64> {
    let k = build_kernel(kernel, &bandwidths, gaussian_tol)?;
    mmd_squared_fast(&x, &y, &k).map_err(|e| PyValueError::new_err(e.0))
}

#[pyfunction]
#[pyo3(signature = (x, y, bandwidths, kernel="laplace", gaussian_tol=1e-4))]
fn py_mmd_squared_exact(
    x: Vec<Vec<f64>>,
    y: Vec<Vec<f64>>,
    bandwidths: Vec<f64>,
    kernel: &str,
    gaussian_tol: f64,
) -> PyResult<f64> {
    let k = build_kernel(kernel, &bandwidths, gaussian_tol)?;
    mmd_squared_exact_quadratic(&x, &y, &k).map_err(|e| PyValueError::new_err(e.0))
}

#[pyfunction]
#[pyo3(signature = (x, y, bandwidths=None, kernel="laplace", num_permutations=199, alpha=0.05, seed=42, gaussian_tol=1e-4))]
#[allow(clippy::too_many_arguments)]
fn py_permutation_test(
    x: Vec<Vec<f64>>,
    y: Vec<Vec<f64>>,
    bandwidths: Option<Vec<f64>>,
    kernel: &str,
    num_permutations: usize,
    alpha: f64,
    seed: u64,
    gaussian_tol: f64,
) -> PyResult<PyPermutationTestResult> {
    let bws = match bandwidths {
        Some(b) => b,
        None => median_bandwidths(&x, &y, 512).map_err(|e| PyValueError::new_err(e.0))?,
    };
    let k = build_kernel(kernel, &bws, gaussian_tol)?;
    let res = permutation_test(&x, &y, &k, num_permutations, alpha, seed)
        .map_err(|e| PyValueError::new_err(e.0))?;
    Ok(res.into())
}

#[pyfunction]
#[pyo3(signature = (x, y, bandwidth_grid, kernel="laplace", num_permutations=199, alpha=0.05, seed=42, gaussian_tol=1e-4))]
#[allow(clippy::too_many_arguments)]
fn py_aggregated_mmd_test(
    x: Vec<Vec<f64>>,
    y: Vec<Vec<f64>>,
    bandwidth_grid: Vec<Vec<f64>>,
    kernel: &str,
    num_permutations: usize,
    alpha: f64,
    seed: u64,
    gaussian_tol: f64,
) -> PyResult<PyAggregatedTestResult> {
    let mut kernels = Vec::with_capacity(bandwidth_grid.len());
    for bws in &bandwidth_grid {
        kernels.push(build_kernel(kernel, bws, gaussian_tol)?);
    }
    let res = aggregated_mmd_test(&x, &y, &kernels, num_permutations, alpha, seed)
        .map_err(|e| PyValueError::new_err(e.0))?;
    Ok(res.into())
}

#[pyfunction]
#[pyo3(signature = (x, y, proj_dim, kernel="laplace", bandwidths=None, num_permutations=199, alpha=0.05, seed=42, sample_split=true, gaussian_tol=1e-4))]
#[allow(clippy::too_many_arguments)]
fn py_pca_mmd_test(
    x: Vec<Vec<f64>>,
    y: Vec<Vec<f64>>,
    proj_dim: usize,
    kernel: &str,
    bandwidths: Option<Vec<f64>>,
    num_permutations: usize,
    alpha: f64,
    seed: u64,
    sample_split: bool,
    gaussian_tol: f64,
) -> PyResult<PyPermutationTestResult> {
    let res = pca_mmd_test(
        &x,
        &y,
        proj_dim,
        kernel,
        bandwidths.as_deref(),
        gaussian_tol,
        num_permutations,
        alpha,
        seed,
        sample_split,
    )
    .map_err(|e| PyValueError::new_err(e.0))?;
    Ok(res.into())
}

#[pyfunction]
#[pyo3(signature = (x, y, max_points=512))]
fn py_median_bandwidths(x: Vec<Vec<f64>>, y: Vec<Vec<f64>>, max_points: usize) -> PyResult<Vec<f64>> {
    median_bandwidths(&x, &y, max_points).map_err(|e| PyValueError::new_err(e.0))
}

#[pymodule]
fn _core(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_class::<PyPermutationTestResult>()?;
    m.add_class::<PyAggregatedTestResult>()?;
    m.add_function(wrap_pyfunction!(py_mmd_squared, m)?)?;
    m.add_function(wrap_pyfunction!(py_mmd_squared_exact, m)?)?;
    m.add_function(wrap_pyfunction!(py_permutation_test, m)?)?;
    m.add_function(wrap_pyfunction!(py_aggregated_mmd_test, m)?)?;
    m.add_function(wrap_pyfunction!(py_pca_mmd_test, m)?)?;
    m.add_function(wrap_pyfunction!(py_median_bandwidths, m)?)?;
    Ok(())
}