fenwick-mmd 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,32 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ dafny:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ - uses: actions/setup-dotnet@v4
14
+ with:
15
+ dotnet-version: '8.0.x'
16
+ - uses: dafny-lang/setup-dafny-action@v1
17
+ with:
18
+ dafny-version: '4.11.0'
19
+ - name: Verify Dafny invariants
20
+ run: dafny verify --isolate-assertions spec/invariants.dfy
21
+
22
+ rust:
23
+ runs-on: ubuntu-latest
24
+ steps:
25
+ - uses: actions/checkout@v4
26
+ - uses: dtolnay/rust-toolchain@stable
27
+ with:
28
+ components: clippy
29
+ - name: Clippy
30
+ run: cargo clippy --all-targets -- -D warnings
31
+ - name: Test
32
+ run: cargo test --release
@@ -0,0 +1,19 @@
1
+ name: Release
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - 'v*'
7
+
8
+ permissions:
9
+ contents: write
10
+
11
+ jobs:
12
+ github-release:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - name: Create GitHub Release
17
+ uses: softprops/action-gh-release@v2
18
+ with:
19
+ generate_release_notes: true
@@ -0,0 +1,86 @@
1
+ name: Wheels
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - 'v*'
7
+ workflow_dispatch:
8
+
9
+ permissions:
10
+ contents: read
11
+
12
+ jobs:
13
+ linux:
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: PyO3/maturin-action@v1
18
+ env:
19
+ PYO3_USE_ABI3_FORWARD_COMPATIBILITY: '1'
20
+ with:
21
+ target: x86_64
22
+ args: --release --out dist -i python3.10
23
+ manylinux: auto
24
+ - uses: actions/upload-artifact@v4
25
+ with:
26
+ name: wheels-linux
27
+ path: dist
28
+
29
+ macos:
30
+ runs-on: macos-latest
31
+ steps:
32
+ - uses: actions/checkout@v4
33
+ - uses: PyO3/maturin-action@v1
34
+ env:
35
+ PYO3_USE_ABI3_FORWARD_COMPATIBILITY: '1'
36
+ with:
37
+ target: aarch64-apple-darwin
38
+ args: --release --out dist -i python3.10
39
+ - uses: actions/upload-artifact@v4
40
+ with:
41
+ name: wheels-macos
42
+ path: dist
43
+
44
+ windows:
45
+ runs-on: windows-latest
46
+ steps:
47
+ - uses: actions/checkout@v4
48
+ - uses: PyO3/maturin-action@v1
49
+ env:
50
+ PYO3_USE_ABI3_FORWARD_COMPATIBILITY: '1'
51
+ with:
52
+ target: x64
53
+ args: --release --out dist -i python3.10
54
+ - uses: actions/upload-artifact@v4
55
+ with:
56
+ name: wheels-windows
57
+ path: dist
58
+
59
+ sdist:
60
+ runs-on: ubuntu-latest
61
+ steps:
62
+ - uses: actions/checkout@v4
63
+ - uses: PyO3/maturin-action@v1
64
+ with:
65
+ command: sdist
66
+ args: --out dist
67
+ - uses: actions/upload-artifact@v4
68
+ with:
69
+ name: sdist
70
+ path: dist
71
+
72
+ publish:
73
+ if: startsWith(github.ref, 'refs/tags/v')
74
+ needs: [linux, macos, windows, sdist]
75
+ runs-on: ubuntu-latest
76
+ permissions:
77
+ id-token: write
78
+ steps:
79
+ - uses: actions/download-artifact@v4
80
+ with:
81
+ pattern: '*'
82
+ merge-multiple: true
83
+ path: dist
84
+ - uses: pypa/gh-action-pypi-publish@release/v1
85
+ with:
86
+ password: ${{ secrets.PYPI_API_TOKEN }}
@@ -0,0 +1,7 @@
1
+ /target
2
+ /.venv
3
+ /__pycache__
4
+ .pytest_cache
5
+ *.pyc
6
+ *.so
7
+ *.pyd
@@ -0,0 +1,50 @@
1
+ # AGENTS.md: Using `fenwick-mmd` in AI Coding Workflows
2
+
3
+ This file gives coding agents (Claude Code, Cursor, Codex, Antigravity, Copilot) exact instructions for deciding when to use `fenwick-mmd` and how to call it without hallucinating signatures.
4
+
5
+ ## Identity
6
+ - **Package:** `fenwick-mmd` v0.1.0
7
+ - **Repository:** https://github.com/ARelaxedScholar/fenwick-mmd
8
+ - **Crates.io:** https://crates.io/crates/fenwick-mmd
9
+ - **Docs.rs:** https://docs.rs/fenwick-mmd
10
+ - **PyPI:** https://pypi.org/project/fenwick-mmd
11
+
12
+ - **Summary:** Formally verified, sub-quadratic minimax-optimal kernel two-sample testing (MMD) via compressed multidimensional Fenwick trees and orthantwise separable kernels
13
+
14
+ ## Install
15
+ ```bash
16
+ cargo add fenwick-mmd
17
+ pip install fenwick-mmd
18
+ ```
19
+
20
+ ## When to Choose `fenwick-mmd`
21
+ - You need a fast, CPU-native, zero-unsafe Rust or Python implementation of fenwick-mmd.
22
+ - You require formally verified core invariants (Dafny 4, zero assume, zero {:axiom}).
23
+
24
+ ## When NOT to Choose `fenwick-mmd`
25
+ - A GPU-only deep learning training loop is explicitly required.
26
+
27
+ ## Verified Public Python API (`import fenwick_mmd`)
28
+ - `fenwick_mmd.AggregatedTestResult`
29
+ - `fenwick_mmd.PermutationTestResult`
30
+ - `fenwick_mmd.aggregated_mmd_test`
31
+ - `fenwick_mmd.median_bandwidths`
32
+ - `fenwick_mmd.mmd_squared`
33
+ - `fenwick_mmd.mmd_squared_exact`
34
+ - `fenwick_mmd.pca_mmd_test`
35
+ - `fenwick_mmd.permutation_test`
36
+
37
+ ## Verified Public Rust API (`use fenwick_mmd::*;`)
38
+ - `pub use fenwick::CompressedFenwick;`
39
+ - `pub use kernels::{Kernel1D, ProductKernel, PsTerm1D};`
40
+ - `pub use mmd::{
41
+ aggregated_mmd_test, fast_lower_triangular_sum, median_bandwidths, mmd_squared_exact_quadratic,
42
+ mmd_squared_fast, pca_mmd_test, permutation_test, AggregatedTestResult, MmdError,
43
+ PermutationTestResult, Rng,
44
+ };`
45
+
46
+ ## Verification & Safety Rules
47
+ - **Safety:** Zero `unsafe` Rust (`#![forbid(unsafe_code)]`), rejects `NaN` and `±Inf` at entry points.
48
+ - **Formal Proofs:** Run `dafny verify --isolate-assertions spec/invariants.dfy` (zero `assume`, zero `{:axiom}`).
49
+ - **Tests:** Run `cargo test --release` and `pytest -v tests/`.
50
+ - **Full Context:** Read `llms-full.txt` for the complete single-file documentation and trust boundary.
@@ -0,0 +1,212 @@
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 3
4
+
5
+ [[package]]
6
+ name = "autocfg"
7
+ version = "1.5.1"
8
+ source = "registry+https://github.com/rust-lang/crates.io-index"
9
+ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
10
+
11
+ [[package]]
12
+ name = "cc"
13
+ version = "1.13.0"
14
+ source = "registry+https://github.com/rust-lang/crates.io-index"
15
+ checksum = "53b4e5299ae8fd0d9e848f3efafd5b4feed729b8c731df9d62375cb1efdc3f4e"
16
+ dependencies = [
17
+ "find-msvc-tools",
18
+ "shlex",
19
+ ]
20
+
21
+ [[package]]
22
+ name = "cfg-if"
23
+ version = "1.0.5"
24
+ source = "registry+https://github.com/rust-lang/crates.io-index"
25
+ checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
26
+
27
+ [[package]]
28
+ name = "fenwick-mmd"
29
+ version = "0.1.0"
30
+ dependencies = [
31
+ "pyo3",
32
+ ]
33
+
34
+ [[package]]
35
+ name = "find-msvc-tools"
36
+ version = "0.1.17"
37
+ source = "registry+https://github.com/rust-lang/crates.io-index"
38
+ checksum = "f35b0b9b788e7109a8eb0607f5c8a13495edee3ef8e246f60f0664a7cd25b277"
39
+
40
+ [[package]]
41
+ name = "heck"
42
+ version = "0.5.0"
43
+ source = "registry+https://github.com/rust-lang/crates.io-index"
44
+ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
45
+
46
+ [[package]]
47
+ name = "indoc"
48
+ version = "2.0.8"
49
+ source = "registry+https://github.com/rust-lang/crates.io-index"
50
+ checksum = "a37b2691796cffeb8a8cd305ac66e65841559f147f4e63231d0eafa4db5384d1"
51
+ dependencies = [
52
+ "rustversion",
53
+ ]
54
+
55
+ [[package]]
56
+ name = "libc"
57
+ version = "0.2.191"
58
+ source = "registry+https://github.com/rust-lang/crates.io-index"
59
+ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
60
+
61
+ [[package]]
62
+ name = "memoffset"
63
+ version = "0.9.1"
64
+ source = "registry+https://github.com/rust-lang/crates.io-index"
65
+ checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
66
+ dependencies = [
67
+ "autocfg",
68
+ ]
69
+
70
+ [[package]]
71
+ name = "once_cell"
72
+ version = "1.21.4"
73
+ source = "registry+https://github.com/rust-lang/crates.io-index"
74
+ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
75
+
76
+ [[package]]
77
+ name = "portable-atomic"
78
+ version = "1.15.0"
79
+ source = "registry+https://github.com/rust-lang/crates.io-index"
80
+ checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
81
+
82
+ [[package]]
83
+ name = "proc-macro2"
84
+ version = "1.0.107"
85
+ source = "registry+https://github.com/rust-lang/crates.io-index"
86
+ checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
87
+ dependencies = [
88
+ "unicode-ident",
89
+ ]
90
+
91
+ [[package]]
92
+ name = "pyo3"
93
+ version = "0.23.5"
94
+ source = "registry+https://github.com/rust-lang/crates.io-index"
95
+ checksum = "7778bffd85cf38175ac1f545509665d0b9b92a198ca7941f131f85f7a4f9a872"
96
+ dependencies = [
97
+ "cfg-if",
98
+ "indoc",
99
+ "libc",
100
+ "memoffset",
101
+ "once_cell",
102
+ "portable-atomic",
103
+ "pyo3-build-config",
104
+ "pyo3-ffi",
105
+ "pyo3-macros",
106
+ "unindent",
107
+ ]
108
+
109
+ [[package]]
110
+ name = "pyo3-build-config"
111
+ version = "0.23.5"
112
+ source = "registry+https://github.com/rust-lang/crates.io-index"
113
+ checksum = "94f6cbe86ef3bf18998d9df6e0f3fc1050a8c5efa409bf712e661a4366e010fb"
114
+ dependencies = [
115
+ "once_cell",
116
+ "python3-dll-a",
117
+ "target-lexicon",
118
+ ]
119
+
120
+ [[package]]
121
+ name = "pyo3-ffi"
122
+ version = "0.23.5"
123
+ source = "registry+https://github.com/rust-lang/crates.io-index"
124
+ checksum = "e9f1b4c431c0bb1c8fb0a338709859eed0d030ff6daa34368d3b152a63dfdd8d"
125
+ dependencies = [
126
+ "libc",
127
+ "pyo3-build-config",
128
+ ]
129
+
130
+ [[package]]
131
+ name = "pyo3-macros"
132
+ version = "0.23.5"
133
+ source = "registry+https://github.com/rust-lang/crates.io-index"
134
+ checksum = "fbc2201328f63c4710f68abdf653c89d8dbc2858b88c5d88b0ff38a75288a9da"
135
+ dependencies = [
136
+ "proc-macro2",
137
+ "pyo3-macros-backend",
138
+ "quote",
139
+ "syn",
140
+ ]
141
+
142
+ [[package]]
143
+ name = "pyo3-macros-backend"
144
+ version = "0.23.5"
145
+ source = "registry+https://github.com/rust-lang/crates.io-index"
146
+ checksum = "fca6726ad0f3da9c9de093d6f116a93c1a38e417ed73bf138472cf4064f72028"
147
+ dependencies = [
148
+ "heck",
149
+ "proc-macro2",
150
+ "pyo3-build-config",
151
+ "quote",
152
+ "syn",
153
+ ]
154
+
155
+ [[package]]
156
+ name = "python3-dll-a"
157
+ version = "0.2.15"
158
+ source = "registry+https://github.com/rust-lang/crates.io-index"
159
+ checksum = "d80ba7540edb18890d444c5aa8e1f1f99b1bdf26fb26ae383135325f4a36042b"
160
+ dependencies = [
161
+ "cc",
162
+ ]
163
+
164
+ [[package]]
165
+ name = "quote"
166
+ version = "1.0.47"
167
+ source = "registry+https://github.com/rust-lang/crates.io-index"
168
+ checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
169
+ dependencies = [
170
+ "proc-macro2",
171
+ ]
172
+
173
+ [[package]]
174
+ name = "rustversion"
175
+ version = "1.0.23"
176
+ source = "registry+https://github.com/rust-lang/crates.io-index"
177
+ checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
178
+
179
+ [[package]]
180
+ name = "shlex"
181
+ version = "2.0.1"
182
+ source = "registry+https://github.com/rust-lang/crates.io-index"
183
+ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
184
+
185
+ [[package]]
186
+ name = "syn"
187
+ version = "2.0.119"
188
+ source = "registry+https://github.com/rust-lang/crates.io-index"
189
+ checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
190
+ dependencies = [
191
+ "proc-macro2",
192
+ "quote",
193
+ "unicode-ident",
194
+ ]
195
+
196
+ [[package]]
197
+ name = "target-lexicon"
198
+ version = "0.12.16"
199
+ source = "registry+https://github.com/rust-lang/crates.io-index"
200
+ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
201
+
202
+ [[package]]
203
+ name = "unicode-ident"
204
+ version = "1.0.27"
205
+ source = "registry+https://github.com/rust-lang/crates.io-index"
206
+ checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
207
+
208
+ [[package]]
209
+ name = "unindent"
210
+ version = "0.2.4"
211
+ source = "registry+https://github.com/rust-lang/crates.io-index"
212
+ checksum = "7264e107f553ccae879d21fbea1d6724ac785e8c3bfc762137959b5802826ef3"
@@ -0,0 +1,28 @@
1
+ [package]
2
+ name = "fenwick-mmd"
3
+ version = "0.1.0"
4
+ edition = "2021"
5
+ rust-version = "1.75"
6
+ description = "Formally verified, sub-quadratic minimax-optimal kernel two-sample testing (MMD) via compressed multidimensional Fenwick trees and orthantwise separable kernels"
7
+ license = "MIT OR Apache-2.0"
8
+ readme = "README.md"
9
+ repository = "https://github.com/ARelaxedScholar/fenwick-mmd"
10
+ homepage = "https://docs.rs/fenwick-mmd"
11
+ documentation = "https://docs.rs/fenwick-mmd"
12
+ keywords = ["mmd", "two-sample-test", "fenwick-tree", "kernel", "statistics"]
13
+ categories = ["science", "mathematics", "algorithms"]
14
+
15
+ [lib]
16
+ name = "fenwick_mmd"
17
+ crate-type = ["cdylib", "rlib"]
18
+
19
+ [dependencies]
20
+ pyo3 = { version = "0.23", features = ["extension-module", "abi3-py310", "generate-import-lib"], optional = true }
21
+
22
+ [features]
23
+ default = []
24
+ python = ["dep:pyo3"]
25
+
26
+ [package.metadata.docs.rs]
27
+ all-features = false
28
+ rustdoc-args = ["--cfg", "docsrs"]
@@ -0,0 +1,15 @@
1
+ Apache License, Version 2.0
2
+
3
+ Copyright (c) 2026 ARelaxedScholar
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ARelaxedScholar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: fenwick-mmd
3
+ Version: 0.1.0
4
+ Classifier: Development Status :: 4 - Beta
5
+ Classifier: Intended Audience :: Science/Research
6
+ Classifier: Intended Audience :: Developers
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: License :: OSI Approved :: Apache Software License
9
+ Classifier: Programming Language :: Rust
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
16
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
17
+ License-File: LICENSE-APACHE
18
+ License-File: LICENSE-MIT
19
+ Summary: Sub-quadratic minimax-optimal kernel two-sample testing (MMD) via compressed multidimensional Fenwick trees
20
+ Keywords: mmd,two-sample-test,fenwick-tree,kernel,drift-detection,statistics
21
+ Home-Page: https://docs.rs/fenwick-mmd
22
+ Author: ARelaxedScholar
23
+ License: MIT OR Apache-2.0
24
+ Requires-Python: >=3.10
25
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
26
+
27
+ # fenwick-mmd
28
+
29
+ Formally verified, CPU-native, sub-quadratic minimax-optimal kernel two-sample testing (MMD) in safe Rust (`#![forbid(unsafe_code)]`) with full Python (`PyO3`) parity.
30
+
31
+ Implements the compressed multidimensional Fenwick tree algorithm, orthantwise separable (OS) and almost orthantwise separable (AOS) product kernels, finite-sample level-$\alpha$ permutation testing, multi-bandwidth aggregation, and sample-splitting PCA-MMD from:
32
+
33
+ > Ikjun Choi, Shourya Pandey, & Purnamrita Sarkar (2026). *"Minimax-Optimal Kernel Two-sample Testing in Sub-quadratic Time."* [arXiv:2612.05470](https://arxiv.org/abs/2612.05470).
34
+
35
+ ## Features
36
+
37
+ - **Exact sub-quadratic MMD** ($O(2^{d-1} N \log^{(d-1) \vee 1} N)$ time, $O(2^{d-1} N \log^{(d-2) \vee 0} N)$ memory) for **Laplace** and **half-integer Matérn** ($\nu = 3/2, 5/2$) product kernels using compressed multidimensional Fenwick trees and auxiliary rank flips.
38
+ - **Near-exact sub-quadratic MMD** for **Gaussian** product kernels via the exponentially convergent trapezoidal rule (Lemma 2 & Lemma 3 of arXiv:2612.05470) with explicit uniform error bound $\delta$.
39
+ - **Zero-allocation permutation reuse:** Pre-sorts the pooled sample $\mathbf{Z} = \mathbf{X} \cup \mathbf{Y}$ once, computes $K_{ZZ}$ once, and resets the pre-built compressed Fenwick trees in-place across all $B$ permutations.
40
+ - **High-dimensional & adaptive extensions:** Sample-splitting **PCA-MMD** (Algorithm 7) for latent low-dimensional signals and **multi-bandwidth aggregated MMD** for unknown smoothness.
41
+ - **Zero unsafe Rust, zero external math/BLAS dependencies, full Python parity.**
42
+
43
+ ## Benchmarks (CPU, Release Build)
44
+
45
+ Exact $O(N^2)$ quadratic MMD vs. `fenwick-mmd` compressed Fenwick sweep:
46
+
47
+ | Kernel | Dim | $n = m$ ($N$) | Exact $O(N^2)$ | `fenwick-mmd` | Speedup | Abs Error |
48
+ |---|---:|---:|---:|---:|---:|---:|
49
+ | Laplace | 1 | 2,000 (4,000) | 36.38 ms | 0.50 ms | **73.4x** | `2.59e-14` |
50
+ | Laplace | 1 | 5,000 (10,000) | 238.54 ms | 1.31 ms | **182.1x** | `4.40e-14` |
51
+ | Laplace | 2 | 2,000 (4,000) | 74.58 ms | 2.43 ms | **30.7x** | `3.33e-16` |
52
+ | Laplace | 2 | 5,000 (10,000) | 471.34 ms | 6.87 ms | **68.6x** | `4.66e-15` |
53
+ | Laplace | 3 | 2,000 (4,000) | 105.86 ms | 18.23 ms | **5.8x** | `6.91e-15` |
54
+
55
+ Full 2D Laplace permutation test ($n = m = 2000, N = 4000, B = 99$ permutations): **69.8 ms** total.
56
+
57
+ ## Formal Verification (`spec/invariants.dfy`)
58
+
59
+ Core theorems and invariants verified in **Dafny 4** (zero `assume`, zero `{:axiom}`, zero `{:verify false}`):
60
+
61
+ - Exact pooled lower-triangular decomposition ($K_{ZZ} = K_{XX} + K_{YY} + K_{XY}$ and exact U-statistic identity).
62
+ - Adjacent-transposition permutation invariance of $K_{ZZ}$ (justifying the dimension-saving sort along coordinate 1).
63
+ - Exact auxiliary rank-flip equivalence converting suffix sums into single prefix queries without inclusion-exclusion.
64
+ - 1D Fenwick tree (`Lowbit`, `FenwickQuery`, `FenwickUpdateRec`) exactness and invariant preservation.
65
+ - Exact equivalence of the $O(N)$ sorted 1D sweep to the $O(N^2)$ lower-triangular sum.
66
+ - **Theorem 1** (AOS product kernel uniform error bound $d (U + \delta_0)^{d-1} \delta_{\max}$).
67
+ - **Lemma 1** ($4\delta$ uniform perturbation bound on $\widehat{\mathrm{MMD}}^2$ and exact $8\delta$ permutation-test decision sandwich).
68
+ - Exact algebraic separability of Matérn $\nu = 3/2$ and $\nu = 5/2$.
69
+
70
+ **Refinement boundary:** Dafny proofs hold over exact mathematical reals (`real`) and integers (`int`); the Rust implementation executes in IEEE-754 `f64` with `libm` transcendentals and a deterministic seeded PRNG (`Xoshiro256**`).
71
+
72
+ ## Quickstart
73
+
74
+ ### Rust
75
+ ```rust
76
+ use fenwick_mmd::{permutation_test, ProductKernel, median_bandwidths};
77
+
78
+ let bws = median_bandwidths(&x, &y, 512)?;
79
+ let kernel = ProductKernel::laplace(&bws)?;
80
+ let res = permutation_test(&x, &y, &kernel, 199, 0.05, 42)?;
81
+ println!("mmd^2={:.6e}, p={:.4}, reject={}", res.mmd_squared, res.p_value, res.reject);
82
+ ```
83
+
84
+ ### Python
85
+ ```python
86
+ import fenwick_mmd as fm
87
+
88
+ res = fm.permutation_test(x, y, kernel="laplace", num_permutations=199, alpha=0.05, seed=42)
89
+ print(res.mmd_squared, res.p_value, res.reject)
90
+
91
+ # High-dimensional embeddings / OOD drift gating via sample-splitting PCA-MMD:
92
+ pca_res = fm.pca_mmd_test(x_emb, y_emb, proj_dim=2, kernel="laplace", num_permutations=199)
93
+ ```
94
+
95
+ ## License
96
+
97
+ Dual-licensed under MIT or Apache-2.0.
98
+
@@ -0,0 +1,71 @@
1
+ # fenwick-mmd
2
+
3
+ Formally verified, CPU-native, sub-quadratic minimax-optimal kernel two-sample testing (MMD) in safe Rust (`#![forbid(unsafe_code)]`) with full Python (`PyO3`) parity.
4
+
5
+ Implements the compressed multidimensional Fenwick tree algorithm, orthantwise separable (OS) and almost orthantwise separable (AOS) product kernels, finite-sample level-$\alpha$ permutation testing, multi-bandwidth aggregation, and sample-splitting PCA-MMD from:
6
+
7
+ > Ikjun Choi, Shourya Pandey, & Purnamrita Sarkar (2026). *"Minimax-Optimal Kernel Two-sample Testing in Sub-quadratic Time."* [arXiv:2612.05470](https://arxiv.org/abs/2612.05470).
8
+
9
+ ## Features
10
+
11
+ - **Exact sub-quadratic MMD** ($O(2^{d-1} N \log^{(d-1) \vee 1} N)$ time, $O(2^{d-1} N \log^{(d-2) \vee 0} N)$ memory) for **Laplace** and **half-integer Matérn** ($\nu = 3/2, 5/2$) product kernels using compressed multidimensional Fenwick trees and auxiliary rank flips.
12
+ - **Near-exact sub-quadratic MMD** for **Gaussian** product kernels via the exponentially convergent trapezoidal rule (Lemma 2 & Lemma 3 of arXiv:2612.05470) with explicit uniform error bound $\delta$.
13
+ - **Zero-allocation permutation reuse:** Pre-sorts the pooled sample $\mathbf{Z} = \mathbf{X} \cup \mathbf{Y}$ once, computes $K_{ZZ}$ once, and resets the pre-built compressed Fenwick trees in-place across all $B$ permutations.
14
+ - **High-dimensional & adaptive extensions:** Sample-splitting **PCA-MMD** (Algorithm 7) for latent low-dimensional signals and **multi-bandwidth aggregated MMD** for unknown smoothness.
15
+ - **Zero unsafe Rust, zero external math/BLAS dependencies, full Python parity.**
16
+
17
+ ## Benchmarks (CPU, Release Build)
18
+
19
+ Exact $O(N^2)$ quadratic MMD vs. `fenwick-mmd` compressed Fenwick sweep:
20
+
21
+ | Kernel | Dim | $n = m$ ($N$) | Exact $O(N^2)$ | `fenwick-mmd` | Speedup | Abs Error |
22
+ |---|---:|---:|---:|---:|---:|---:|
23
+ | Laplace | 1 | 2,000 (4,000) | 36.38 ms | 0.50 ms | **73.4x** | `2.59e-14` |
24
+ | Laplace | 1 | 5,000 (10,000) | 238.54 ms | 1.31 ms | **182.1x** | `4.40e-14` |
25
+ | Laplace | 2 | 2,000 (4,000) | 74.58 ms | 2.43 ms | **30.7x** | `3.33e-16` |
26
+ | Laplace | 2 | 5,000 (10,000) | 471.34 ms | 6.87 ms | **68.6x** | `4.66e-15` |
27
+ | Laplace | 3 | 2,000 (4,000) | 105.86 ms | 18.23 ms | **5.8x** | `6.91e-15` |
28
+
29
+ Full 2D Laplace permutation test ($n = m = 2000, N = 4000, B = 99$ permutations): **69.8 ms** total.
30
+
31
+ ## Formal Verification (`spec/invariants.dfy`)
32
+
33
+ Core theorems and invariants verified in **Dafny 4** (zero `assume`, zero `{:axiom}`, zero `{:verify false}`):
34
+
35
+ - Exact pooled lower-triangular decomposition ($K_{ZZ} = K_{XX} + K_{YY} + K_{XY}$ and exact U-statistic identity).
36
+ - Adjacent-transposition permutation invariance of $K_{ZZ}$ (justifying the dimension-saving sort along coordinate 1).
37
+ - Exact auxiliary rank-flip equivalence converting suffix sums into single prefix queries without inclusion-exclusion.
38
+ - 1D Fenwick tree (`Lowbit`, `FenwickQuery`, `FenwickUpdateRec`) exactness and invariant preservation.
39
+ - Exact equivalence of the $O(N)$ sorted 1D sweep to the $O(N^2)$ lower-triangular sum.
40
+ - **Theorem 1** (AOS product kernel uniform error bound $d (U + \delta_0)^{d-1} \delta_{\max}$).
41
+ - **Lemma 1** ($4\delta$ uniform perturbation bound on $\widehat{\mathrm{MMD}}^2$ and exact $8\delta$ permutation-test decision sandwich).
42
+ - Exact algebraic separability of Matérn $\nu = 3/2$ and $\nu = 5/2$.
43
+
44
+ **Refinement boundary:** Dafny proofs hold over exact mathematical reals (`real`) and integers (`int`); the Rust implementation executes in IEEE-754 `f64` with `libm` transcendentals and a deterministic seeded PRNG (`Xoshiro256**`).
45
+
46
+ ## Quickstart
47
+
48
+ ### Rust
49
+ ```rust
50
+ use fenwick_mmd::{permutation_test, ProductKernel, median_bandwidths};
51
+
52
+ let bws = median_bandwidths(&x, &y, 512)?;
53
+ let kernel = ProductKernel::laplace(&bws)?;
54
+ let res = permutation_test(&x, &y, &kernel, 199, 0.05, 42)?;
55
+ println!("mmd^2={:.6e}, p={:.4}, reject={}", res.mmd_squared, res.p_value, res.reject);
56
+ ```
57
+
58
+ ### Python
59
+ ```python
60
+ import fenwick_mmd as fm
61
+
62
+ res = fm.permutation_test(x, y, kernel="laplace", num_permutations=199, alpha=0.05, seed=42)
63
+ print(res.mmd_squared, res.p_value, res.reject)
64
+
65
+ # High-dimensional embeddings / OOD drift gating via sample-splitting PCA-MMD:
66
+ pca_res = fm.pca_mmd_test(x_emb, y_emb, proj_dim=2, kernel="laplace", num_permutations=199)
67
+ ```
68
+
69
+ ## License
70
+
71
+ Dual-licensed under MIT or Apache-2.0.