diff --git a/CHANGELOG.md b/CHANGELOG.md index ef3fc16..78928a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## 0.11.1 2026-06-13 + +### Changed + +* Extract Hermite node weights from eval loop for cubic methods + * 3x asymptotic speedup for large data; modest improvement in latency +* Use inlined helper function for FMA feature switching + +### Added + +* Add B-spline methods for regular and rectilinear grids + * Tridiagonal coeff solve using preallocated scratch space, optionally parallelized + * Use same BCs as Hermite methods (zero third derivative) for reduced ringing and graceful transition to linearized extrapolation + ## 0.11.0 2026-01-15 ### Changed diff --git a/Cargo.lock b/Cargo.lock index d724307..db3411c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -32,12 +32,24 @@ version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + [[package]] name = "autocfg" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" +[[package]] +name = "bitflags" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" + [[package]] name = "bumpalo" version = "3.19.0" @@ -66,6 +78,17 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9" +[[package]] +name = "chacha20" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + [[package]] name = "ciborium" version = "0.2.2" @@ -118,11 +141,20 @@ version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675" +[[package]] +name = "cpufeatures" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +dependencies = [ + "libc", +] + [[package]] name = "criterion" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d883447757bb0ee46f233e9dc22eb84d93a9508c9b868687b274fc431d886bf" +checksum = "950046b2aa2492f9a536f5f4f9a3de7b9e2476e575e05bd6c333371add4d98f3" dependencies = [ "alloca", "anes", @@ -145,9 +177,9 @@ dependencies = [ [[package]] name = "criterion-plot" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed943f81ea2faa8dcecbbfa50164acf95d555afec96a27871663b300e387b2e4" +checksum = "d8d80a2f4f5b554395e47b5d8305bc3d27813bacb73493eb1001e8f76dae29ea" dependencies = [ "cast", "itertools 0.13.0", @@ -190,22 +222,36 @@ version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + [[package]] name = "find-msvc-tools" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ced73b1dacfc750a6db6c0a0c3a3853c8b41997e2e2c563dc90804ae6867959" +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + [[package]] name = "getrandom" -version = "0.3.3" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" dependencies = [ "cfg-if", "libc", "r-efi", - "wasi", + "rand_core", + "wasip2", + "wasip3", ] [[package]] @@ -218,6 +264,21 @@ dependencies = [ "crunchy", ] +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + [[package]] name = "heck" version = "0.5.0" @@ -231,14 +292,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" [[package]] -name = "indoc" -version = "2.0.5" +name = "id-arena" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b248f5224d1d606005e02c97f5aa4e88eeb230488bcc03bc9ca4d7991399f2b5" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] [[package]] name = "interpn" -version = "0.11.0" +version = "0.11.1" dependencies = [ "criterion", "crunchy", @@ -286,6 +359,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + [[package]] name = "libc" version = "0.2.158" @@ -320,15 +399,6 @@ version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" -[[package]] -name = "memoffset" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" -dependencies = [ - "autocfg", -] - [[package]] name = "ndarray" version = "0.17.2" @@ -384,9 +454,9 @@ dependencies = [ [[package]] name = "numpy" -version = "0.27.1" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7aac2e6a6e4468ffa092ad43c39b81c79196c2bb773b8db4085f695efe3bba17" +checksum = "778da78c64ddc928ebf5ad9df5edf0789410ff3bdbf3619aed51cd789a6af1e2" dependencies = [ "libc", "ndarray", @@ -464,12 +534,13 @@ dependencies = [ ] [[package]] -name = "ppv-lite86" -version = "0.2.21" +name = "prettyplease" +version = "0.2.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" dependencies = [ - "zerocopy", + "proc-macro2", + "syn", ] [[package]] @@ -483,26 +554,23 @@ dependencies = [ [[package]] name = "pyo3" -version = "0.27.2" +version = "0.28.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab53c047fcd1a1d2a8820fe84f05d6be69e9526be40cb03b73f86b6b03e6d87d" +checksum = "91fd8e38a3b50ed1167fb981cd6fd60147e091784c427b8f7183a7ee32c31c12" dependencies = [ - "indoc", "libc", - "memoffset", "once_cell", "portable-atomic", "pyo3-build-config", "pyo3-ffi", "pyo3-macros", - "unindent", ] [[package]] name = "pyo3-build-config" -version = "0.27.2" +version = "0.28.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b455933107de8642b4487ed26d912c2d899dec6114884214a0b3bb3be9261ea6" +checksum = "e368e7ddfdeb98c9bca7f8383be1648fd84ab466bf2bc015e94008db6d35611e" dependencies = [ "python3-dll-a", "target-lexicon", @@ -510,9 +578,9 @@ dependencies = [ [[package]] name = "pyo3-ffi" -version = "0.27.2" +version = "0.28.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c85c9cbfaddf651b1221594209aed57e9e5cff63c4d11d1feead529b872a089" +checksum = "7f29e10af80b1f7ccaf7f69eace800a03ecd13e883acfacc1e5d0988605f651e" dependencies = [ "libc", "pyo3-build-config", @@ -520,9 +588,9 @@ dependencies = [ [[package]] name = "pyo3-macros" -version = "0.27.2" +version = "0.28.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a5b10c9bf9888125d917fb4d2ca2d25c8df94c7ab5a52e13313a07e050a3b02" +checksum = "df6e520eff47c45997d2fc7dd8214b25dd1310918bbb2642156ef66a67f29813" dependencies = [ "proc-macro2", "pyo3-macros-backend", @@ -532,9 +600,9 @@ dependencies = [ [[package]] name = "pyo3-macros-backend" -version = "0.27.2" +version = "0.28.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03b51720d314836e53327f5871d4c0cfb4fb37cc2c4a11cc71907a86342c40f9" +checksum = "c4cdc218d835738f81c2338f822078af45b4afdf8b2e33cbb5916f108b813acb" dependencies = [ "heck", "proc-macro2", @@ -554,47 +622,35 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.36" +version = "1.0.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" dependencies = [ "proc-macro2", ] [[package]] name = "r-efi" -version = "5.3.0" +version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "rand" -version = "0.9.2" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" +checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207" dependencies = [ - "rand_chacha", - "rand_core", -] - -[[package]] -name = "rand_chacha" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" -dependencies = [ - "ppv-lite86", + "chacha20", + "getrandom", "rand_core", ] [[package]] name = "rand_core" -version = "0.9.3" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" -dependencies = [ - "getrandom", -] +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" [[package]] name = "rawpointer" @@ -604,9 +660,9 @@ checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" [[package]] name = "rayon" -version = "1.11.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" dependencies = [ "either", "rayon-core", @@ -678,6 +734,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.228" @@ -740,9 +802,9 @@ dependencies = [ [[package]] name = "target-lexicon" -version = "0.13.2" +version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e502f78cdbb8ba4718f566c418c52bc729126ffd16baee5baa718cf25dd5a69a" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" [[package]] name = "tinytemplate" @@ -761,10 +823,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] -name = "unindent" -version = "0.2.3" +name = "unicode-xid" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7de7d73e1754487cb58364ee906a499937a0dfabd86bcb980fa99ec8c8fa2ce" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" [[package]] name = "walkdir" @@ -777,21 +839,21 @@ dependencies = [ ] [[package]] -name = "wasi" -version = "0.14.7+wasi-0.2.4" +name = "wasip2" +version = "1.0.1+wasi-0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "883478de20367e224c0090af9cf5f9fa85bed63a95c1abf3afc5c083ebc06e8c" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" dependencies = [ - "wasip2", + "wit-bindgen 0.46.0", ] [[package]] -name = "wasip2" -version = "1.0.1+wasi-0.2.4" +name = "wasip3" +version = "0.4.0+wasi-0.3.0-rc-2026-01-06" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" dependencies = [ - "wit-bindgen", + "wit-bindgen 0.51.0", ] [[package]] @@ -853,6 +915,40 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap", + "semver", +] + [[package]] name = "web-sys" version = "0.3.81" @@ -916,21 +1012,89 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" [[package]] -name = "zerocopy" -version = "0.8.27" +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +dependencies = [ + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" dependencies = [ - "zerocopy-derive", + "anyhow", + "heck", + "wit-parser", ] [[package]] -name = "zerocopy-derive" -version = "0.8.27" +name = "wit-bindgen-rust" +version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", "proc-macro2", "quote", "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", ] diff --git a/Cargo.toml b/Cargo.toml index 18d690e..fba6697 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "interpn" -version = "0.11.0" +version = "0.11.1" edition = "2024" rust-version = "1.87" # 2025-05-15 authors = ["James Logan "] @@ -21,20 +21,20 @@ num-traits = { version = "^0.2.19", default-features = false, features = ["libm" crunchy = { version = "^0.2.4", default-features = false } # Parallelism -rayon = { version = "^1.11.0", optional = true } +rayon = { version = "^1.12.0", optional = true } num_cpus = { version = "^1.17.0", optional = true } # Python bindings -pyo3 = { version = "0.27.2", features = ["extension-module", "abi3-py310", "generate-import-lib"], optional = true } -numpy = { version = "0.27.1", optional = true } +pyo3 = { version = "0.28.3", features = ["extension-module", "abi3-py310", "generate-import-lib"], optional = true } +numpy = { version = "0.28.0", optional = true } # Test-only utils itertools = { version = "0.14.0", optional = true } [dev-dependencies] -rand = "0.9.2" -criterion = "0.8.1" +rand = "0.10.1" +criterion = "0.8.2" ndarray = "0.17.2" [features] @@ -47,7 +47,7 @@ par = ["std", "rayon", "num_cpus"] [profile.release] opt-level = 3 -codegen-units = 1 +codegen-units = 4 lto = true strip = true overflow-checks = true diff --git a/README.md b/README.md index 8f62d46..1c972b2 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,8 @@ Available as a rust crate and python library. |-----------------------------------|-----------------|---------------------|-----------------------| ------------------ | | Nearest-Neighbor | ✅ | ✅ | ✅ | ✅ | | Linear | ✅ | ✅ | ✅ | ✅ | -| Cubic | ✅ | ✅ | ✅ | ✅ | +| Cubic Hermite | ✅ | ✅ | ✅ | ✅ | +| Cubic B-spline | ✅ | ✅ | ✅ | ✅ | The methods provided here, while more limited in scope than scipy's, diff --git a/benches/bench.rs b/benches/bench.rs index 72daf6a..032aad7 100644 --- a/benches/bench.rs +++ b/benches/bench.rs @@ -3,8 +3,8 @@ use criterion::*; use gridgen::*; use interpn::{ - Linear1D, LinearHoldLast1D, MultilinearRegular, NearestRectilinear, NearestRegular, - RectilinearGrid1D, RegularGrid1D, multicubic, multilinear, nearest, + Linear1D, LinearHoldLast1D, MultilinearRegular, RectilinearGrid1D, RegularGrid1D, multibspline, + multicubic, multilinear, nearest, one_dim::{ Interp1D, hold::{Left1D, Nearest1D}, @@ -13,13 +13,8 @@ use interpn::{ use std::hint::black_box; -enum Kind { - Interp, - Extrap, -} - macro_rules! bench_interp_specific { - ($group:ident, $ndims:expr, $gridsize:expr, $size:expr, $kind:expr) => { + ($group:ident, $ndims:expr, $gridsize:expr, $size:expr) => { $group.throughput(Throughput::Elements(*$size as u64)); // $group.plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic)); let scan_or_shuffle = "Shuffled Order"; @@ -41,12 +36,9 @@ macro_rules! bench_interp_specific { // Observation grid let m: usize = ((size as f64).powf(1.0 / ($ndims as f64)) + 2.0) as usize; - let gridobs_t = match $kind { - Kind::Interp => gen_interp_obs_grid(&grids, m, true), - Kind::Extrap => gen_extrap_obs_grid(&grids, m, true), - }; + let gridobs_t = gen_interp_obs_grid(&grids, m, true); let obs: Vec<&[f64]> = gridobs_t.iter().map(|x| &x[..size]).collect(); - let obs = (&obs[..]).try_into().unwrap(); + let obs: &[&[f64]; $ndims] = (&obs[..]).try_into().unwrap(); let mut out = vec![0.0; size]; let dims = [$gridsize; $ndims]; @@ -80,11 +72,9 @@ macro_rules! bench_interp_specific { // Observation grid let m: usize = ((size as f64).powf(1.0 / ($ndims as f64)) + 2.0) as usize; - let gridobs_t = match $kind { - Kind::Interp => gen_interp_obs_grid(&grids, m, true), - Kind::Extrap => gen_extrap_obs_grid(&grids, m, true), - }; + let gridobs_t = gen_interp_obs_grid(&grids, m, true); let obs: Vec<&[f64]> = gridobs_t.iter().map(|x| &x[..size]).collect(); + let obs: &[&[f64]; $ndims] = (&obs[..]).try_into().unwrap(); let mut out = vec![0.0; size]; let dims = [$gridsize; $ndims]; @@ -95,13 +85,110 @@ macro_rules! bench_interp_specific { b.iter(|| { black_box({ - multilinear::regular::interpn(&dims, &starts, &steps, &z, &obs, &mut out) + multilinear::regular::interpn(&dims, &starts, &steps, &z, obs, &mut out) .unwrap() }) }); }, ); + $group.bench_with_input( + BenchmarkId::new( + format!( + "Bspline Regular {}x{}D Precomputed Coeffs, {}", + $gridsize, $ndims, scan_or_shuffle + ), + $size, + ), + $size, + |b, &size| { + // Interpolation grid + let (grids, z) = gen_grid($ndims, $gridsize, 0.0); + + // Observation grid + let m: usize = ((size as f64).powf(1.0 / ($ndims as f64)) + 2.0) as usize; + let gridobs_t = gen_interp_obs_grid(&grids, m, true); + let obs: Vec<&[f64]> = gridobs_t.iter().map(|x| &x[..size]).collect(); + let obs: &[&[f64]; $ndims] = (&obs[..]).try_into().unwrap(); + let mut out = vec![0.0; size]; + + let dims = [$gridsize; $ndims]; + let mut starts = [0.0; $ndims]; + let mut steps = [0.0; $ndims]; + (0..$ndims).for_each(|i| starts[i] = grids[i][0]); + (0..$ndims).for_each(|i| steps[i] = grids[i][1] - grids[i][0]); + + let coeff_len = + multibspline::MultiBsplineRegular::::coeff_storage_len(dims); + let scratch_len = + multibspline::MultiBsplineRegular::::construction_scratch_len( + dims, + ); + let mut coeffs = vec![0.0; coeff_len]; + let mut scratch = vec![0.0; scratch_len]; + multibspline::regular::coefficients(dims, &z, &mut coeffs, &mut scratch).unwrap(); + let interpolator: multibspline::MultiBsplineRegular<'_, _, $ndims> = + multibspline::MultiBsplineRegular::new(dims, starts, steps, &coeffs, false) + .unwrap(); + + b.iter(|| black_box({ interpolator.interp(obs, &mut out).unwrap() })); + }, + ); + + $group.bench_with_input( + BenchmarkId::new( + format!( + "Bspline Regular {}x{}D With Construction, {}", + $gridsize, $ndims, scan_or_shuffle + ), + $size, + ), + $size, + |b, &size| { + // Interpolation grid + let (grids, z) = gen_grid($ndims, $gridsize, 0.0); + + // Observation grid + let m: usize = ((size as f64).powf(1.0 / ($ndims as f64)) + 2.0) as usize; + let gridobs_t = gen_interp_obs_grid(&grids, m, true); + let obs: Vec<&[f64]> = gridobs_t.iter().map(|x| &x[..size]).collect(); + let obs: &[&[f64]; $ndims] = (&obs[..]).try_into().unwrap(); + let mut out = vec![0.0; size]; + + let dims = [$gridsize; $ndims]; + let mut starts = [0.0; $ndims]; + let mut steps = [0.0; $ndims]; + (0..$ndims).for_each(|i| starts[i] = grids[i][0]); + (0..$ndims).for_each(|i| steps[i] = grids[i][1] - grids[i][0]); + + let coeff_len = + multibspline::MultiBsplineRegular::::coeff_storage_len(dims); + let scratch_len = + multibspline::MultiBsplineRegular::::construction_scratch_len( + dims, + ); + let mut coeffs = vec![0.0; coeff_len]; + let mut scratch = vec![0.0; scratch_len]; + + b.iter(|| { + black_box({ + let interpolator: multibspline::MultiBsplineRegular<'_, _, $ndims> = + multibspline::MultiBsplineRegular::from_values_with_workspace( + dims, + starts, + steps, + &z, + &mut coeffs, + &mut scratch, + false, + ) + .unwrap(); + interpolator.interp(obs, &mut out).unwrap() + }) + }); + }, + ); + $group.bench_with_input( BenchmarkId::new( format!( @@ -117,10 +204,7 @@ macro_rules! bench_interp_specific { // Observation grid let m: usize = ((size as f64).powf(1.0 / ($ndims as f64)) + 2.0) as usize; - let gridobs_t = match $kind { - Kind::Interp => gen_interp_obs_grid(&grids, m, true), - Kind::Extrap => gen_extrap_obs_grid(&grids, m, true), - }; + let gridobs_t = gen_interp_obs_grid(&grids, m, true); let obs: Vec<&[f64]> = gridobs_t.iter().map(|x| &x[..size]).collect(); let mut out = vec![0.0; size]; @@ -147,10 +231,7 @@ macro_rules! bench_interp_specific { |b, &size| { let (grids, z) = gen_grid($ndims, $gridsize, 0.0); let m: usize = ((size as f64).powf(1.0 / ($ndims as f64)) + 2.0) as usize; - let gridobs_t = match $kind { - Kind::Interp => gen_interp_obs_grid(&grids, m, true), - Kind::Extrap => gen_extrap_obs_grid(&grids, m, true), - }; + let gridobs_t = gen_interp_obs_grid(&grids, m, true); let obs: Vec<&[f64]> = gridobs_t.iter().map(|x| &x[..size]).collect(); let mut out = vec![0.0; size]; @@ -182,10 +263,7 @@ macro_rules! bench_interp_specific { let (grids, z) = gen_grid($ndims, $gridsize, 1e-3); let m: usize = ((size as f64).powf(1.0 / ($ndims as f64)) + 2.0) as usize; - let gridobs_t = match $kind { - Kind::Interp => gen_interp_obs_grid(&grids, m, true), - Kind::Extrap => gen_extrap_obs_grid(&grids, m, true), - }; + let gridobs_t = gen_interp_obs_grid(&grids, m, true); let obs: Vec<&[f64]> = gridobs_t.iter().map(|x| &x[..size]).collect(); let mut out = vec![0.0; size]; @@ -214,10 +292,7 @@ macro_rules! bench_interp_specific { // Observation grid let m: usize = ((size as f64).powf(1.0 / ($ndims as f64)) + 2.0) as usize; - let gridobs_t = match $kind { - Kind::Interp => gen_interp_obs_grid(&grids, m, true), - Kind::Extrap => gen_extrap_obs_grid(&grids, m, true), - }; + let gridobs_t = gen_interp_obs_grid(&grids, m, true); let obs: Vec<&[f64]> = gridobs_t.iter().map(|x| &x[..size]).collect(); let mut out = vec![0.0; size]; @@ -253,10 +328,7 @@ macro_rules! bench_interp_specific { // Observation grid let m: usize = ((size as f64).powf(1.0 / ($ndims as f64)) + 2.0) as usize; - let gridobs_t = match $kind { - Kind::Interp => gen_interp_obs_grid(&grids, m, true), - Kind::Extrap => gen_extrap_obs_grid(&grids, m, true), - }; + let gridobs_t = gen_interp_obs_grid(&grids, m, true); let obs: Vec<&[f64]> = gridobs_t.iter().map(|x| &x[..size]).collect(); let mut out = vec![0.0; size]; @@ -282,7 +354,7 @@ fn bench_interp(c: &mut Criterion) { let mut group = c.benchmark_group(format!("Interp_1D_Shuffled_{gridsize}-grid")); for size in [1, 100, 1_000_000].iter() { group.throughput(Throughput::Elements(*size as u64)); - bench_interp_specific!(group, 1, gridsize, size, Kind::Interp); + bench_interp_specific!(group, 1, gridsize, size); } group.finish(); } @@ -291,7 +363,7 @@ fn bench_interp(c: &mut Criterion) { let mut group = c.benchmark_group(format!("Interp_2D_Shuffled_{gridsize}-grid")); for size in [1, 100, 1_000_000].iter() { group.throughput(Throughput::Elements(*size as u64)); - bench_interp_specific!(group, 2, gridsize, size, Kind::Interp); + bench_interp_specific!(group, 2, gridsize, size); } group.finish(); } @@ -300,14 +372,13 @@ fn bench_interp(c: &mut Criterion) { let mut group = c.benchmark_group(format!("Interp_3D_Shuffled_{gridsize}-grid")); for size in [1, 100, 1_000_000].iter() { group.throughput(Throughput::Elements(*size as u64)); - bench_interp_specific!(group, 3, gridsize, size, Kind::Interp); + bench_interp_specific!(group, 3, gridsize, size); } group.finish(); } // 1D specialized linear rectilinear for gridsize in [10, 1000] { - let kind = Kind::Interp; let ndims = 1; let mut group = c.benchmark_group(format!("Interp_1D_Special_{gridsize}-grid")); for size in [1, 100, 1_000_000].iter() { @@ -322,10 +393,7 @@ fn bench_interp(c: &mut Criterion) { // Observation grid let m: usize = ((size as f64).powf(1.0 / (ndims as f64)) + 2.0) as usize; - let gridobs_t = match kind { - Kind::Interp => gen_interp_obs_grid(&grids, m, true), - Kind::Extrap => gen_extrap_obs_grid(&grids, m, true), - }; + let gridobs_t = gen_interp_obs_grid(&grids, m, true); let obs: Vec<&[f64]> = gridobs_t.iter().map(|x| &x[..size]).collect(); let mut out = vec![0.0; size]; @@ -343,7 +411,6 @@ fn bench_interp(c: &mut Criterion) { // 1D specialized linear regular for gridsize in [10, 1000] { - let kind = Kind::Interp; let ndims = 1; let mut group = c.benchmark_group(format!("Interp_1D_Special_{gridsize}-grid")); for size in [1, 100, 1_000_000].iter() { @@ -359,10 +426,7 @@ fn bench_interp(c: &mut Criterion) { // Observation grid let m: usize = ((size as f64).powf(1.0 / (ndims as f64)) + 2.0) as usize; - let gridobs_t = match kind { - Kind::Interp => gen_interp_obs_grid(&grids, m, true), - Kind::Extrap => gen_extrap_obs_grid(&grids, m, true), - }; + let gridobs_t = gen_interp_obs_grid(&grids, m, true); let obs: Vec<&[f64]> = gridobs_t.iter().map(|x| &x[..size]).collect(); let mut out = vec![0.0; size]; @@ -380,7 +444,6 @@ fn bench_interp(c: &mut Criterion) { // 1D specialized linear hold-last regular for gridsize in [10, 1000] { - let kind = Kind::Interp; let ndims = 1; let mut group = c.benchmark_group(format!("Interp_1D_Special_{gridsize}-grid")); for size in [1, 100, 1_000_000].iter() { @@ -396,10 +459,7 @@ fn bench_interp(c: &mut Criterion) { // Observation grid let m: usize = ((size as f64).powf(1.0 / (ndims as f64)) + 2.0) as usize; - let gridobs_t = match kind { - Kind::Interp => gen_interp_obs_grid(&grids, m, true), - Kind::Extrap => gen_extrap_obs_grid(&grids, m, true), - }; + let gridobs_t = gen_interp_obs_grid(&grids, m, true); let obs: Vec<&[f64]> = gridobs_t.iter().map(|x| &x[..size]).collect(); let mut out = vec![0.0; size]; @@ -417,7 +477,6 @@ fn bench_interp(c: &mut Criterion) { // 1D specialized hold-left for gridsize in [10, 1000] { - let kind = Kind::Interp; let ndims = 1; let mut group = c.benchmark_group(format!("Interp_1D_Special_{gridsize}-grid")); for size in [1, 100, 1_000_000].iter() { @@ -433,10 +492,7 @@ fn bench_interp(c: &mut Criterion) { // Observation grid let m: usize = ((size as f64).powf(1.0 / (ndims as f64)) + 2.0) as usize; - let gridobs_t = match kind { - Kind::Interp => gen_interp_obs_grid(&grids, m, true), - Kind::Extrap => gen_extrap_obs_grid(&grids, m, true), - }; + let gridobs_t = gen_interp_obs_grid(&grids, m, true); let obs: Vec<&[f64]> = gridobs_t.iter().map(|x| &x[..size]).collect(); let mut out = vec![0.0; size]; @@ -454,7 +510,6 @@ fn bench_interp(c: &mut Criterion) { // 1D specialized nearest for gridsize in [10, 1000] { - let kind = Kind::Interp; let ndims = 1; let mut group = c.benchmark_group(format!("Interp_1D_Special_{gridsize}-grid")); for size in [1, 100, 1_000_000].iter() { @@ -470,10 +525,7 @@ fn bench_interp(c: &mut Criterion) { // Observation grid let m: usize = ((size as f64).powf(1.0 / (ndims as f64)) + 2.0) as usize; - let gridobs_t = match kind { - Kind::Interp => gen_interp_obs_grid(&grids, m, true), - Kind::Extrap => gen_extrap_obs_grid(&grids, m, true), - }; + let gridobs_t = gen_interp_obs_grid(&grids, m, true); let obs: Vec<&[f64]> = gridobs_t.iter().map(|x| &x[..size]).collect(); let mut out = vec![0.0; size]; @@ -494,7 +546,7 @@ criterion_group!(benches_interp, bench_interp); criterion_main!(benches_interp); mod randn { - use rand::Rng; + use rand::RngExt; use rand::SeedableRng; use rand::distr::StandardUniform; use rand::rngs::StdRng; @@ -573,35 +625,4 @@ mod gridgen { // let xobsslice: Vec<&[f64]> = gridobs_t.iter().map(|x| &x[..size]).collect(); gridobs_t } - - // Generate a set of observation points that are entirely outside - // the interpolation grid on every axis (meaning, in a corner region, - // the worst case for perf). - // - // `size` is the size per grid, so the total number of points will be size.pow(ndims). - pub fn gen_extrap_obs_grid( - grids: &Vec>, - size: usize, - _shuffled: bool, - ) -> Vec> { - let ndims = grids.len(); - - let xobs: Vec> = (0..ndims) - .map(|i| { - linspace( - grids[i].last().unwrap() + 1.0, - grids[i].last().unwrap() + 2.0, - size, - ) - }) - .collect(); - let gridobs = meshgrid((0..ndims).map(|i| &xobs[i]).collect()); - let gridobs_t: Vec> = (0..ndims) - .map(|i| gridobs.iter().map(|x| x[i]).collect()) - .collect(); // transpose - - // unpack like: - // let obs: Vec<&[f64]> = gridobs_t.iter().map(|x| &x[..size]).collect(); - gridobs_t - } } diff --git a/benches/bench_cpu.py b/benches/bench_cpu.py index b5fcdc3..c616200 100644 --- a/benches/bench_cpu.py +++ b/benches/bench_cpu.py @@ -12,6 +12,8 @@ from plotly.subplots import make_subplots from interpn import ( + MultiBsplineRegular, + MultiBsplineRectilinear, MultilinearRectilinear, MultilinearRegular, MulticubicRegular, @@ -30,6 +32,12 @@ TARGET_SAMPLE_SECONDS = 2.0 MAX_TIMER_LOOPS = 1_000_000_000 +MULTIBSPLINE_LABEL = "InterpN MultiBsplineRegular" +MULTIBSPLINE_RECTILINEAR_LABEL = "InterpN MultiBsplineRectilinear" +MULTICUBIC_LABELS = { + "InterpN MulticubicRegular", + "InterpN MulticubicRectilinear", +} def average_call_time( @@ -56,12 +64,33 @@ def average_call_time( "cubic": "#ff7f0e", "nearest": "#2ca02c", } +THREAD_SPEEDUP_METHODS = ["linear", "cubic", "nearest"] def _normalized_line_style(index: int) -> str: return DASH_STYLES[index % len(DASH_STYLES)] +def _normalized_legend_name(label: str) -> str: + if label.startswith("Scipy RegularGridInterpolator"): + return "Scipy" + if label in MULTICUBIC_LABELS: + return "InterpN Cubic" + if label in {MULTIBSPLINE_LABEL, MULTIBSPLINE_RECTILINEAR_LABEL}: + return "InterpN B-Spline" + if label.startswith("InterpN"): + return "InterpN" + return label + + +def _regular_fill_candidate(name: str, kind: str) -> bool: + if kind == "Linear": + return name == "InterpN MultilinearRegular" + if kind == "Cubic": + return name in {"InterpN MulticubicRegular", MULTIBSPLINE_LABEL} + return False + + def fill_between( fig: go.Figure, *, @@ -116,7 +145,7 @@ def _plot_normalized_vs_nobs( x_vals = np.array(ns[:min_len]) ratios = values[:min_len] / baseline_arr[:min_len] is_baseline = label.startswith("Scipy RegularGridInterpolator") - legend_name = "Scipy" if is_baseline else "InterpN" + legend_name = _normalized_legend_name(label) showlegend = True for trace in fig.data: if trace.name == legend_name: @@ -237,20 +266,21 @@ def _plot_throughput_vs_dims( interpn_series = [ values for name, values in throughputs.items() - if name.startswith("InterpN") and f"Multi{kind.lower()}" in name and values + if _regular_fill_candidate(name, kind) and values ] - v = max(interpn_series, key=lambda vals: vals[-1]) - - baseline_norm = np.array(baseline_vals) / max_throughput - fill_between( - fig, - x=np.array(ndims_to_test), - upper=np.array(v) / max_throughput, - lower=baseline_norm, - row=row, - col=1, - ) + if baseline_vals and interpn_series: + v = max(interpn_series, key=lambda vals: vals[-1]) + fill_len = min(len(v), len(baseline_vals), len(ndims_to_test)) + baseline_norm = np.array(baseline_vals[:fill_len]) / max_throughput + fill_between( + fig, + x=np.array(ndims_to_test[:fill_len]), + upper=np.array(v[:fill_len]) / max_throughput, + lower=baseline_norm, + row=row, + col=1, + ) # Lines for idx, (label, values) in enumerate(series): @@ -269,7 +299,7 @@ def _plot_throughput_vs_dims( line=dict(color="black", width=2, dash=_normalized_line_style(idx)), marker=dict(symbol="square" if is_baseline else "circle", size=8), opacity=1.0 if is_baseline else 1.0, - name=label, + name=_normalized_legend_name(label), showlegend=True, legendgroup=kind, legendgrouptitle_text=kind, @@ -391,12 +421,10 @@ def _plot_speedup_vs_dims( x=x_vals, y=speedup, mode="lines", - line=dict(color="black", width=3), + line=dict(color="black", width=3, dash=_normalized_line_style(idx)), marker=dict(symbol="circle", size=8), - name=name, - showlegend=False, - # legendgroup=kind, - # legendgrouptitle_text=kind, + name=_normalized_legend_name(name), + showlegend=True, ), row=1, col=1, @@ -450,14 +478,14 @@ def _plot_speedup_vs_dims( yanchor="top", ), height=450, - margin=dict(t=60, l=60, r=20, b=90), - # legend=dict( - # orientation="v", - # yanchor="top", - # y=1.0, - # x=1.02, - # xanchor="left", - # ), + margin=dict(t=60, l=60, r=220, b=90), + legend=dict( + orientation="v", + yanchor="top", + y=1.0, + x=1.02, + xanchor="left", + ), plot_bgcolor="rgba(0,0,0,0)", paper_bgcolor="rgba(0,0,0,0)", font=dict(color="black"), @@ -476,10 +504,11 @@ def _thread_counts() -> list[int]: max_threads = os.cpu_count() or 1 max_threads = max(int(max_threads / 2), 1) # Real threads, not hyperthreads counts = [] - threads = 1 - while threads < max_threads: + for exponent in range(max_threads.bit_length()): + threads = 1 << exponent + if threads >= max_threads: + break counts.append(threads) - threads *= 2 counts.append(max_threads) return sorted(set(counts)) @@ -493,21 +522,20 @@ def _plot_speedup_vs_threads( ) -> None: fig = make_subplots(rows=1, cols=1) dash_styles = [ - _normalized_line_style(i) - for i in range(len(["linear", "cubic", "nearest"]) * 2) + _normalized_line_style(i) for i in range(len(THREAD_SPEEDUP_METHODS) * 2) ] all_values = [] thread_arr = np.array(thread_counts) - series: list[tuple[str, np.ndarray]] = [] + series: list[tuple[str, str, np.ndarray]] = [] for grid_kind in ["regular", "rectilinear"]: - for method in ["linear", "cubic", "nearest"]: + for method in THREAD_SPEEDUP_METHODS: values = speedups[grid_kind].get(method) if not values: continue values_arr = np.array(values, dtype=float) all_values.append(values_arr) - series.append((f"{method.title()} {grid_kind}", values_arr)) - for _, values_arr in series: + series.append((f"{method.title()} {grid_kind}", method, values_arr)) + for _, _, values_arr in series: ones = np.ones_like(values_arr) fill_between( fig, @@ -518,7 +546,7 @@ def _plot_speedup_vs_threads( col=1, fillcolor="rgba(139, 196, 59, 0.25)", ) - for idx, (label, values_arr) in enumerate(series): + for idx, (label, method, values_arr) in enumerate(series): fig.add_trace( go.Scatter( x=thread_arr, @@ -526,12 +554,12 @@ def _plot_speedup_vs_threads( mode="lines+markers", name=label, line=dict( - color="black", + color=THREAD_SPEEDUP_COLORS[method], width=2, dash=dash_styles[idx], ), - marker=dict(size=7, color="black"), - showlegend=False, + marker=dict(size=7, color=THREAD_SPEEDUP_COLORS[method]), + showlegend=True, ), row=1, col=1, @@ -582,8 +610,15 @@ def _plot_speedup_vs_threads( yanchor="top", ), height=430, - margin=dict(t=70, l=60, r=40, b=80), - showlegend=False, + margin=dict(t=70, l=60, r=170, b=80), + showlegend=True, + legend=dict( + orientation="v", + yanchor="top", + y=1.0, + x=1.02, + xanchor="left", + ), plot_bgcolor="rgba(0,0,0,0)", paper_bgcolor="rgba(0,0,0,0)", font=dict(color="black"), @@ -633,7 +668,7 @@ def make_grids(kind: str) -> list[NDArray]: ) out = np.zeros_like(obs[0]) - for method in ["linear", "cubic", "nearest"]: + for method in THREAD_SPEEDUP_METHODS: timings = [] for threads in thread_counts: timed = average_call_time( @@ -699,6 +734,12 @@ def bench_4_dims_1_obs(): cubic_regular_interpn = MulticubicRegular.new( dims, starts, steps, zgrid, linearize_extrapolation=True ) + bspline_regular_interpn = MultiBsplineRegular.new( + dims, starts, steps, zgrid, linearize_extrapolation=True + ) + bspline_rectilinear_interpn = MultiBsplineRectilinear.new( + grids, zgrid, linearize_extrapolation=True + ) cubic_rectilinear_interpn = MulticubicRectilinear.new( grids, zgrid, linearize_extrapolation=True ) @@ -712,6 +753,10 @@ def bench_4_dims_1_obs(): "InterpN MultilinearRegular": lambda p: regular_interpn.eval(p, out), "InterpN MultilinearRectilinear": lambda p: rectilinear_interpn.eval(p, out), "InterpN MulticubicRegular": lambda p: cubic_regular_interpn.eval(p, out), + MULTIBSPLINE_LABEL: lambda p: bspline_regular_interpn.eval(p, out), + MULTIBSPLINE_RECTILINEAR_LABEL: lambda p: bspline_rectilinear_interpn.eval( + p, out + ), "InterpN MulticubicRectilinear": lambda p: cubic_rectilinear_interpn.eval( p, out ), @@ -731,6 +776,8 @@ def bench_4_dims_1_obs(): "InterpN MultilinearRegular": points_interpn, "InterpN MultilinearRectilinear": points_interpn, "InterpN MulticubicRegular": points_interpn, + MULTIBSPLINE_LABEL: points_interpn, + MULTIBSPLINE_RECTILINEAR_LABEL: points_interpn, "InterpN MulticubicRectilinear": points_interpn, "InterpN NearestRegular": points_interpn, "InterpN NearestRectilinear": points_interpn, @@ -761,6 +808,8 @@ def bench_4_dims_1_obs(): "InterpN MultilinearRegular": points_interpn1, "InterpN MultilinearRectilinear": points_interpn1, "InterpN MulticubicRegular": points_interpn1, + MULTIBSPLINE_LABEL: points_interpn1, + MULTIBSPLINE_RECTILINEAR_LABEL: points_interpn1, "InterpN MulticubicRectilinear": points_interpn1, "InterpN NearestRegular": points_interpn1, "InterpN NearestRectilinear": points_interpn1, @@ -791,6 +840,8 @@ def bench_4_dims_1_obs(): "InterpN MultilinearRegular": points_interpn2, "InterpN MultilinearRectilinear": points_interpn2, "InterpN MulticubicRegular": points_interpn2, + MULTIBSPLINE_LABEL: points_interpn2, + MULTIBSPLINE_RECTILINEAR_LABEL: points_interpn2, "InterpN MulticubicRectilinear": points_interpn2, "InterpN NearestRegular": points_interpn2, "InterpN NearestRectilinear": points_interpn2, @@ -824,6 +875,8 @@ def bench_4_dims_1_obs(): "InterpN MultilinearRegular": points_interpn3, "InterpN MultilinearRectilinear": points_interpn3, "InterpN MulticubicRegular": points_interpn3, + MULTIBSPLINE_LABEL: points_interpn3, + MULTIBSPLINE_RECTILINEAR_LABEL: points_interpn3, "InterpN MulticubicRectilinear": points_interpn3, "InterpN NearestRegular": points_interpn3, "InterpN NearestRectilinear": points_interpn3, @@ -871,6 +924,12 @@ def bench_3_dims_n_obs_unordered(): cubic_regular_interpn = MulticubicRegular.new( dims, starts, steps, zgrid, linearize_extrapolation=True ) + bspline_regular_interpn = MultiBsplineRegular.new( + dims, starts, steps, zgrid, linearize_extrapolation=True + ) + bspline_rectilinear_interpn = MultiBsplineRectilinear.new( + grids, zgrid, linearize_extrapolation=True + ) cubic_rectilinear_interpn = MulticubicRectilinear.new( grids, zgrid, linearize_extrapolation=True ) @@ -883,6 +942,8 @@ def bench_3_dims_n_obs_unordered(): "InterpN MultilinearRegular": [], "InterpN MultilinearRectilinear": [], "InterpN MulticubicRegular": [], + MULTIBSPLINE_LABEL: [], + MULTIBSPLINE_RECTILINEAR_LABEL: [], "InterpN MulticubicRectilinear": [], "InterpN NearestRegular": [], "InterpN NearestRectilinear": [], @@ -921,6 +982,10 @@ def bench_3_dims_n_obs_unordered(): "InterpN MulticubicRegular": lambda p: cubic_regular_interpn.eval( p, out ), + MULTIBSPLINE_LABEL: lambda p: bspline_regular_interpn.eval(p, out), + MULTIBSPLINE_RECTILINEAR_LABEL: ( + lambda p: bspline_rectilinear_interpn.eval(p, out) + ), "InterpN MulticubicRectilinear": lambda p: cubic_rectilinear_interpn.eval( p, out ), @@ -941,6 +1006,8 @@ def bench_3_dims_n_obs_unordered(): "InterpN MultilinearRegular": points_interpn, "InterpN MultilinearRectilinear": points_interpn, "InterpN MulticubicRegular": points_interpn, + MULTIBSPLINE_LABEL: points_interpn, + MULTIBSPLINE_RECTILINEAR_LABEL: points_interpn, "InterpN MulticubicRectilinear": points_interpn, "InterpN NearestRegular": points_interpn, "InterpN NearestRectilinear": points_interpn, @@ -962,6 +1029,8 @@ def bench_3_dims_n_obs_unordered(): "InterpN MultilinearRegular": "Linear", "InterpN MultilinearRectilinear": "Linear", "InterpN MulticubicRegular": "Cubic", + MULTIBSPLINE_LABEL: "Cubic", + MULTIBSPLINE_RECTILINEAR_LABEL: "Cubic", "InterpN MulticubicRectilinear": "Cubic", "InterpN NearestRegular": "Linear", "InterpN NearestRectilinear": "Linear", @@ -1011,6 +1080,12 @@ def bench_4_dims_n_obs_unordered(): cubic_regular_interpn = MulticubicRegular.new( dims, starts, steps, zgrid, linearize_extrapolation=True ) + bspline_regular_interpn = MultiBsplineRegular.new( + dims, starts, steps, zgrid, linearize_extrapolation=True + ) + bspline_rectilinear_interpn = MultiBsplineRectilinear.new( + grids, zgrid, linearize_extrapolation=True + ) cubic_rectilinear_interpn = MulticubicRectilinear.new( grids, zgrid, linearize_extrapolation=True ) @@ -1023,6 +1098,8 @@ def bench_4_dims_n_obs_unordered(): "InterpN MultilinearRegular": [], "InterpN MultilinearRectilinear": [], "InterpN MulticubicRegular": [], + MULTIBSPLINE_LABEL: [], + MULTIBSPLINE_RECTILINEAR_LABEL: [], "InterpN MulticubicRectilinear": [], "InterpN NearestRegular": [], "InterpN NearestRectilinear": [], @@ -1059,6 +1136,10 @@ def bench_4_dims_n_obs_unordered(): "InterpN MulticubicRegular": lambda p: cubic_regular_interpn.eval( p, out ), + MULTIBSPLINE_LABEL: lambda p: bspline_regular_interpn.eval(p, out), + MULTIBSPLINE_RECTILINEAR_LABEL: ( + lambda p: bspline_rectilinear_interpn.eval(p, out) + ), "InterpN MulticubicRectilinear": lambda p: cubic_rectilinear_interpn.eval( p, out ), @@ -1079,6 +1160,8 @@ def bench_4_dims_n_obs_unordered(): "InterpN MultilinearRegular": points_interpn, "InterpN MultilinearRectilinear": points_interpn, "InterpN MulticubicRegular": points_interpn, + MULTIBSPLINE_LABEL: points_interpn, + MULTIBSPLINE_RECTILINEAR_LABEL: points_interpn, "InterpN MulticubicRectilinear": points_interpn, "InterpN NearestRegular": points_interpn, "InterpN NearestRectilinear": points_interpn, @@ -1098,6 +1181,8 @@ def bench_4_dims_n_obs_unordered(): "InterpN MultilinearRegular": "Linear", "InterpN MultilinearRectilinear": "Linear", "InterpN MulticubicRegular": "Cubic", + MULTIBSPLINE_LABEL: "Cubic", + MULTIBSPLINE_RECTILINEAR_LABEL: "Cubic", "InterpN MulticubicRectilinear": "Cubic", "InterpN NearestRegular": "Linear", "InterpN NearestRectilinear": "Linear", @@ -1129,6 +1214,8 @@ def bench_throughput_vs_dims(): "InterpN MultilinearRegular": [], "InterpN MultilinearRectilinear": [], "InterpN MulticubicRegular": [], + MULTIBSPLINE_LABEL: [], + MULTIBSPLINE_RECTILINEAR_LABEL: [], "InterpN MulticubicRectilinear": [], "InterpN NearestRegular": [], "InterpN NearestRectilinear": [], @@ -1159,6 +1246,12 @@ def bench_throughput_vs_dims(): cubic_regular_interpn = MulticubicRegular.new( dims, starts, steps, zgrid, linearize_extrapolation=True ) + bspline_regular_interpn = MultiBsplineRegular.new( + dims, starts, steps, zgrid, linearize_extrapolation=True + ) + bspline_rectilinear_interpn = MultiBsplineRectilinear.new( + grids, zgrid, linearize_extrapolation=True + ) cubic_rectilinear_interpn = MulticubicRectilinear.new( grids, zgrid, linearize_extrapolation=True ) @@ -1190,6 +1283,11 @@ def bench_throughput_vs_dims(): ), "InterpN MulticubicRegular": lambda p, interp=cubic_regular_interpn: interp.eval(p, out), + MULTIBSPLINE_LABEL: lambda p, + interp=bspline_regular_interpn: interp.eval(p, out), + MULTIBSPLINE_RECTILINEAR_LABEL: ( + lambda p, interp=bspline_rectilinear_interpn: interp.eval(p, out) + ), "InterpN MulticubicRectilinear": ( lambda p, interp=cubic_rectilinear_interpn: interp.eval(p, out) ), @@ -1221,6 +1319,8 @@ def bench_throughput_vs_dims(): "InterpN MultilinearRegular": points_interpn, "InterpN MultilinearRectilinear": points_interpn, "InterpN MulticubicRegular": points_interpn, + MULTIBSPLINE_LABEL: points_interpn, + MULTIBSPLINE_RECTILINEAR_LABEL: points_interpn, "InterpN MulticubicRectilinear": points_interpn, "InterpN NearestRegular": points_interpn, "InterpN NearestRectilinear": points_interpn, @@ -1246,6 +1346,8 @@ def bench_throughput_vs_dims(): "InterpN MultilinearRegular": "Linear", "InterpN MultilinearRectilinear": "Linear", "InterpN MulticubicRegular": "Cubic", + MULTIBSPLINE_LABEL: "Cubic", + MULTIBSPLINE_RECTILINEAR_LABEL: "Cubic", "InterpN MulticubicRectilinear": "Cubic", "InterpN NearestRegular": "Linear", "InterpN NearestRectilinear": "Linear", diff --git a/benches/bench_mem.py b/benches/bench_mem.py index b80c7dc..c272349 100644 --- a/benches/bench_mem.py +++ b/benches/bench_mem.py @@ -13,6 +13,8 @@ from plotly.subplots import make_subplots from interpn import ( + MultiBsplineRegular, + MultiBsplineRectilinear, MultilinearRectilinear, MultilinearRegular, MulticubicRegular, @@ -21,6 +23,21 @@ NearestRectilinear, ) +MULTIBSPLINE_LABEL = "InterpN MultiBsplineRegular" +MULTIBSPLINE_RECTILINEAR_LABEL = "InterpN MultiBsplineRectilinear" +MULTICUBIC_LABELS = { + "InterpN MulticubicRegular", + "InterpN MulticubicRectilinear", +} + + +def _legend_name(label: str) -> str: + if label in MULTICUBIC_LABELS: + return "InterpN Cubic" + if label in {MULTIBSPLINE_LABEL, MULTIBSPLINE_RECTILINEAR_LABEL}: + return "InterpN B-Spline" + return label + def bench_eval_mem_vs_dims(): usages = { @@ -29,6 +46,8 @@ def bench_eval_mem_vs_dims(): "InterpN MultilinearRegular": [], "InterpN MultilinearRectilinear": [], "InterpN MulticubicRegular": [], + MULTIBSPLINE_LABEL: [], + MULTIBSPLINE_RECTILINEAR_LABEL: [], "InterpN MulticubicRectilinear": [], "InterpN NearestRegular": [], "InterpN NearestRectilinear": [], @@ -57,7 +76,11 @@ def bench_eval_mem_vs_dims(): rectilinear_interpn = MultilinearRectilinear.new(grids, zgrid) regular_interpn = MultilinearRegular.new(dims, starts, steps, zgrid) cubic_regular_interpn = MulticubicRegular.new(dims, starts, steps, zgrid) + bspline_regular_interpn = MultiBsplineRegular.new(dims, starts, steps, zgrid) + bspline_rectilinear_interpn = MultiBsplineRectilinear.new(grids, zgrid) cubic_rectilinear_interpn = MulticubicRectilinear.new(grids, zgrid) + nearest_regular_interpn = NearestRegular.new(dims, starts, steps, zgrid) + nearest_rectilinear_interpn = NearestRectilinear.new(grids, zgrid) m = max(int(float(nobs) ** (1.0 / ndims) + 2), 2) @@ -76,10 +99,14 @@ def bench_eval_mem_vs_dims(): interps = { "Scipy RegularGridInterpolator Linear": rectilinear_sp, "Scipy RegularGridInterpolator Cubic": cubic_rectilinear_sp, - "InterpN MultilinearRegular": lambda p: regular_interpn.eval, - "InterpN MultilinearRectilinear": lambda p: rectilinear_interpn.eval, - "InterpN MulticubicRegular": lambda p: cubic_regular_interpn.eval, - "InterpN MulticubicRectilinear": lambda p: cubic_rectilinear_interpn.eval, + "InterpN MultilinearRegular": regular_interpn.eval, + "InterpN MultilinearRectilinear": rectilinear_interpn.eval, + "InterpN MulticubicRegular": cubic_regular_interpn.eval, + MULTIBSPLINE_LABEL: bspline_regular_interpn.eval, + MULTIBSPLINE_RECTILINEAR_LABEL: bspline_rectilinear_interpn.eval, + "InterpN MulticubicRectilinear": cubic_rectilinear_interpn.eval, + "InterpN NearestRegular": nearest_regular_interpn.eval, + "InterpN NearestRectilinear": nearest_rectilinear_interpn.eval, } # Interpolation in random order @@ -91,7 +118,11 @@ def bench_eval_mem_vs_dims(): "InterpN MultilinearRegular": points_interpn, "InterpN MultilinearRectilinear": points_interpn, "InterpN MulticubicRegular": points_interpn, + MULTIBSPLINE_LABEL: points_interpn, + MULTIBSPLINE_RECTILINEAR_LABEL: points_interpn, "InterpN MulticubicRectilinear": points_interpn, + "InterpN NearestRegular": points_interpn, + "InterpN NearestRectilinear": points_interpn, } for name, func in interps.items(): @@ -108,7 +139,11 @@ def bench_eval_mem_vs_dims(): "InterpN MultilinearRegular": "Linear", "InterpN MultilinearRectilinear": "Linear", "InterpN MulticubicRegular": "Cubic", + MULTIBSPLINE_LABEL: "Cubic", + MULTIBSPLINE_RECTILINEAR_LABEL: "Cubic", "InterpN MulticubicRectilinear": "Cubic", + "InterpN NearestRegular": "Linear", + "InterpN NearestRectilinear": "Linear", } dash_styles = ["dot", "solid", "dash", "dashdot", "longdashdot"] @@ -136,7 +171,7 @@ def bench_eval_mem_vs_dims(): dash=dash_styles[idx % len(dash_styles)], ), opacity=0.5 if idx == 0 else 1.0, - name=label, + name=_legend_name(label), showlegend=col == 1, ), row=1, diff --git a/docs/1d_quality_of_fit_Rectilinear.html b/docs/1d_quality_of_fit_Rectilinear.html index c53f0e2..0f434ae 100644 --- a/docs/1d_quality_of_fit_Rectilinear.html +++ b/docs/1d_quality_of_fit_Rectilinear.html @@ -1,2 +1,2 @@ -
-
\ No newline at end of file +
+
\ No newline at end of file diff --git a/docs/1d_quality_of_fit_Rectilinear.svg b/docs/1d_quality_of_fit_Rectilinear.svg index 353ffaa..0f1dfef 100644 --- a/docs/1d_quality_of_fit_Rectilinear.svg +++ b/docs/1d_quality_of_fit_Rectilinear.svg @@ -1 +1 @@ -05−1−0.500.51−1−0.500.51−202−200μ−100μ0−202−0.200.2−202−2−1.5−1−0.50DataInterpNScipyInterpN ErrorScipy ErrorComparison — InterpN vs. Scipy w/ Cubic InterpolantRectilinear Gridxxxf(x)ErrorQuadraticSineStepError, QuadraticError, SineError, Step \ No newline at end of file +05−1−0.500.51−1−0.500.51−202−200μ−100μ0−202−0.200.2−202−2−1.5−1−0.50DataInterpN CubicInterpN B-SplineScipyInterpN Cubic ErrorInterpN B-Spline ErrorScipy ErrorComparison — InterpN Cubic vs. InterpN B-Spline vs. Scipy w/ Cubic InterpolantRectilinear Gridxxxf(x)ErrorQuadraticSineStepError, QuadraticError, SineError, Step \ No newline at end of file diff --git a/docs/1d_quality_of_fit_Regular.html b/docs/1d_quality_of_fit_Regular.html index ecc5521..dfe1d0e 100644 --- a/docs/1d_quality_of_fit_Regular.html +++ b/docs/1d_quality_of_fit_Regular.html @@ -1,2 +1,2 @@ -
-
\ No newline at end of file +
+
\ No newline at end of file diff --git a/docs/1d_quality_of_fit_Regular.svg b/docs/1d_quality_of_fit_Regular.svg index 6b189de..541ceeb 100644 --- a/docs/1d_quality_of_fit_Regular.svg +++ b/docs/1d_quality_of_fit_Regular.svg @@ -1 +1 @@ -05−1−0.500.51012−202−10f−5f0−202−0.200.2−202012DataInterpNScipyInterpN ErrorScipy ErrorComparison — InterpN vs. Scipy w/ Cubic InterpolantRegular Gridxxxf(x)ErrorQuadraticSineStepError, QuadraticError, SineError, Step \ No newline at end of file +05−1−0.500.51012−202−10f010f−202−0.200.2−202012DataInterpN CubicInterpN B-SplineScipyInterpN Cubic ErrorInterpN B-Spline ErrorScipy ErrorComparison — InterpN Cubic vs. InterpN B-Spline vs. Scipy w/ Cubic InterpolantRegular Gridxxxf(x)ErrorQuadraticSineStepError, QuadraticError, SineError, Step \ No newline at end of file diff --git a/docs/2d_quality_of_fit_Rectilinear.html b/docs/2d_quality_of_fit_Rectilinear.html index bda719b..e11a052 100644 --- a/docs/2d_quality_of_fit_Rectilinear.html +++ b/docs/2d_quality_of_fit_Rectilinear.html @@ -1,2 +1,2 @@ -
-
\ No newline at end of file +
+
\ No newline at end of file diff --git a/docs/2d_quality_of_fit_Rectilinear.svg b/docs/2d_quality_of_fit_Rectilinear.svg index 3bd71d3..179de26 100644 --- a/docs/2d_quality_of_fit_Rectilinear.svg +++ b/docs/2d_quality_of_fit_Rectilinear.svg @@ -1 +1 @@ -Sampled data1020304050−0.00200.002Quadratic Test Function w/ Cubic InterpolantRectilinear GridTruthInterpNScipyError, InterpNError, Scipy \ No newline at end of file +Sampled data1020304050−0.00200.002Quadratic Test Function w/ Cubic InterpolantRectilinear GridTruthInterpN CubicInterpN B-SplineScipyError, InterpN CubicError, InterpN B-SplineError, Scipy \ No newline at end of file diff --git a/docs/2d_quality_of_fit_Regular.html b/docs/2d_quality_of_fit_Regular.html index 2ece335..26756cf 100644 --- a/docs/2d_quality_of_fit_Regular.html +++ b/docs/2d_quality_of_fit_Regular.html @@ -1,2 +1,2 @@ -
-
\ No newline at end of file +
+
\ No newline at end of file diff --git a/docs/2d_quality_of_fit_Regular.svg b/docs/2d_quality_of_fit_Regular.svg index f567745..4ccabef 100644 --- a/docs/2d_quality_of_fit_Regular.svg +++ b/docs/2d_quality_of_fit_Regular.svg @@ -1 +1 @@ -Sampled data1020304050−500f0500fQuadratic Test Function w/ Cubic InterpolantRegular GridTruthInterpNScipyError, InterpNError, Scipy \ No newline at end of file +Sampled data1020304050−500f0500fQuadratic Test Function w/ Cubic InterpolantRegular GridTruthInterpN CubicInterpN B-SplineScipyError, InterpN CubicError, InterpN B-SplineError, Scipy \ No newline at end of file diff --git a/docs/3d_throughput_vs_nobs_cubic.html b/docs/3d_throughput_vs_nobs_cubic.html index 3a637d5..a686767 100644 --- a/docs/3d_throughput_vs_nobs_cubic.html +++ b/docs/3d_throughput_vs_nobs_cubic.html @@ -1,2 +1,2 @@
-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/3d_throughput_vs_nobs_cubic.svg b/docs/3d_throughput_vs_nobs_cubic.svg index 6ba6f82..5d51604 100644 --- a/docs/3d_throughput_vs_nobs_cubic.svg +++ b/docs/3d_throughput_vs_nobs_cubic.svg @@ -1 +1 @@ -12510251002510002510k24681012ScipyInterpNInterpolation on 20x20x20 GridWithout Preallocated Output, CubicNumber of Observation PointsNormalized Throughput \ No newline at end of file +12510251002510002510k2468ScipyInterpN CubicInterpN B-SplineInterpolation on 20x20x20 GridWithout Preallocated Output, CubicNumber of Observation PointsNormalized Throughput \ No newline at end of file diff --git a/docs/3d_throughput_vs_nobs_linear.html b/docs/3d_throughput_vs_nobs_linear.html index aeba478..044339e 100644 --- a/docs/3d_throughput_vs_nobs_linear.html +++ b/docs/3d_throughput_vs_nobs_linear.html @@ -1,2 +1,2 @@
-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/3d_throughput_vs_nobs_linear.svg b/docs/3d_throughput_vs_nobs_linear.svg index 8d0e56f..ca00992 100644 --- a/docs/3d_throughput_vs_nobs_linear.svg +++ b/docs/3d_throughput_vs_nobs_linear.svg @@ -1 +1 @@ -12510251002510002510k010203040ScipyInterpNInterpolation on 20x20x20 GridWithout Preallocated Output, LinearNumber of Observation PointsNormalized Throughput \ No newline at end of file +12510251002510002510k0510152025ScipyInterpNInterpolation on 20x20x20 GridWithout Preallocated Output, LinearNumber of Observation PointsNormalized Throughput \ No newline at end of file diff --git a/docs/3d_throughput_vs_nobs_prealloc_cubic.html b/docs/3d_throughput_vs_nobs_prealloc_cubic.html index a16bdd8..d107dbf 100644 --- a/docs/3d_throughput_vs_nobs_prealloc_cubic.html +++ b/docs/3d_throughput_vs_nobs_prealloc_cubic.html @@ -1,2 +1,2 @@
-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/3d_throughput_vs_nobs_prealloc_cubic.svg b/docs/3d_throughput_vs_nobs_prealloc_cubic.svg index 46af271..7f356d2 100644 --- a/docs/3d_throughput_vs_nobs_prealloc_cubic.svg +++ b/docs/3d_throughput_vs_nobs_prealloc_cubic.svg @@ -1 +1 @@ -12510251002510002510k0510152025ScipyInterpNInterpolation on 20x20x20 GridWith Preallocated Output, CubicNumber of Observation PointsNormalized Throughput \ No newline at end of file +12510251002510002510k51015ScipyInterpN CubicInterpN B-SplineInterpolation on 20x20x20 GridWith Preallocated Output, CubicNumber of Observation PointsNormalized Throughput \ No newline at end of file diff --git a/docs/3d_throughput_vs_nobs_prealloc_linear.html b/docs/3d_throughput_vs_nobs_prealloc_linear.html index e7f58dd..77d1b73 100644 --- a/docs/3d_throughput_vs_nobs_prealloc_linear.html +++ b/docs/3d_throughput_vs_nobs_prealloc_linear.html @@ -1,2 +1,2 @@
-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/3d_throughput_vs_nobs_prealloc_linear.svg b/docs/3d_throughput_vs_nobs_prealloc_linear.svg index edd786d..18b54ce 100644 --- a/docs/3d_throughput_vs_nobs_prealloc_linear.svg +++ b/docs/3d_throughput_vs_nobs_prealloc_linear.svg @@ -1 +1 @@ -12510251002510002510k020406080ScipyInterpNInterpolation on 20x20x20 GridWith Preallocated Output, LinearNumber of Observation PointsNormalized Throughput \ No newline at end of file +12510251002510002510k0102030405060ScipyInterpNInterpolation on 20x20x20 GridWith Preallocated Output, LinearNumber of Observation PointsNormalized Throughput \ No newline at end of file diff --git a/docs/4d_throughput_vs_nobs_cubic.html b/docs/4d_throughput_vs_nobs_cubic.html index 2bd0a36..674803c 100644 --- a/docs/4d_throughput_vs_nobs_cubic.html +++ b/docs/4d_throughput_vs_nobs_cubic.html @@ -1,2 +1,2 @@
-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/4d_throughput_vs_nobs_cubic.svg b/docs/4d_throughput_vs_nobs_cubic.svg index ffd1df5..d9b81a2 100644 --- a/docs/4d_throughput_vs_nobs_cubic.svg +++ b/docs/4d_throughput_vs_nobs_cubic.svg @@ -1 +1 @@ -12510251002510002510k24681012ScipyInterpNInterpolation on 20x...x20 4D GridWithout Preallocated Output, CubicNumber of Observation PointsNormalized Throughput \ No newline at end of file +12510251002510002510k2468ScipyInterpN CubicInterpN B-SplineInterpolation on 20x...x20 4D GridWithout Preallocated Output, CubicNumber of Observation PointsNormalized Throughput \ No newline at end of file diff --git a/docs/4d_throughput_vs_nobs_linear.html b/docs/4d_throughput_vs_nobs_linear.html index d38ed06..f0c8a13 100644 --- a/docs/4d_throughput_vs_nobs_linear.html +++ b/docs/4d_throughput_vs_nobs_linear.html @@ -1,2 +1,2 @@
-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/4d_throughput_vs_nobs_linear.svg b/docs/4d_throughput_vs_nobs_linear.svg index a7e93d1..20b1cfa 100644 --- a/docs/4d_throughput_vs_nobs_linear.svg +++ b/docs/4d_throughput_vs_nobs_linear.svg @@ -1 +1 @@ -12510251002510002510k0102030405060ScipyInterpNInterpolation on 20x...x20 4D GridWithout Preallocated Output, LinearNumber of Observation PointsNormalized Throughput \ No newline at end of file +12510251002510002510k010203040ScipyInterpNInterpolation on 20x...x20 4D GridWithout Preallocated Output, LinearNumber of Observation PointsNormalized Throughput \ No newline at end of file diff --git a/docs/4d_throughput_vs_nobs_prealloc_cubic.html b/docs/4d_throughput_vs_nobs_prealloc_cubic.html index 1a5c536..5462a2e 100644 --- a/docs/4d_throughput_vs_nobs_prealloc_cubic.html +++ b/docs/4d_throughput_vs_nobs_prealloc_cubic.html @@ -1,2 +1,2 @@
-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/4d_throughput_vs_nobs_prealloc_cubic.svg b/docs/4d_throughput_vs_nobs_prealloc_cubic.svg index e0b0773..709dfac 100644 --- a/docs/4d_throughput_vs_nobs_prealloc_cubic.svg +++ b/docs/4d_throughput_vs_nobs_prealloc_cubic.svg @@ -1 +1 @@ -12510251002510002510k05101520ScipyInterpNInterpolation on 20x...x20 4D GridWith Preallocated Output, CubicNumber of Observation PointsNormalized Throughput \ No newline at end of file +12510251002510002510k51015ScipyInterpN CubicInterpN B-SplineInterpolation on 20x...x20 4D GridWith Preallocated Output, CubicNumber of Observation PointsNormalized Throughput \ No newline at end of file diff --git a/docs/4d_throughput_vs_nobs_prealloc_linear.html b/docs/4d_throughput_vs_nobs_prealloc_linear.html index 8652604..1254bda 100644 --- a/docs/4d_throughput_vs_nobs_prealloc_linear.html +++ b/docs/4d_throughput_vs_nobs_prealloc_linear.html @@ -1,2 +1,2 @@
-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/4d_throughput_vs_nobs_prealloc_linear.svg b/docs/4d_throughput_vs_nobs_prealloc_linear.svg index 3e671c8..280c2c1 100644 --- a/docs/4d_throughput_vs_nobs_prealloc_linear.svg +++ b/docs/4d_throughput_vs_nobs_prealloc_linear.svg @@ -1 +1 @@ -12510251002510002510k020406080100120ScipyInterpNInterpolation on 20x...x20 4D GridWith Preallocated Output, LinearNumber of Observation PointsNormalized Throughput \ No newline at end of file +12510251002510002510k020406080ScipyInterpNInterpolation on 20x...x20 4D GridWith Preallocated Output, LinearNumber of Observation PointsNormalized Throughput \ No newline at end of file diff --git a/docs/nearest_quality_of_fit.html b/docs/nearest_quality_of_fit.html index fd2b84a..c649817 100644 --- a/docs/nearest_quality_of_fit.html +++ b/docs/nearest_quality_of_fit.html @@ -1,2 +1,2 @@ -
-
\ No newline at end of file +
+
\ No newline at end of file diff --git a/docs/nearest_quality_of_fit.svg b/docs/nearest_quality_of_fit.svg index e2676b3..a7d566a 100644 --- a/docs/nearest_quality_of_fit.svg +++ b/docs/nearest_quality_of_fit.svg @@ -1 +1 @@ -Grid samples−1012−101Nearest-Neighbor Quality of Fit — InterpN vs. Scipy griddata (nearest)TruthInterpNScipyError: InterpNError: ScipyScipy - InterpN \ No newline at end of file +Grid samples−1012−101Nearest-Neighbor Quality of Fit — InterpN vs. Scipy griddata (nearest)TruthInterpNScipyError: InterpNError: ScipyScipy - InterpN \ No newline at end of file diff --git a/docs/speedup_vs_dims_1000_obs_cubic.html b/docs/speedup_vs_dims_1000_obs_cubic.html index 0254994..b960888 100644 --- a/docs/speedup_vs_dims_1000_obs_cubic.html +++ b/docs/speedup_vs_dims_1000_obs_cubic.html @@ -1,2 +1,2 @@
-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/speedup_vs_dims_1000_obs_cubic.svg b/docs/speedup_vs_dims_1000_obs_cubic.svg index 6d4a7f3..8f30661 100644 --- a/docs/speedup_vs_dims_1000_obs_cubic.svg +++ b/docs/speedup_vs_dims_1000_obs_cubic.svg @@ -1 +1 @@ -12345601234567InterpN Speedup vs. ScipyCubic, 1000 Observation PointsNumber of DimensionsSpeedup vs. Scipy \ No newline at end of file +1234562468InterpN CubicInterpN B-SplineInterpN Speedup vs. ScipyCubic, 1000 Observation PointsNumber of DimensionsSpeedup vs. Scipy \ No newline at end of file diff --git a/docs/speedup_vs_dims_1000_obs_linear.html b/docs/speedup_vs_dims_1000_obs_linear.html index 4ef968d..8173f92 100644 --- a/docs/speedup_vs_dims_1000_obs_linear.html +++ b/docs/speedup_vs_dims_1000_obs_linear.html @@ -1,2 +1,2 @@
-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/speedup_vs_dims_1000_obs_linear.svg b/docs/speedup_vs_dims_1000_obs_linear.svg index 0b6b74d..cd3b0d2 100644 --- a/docs/speedup_vs_dims_1000_obs_linear.svg +++ b/docs/speedup_vs_dims_1000_obs_linear.svg @@ -1 +1 @@ -1234562468101214InterpN Speedup vs. ScipyLinear, 1000 Observation PointsNumber of DimensionsSpeedup vs. Scipy \ No newline at end of file +1234562468101214InterpNInterpN Speedup vs. ScipyLinear, 1000 Observation PointsNumber of DimensionsSpeedup vs. Scipy \ No newline at end of file diff --git a/docs/speedup_vs_dims_1_obs_cubic.html b/docs/speedup_vs_dims_1_obs_cubic.html index 998f729..fbca05a 100644 --- a/docs/speedup_vs_dims_1_obs_cubic.html +++ b/docs/speedup_vs_dims_1_obs_cubic.html @@ -1,2 +1,2 @@
-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/speedup_vs_dims_1_obs_cubic.svg b/docs/speedup_vs_dims_1_obs_cubic.svg index d45b472..e06f463 100644 --- a/docs/speedup_vs_dims_1_obs_cubic.svg +++ b/docs/speedup_vs_dims_1_obs_cubic.svg @@ -1 +1 @@ -1234560510152025InterpN Speedup vs. ScipyCubic, 1 Observation PointNumber of DimensionsSpeedup vs. Scipy \ No newline at end of file +12345605101520InterpN CubicInterpN B-SplineInterpN Speedup vs. ScipyCubic, 1 Observation PointNumber of DimensionsSpeedup vs. Scipy \ No newline at end of file diff --git a/docs/speedup_vs_dims_1_obs_linear.html b/docs/speedup_vs_dims_1_obs_linear.html index b044b4e..6c3de8e 100644 --- a/docs/speedup_vs_dims_1_obs_linear.html +++ b/docs/speedup_vs_dims_1_obs_linear.html @@ -1,2 +1,2 @@
-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/speedup_vs_dims_1_obs_linear.svg b/docs/speedup_vs_dims_1_obs_linear.svg index 05eb30b..9bf977c 100644 --- a/docs/speedup_vs_dims_1_obs_linear.svg +++ b/docs/speedup_vs_dims_1_obs_linear.svg @@ -1 +1 @@ -123456050100150200250300InterpN Speedup vs. ScipyLinear, 1 Observation PointNumber of DimensionsSpeedup vs. Scipy \ No newline at end of file +123456050100150200InterpNInterpN Speedup vs. ScipyLinear, 1 Observation PointNumber of DimensionsSpeedup vs. Scipy \ No newline at end of file diff --git a/docs/speedup_vs_threads_10000000_obs.html b/docs/speedup_vs_threads_10000000_obs.html index 91340b0..529f110 100644 --- a/docs/speedup_vs_threads_10000000_obs.html +++ b/docs/speedup_vs_threads_10000000_obs.html @@ -1,2 +1,2 @@
-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/speedup_vs_threads_10000000_obs.svg b/docs/speedup_vs_threads_10000000_obs.svg index 390387e..d84d529 100644 --- a/docs/speedup_vs_threads_10000000_obs.svg +++ b/docs/speedup_vs_threads_10000000_obs.svg @@ -1 +1 @@ -123456123456InterpN Thread Speedup (10000000 Observation Points)ThreadsSpeedup vs. 1 Thread \ No newline at end of file +123456123456Linear regularCubic regularB-Spline regularNearest regularLinear rectilinearCubic rectilinearB-Spline rectilinearNearest rectilinearInterpN Thread Speedup (10000000 Observation Points)ThreadsSpeedup vs. 1 Thread \ No newline at end of file diff --git a/docs/throughput_vs_dims_1000_obs.html b/docs/throughput_vs_dims_1000_obs.html index 41d773e..aa59572 100644 --- a/docs/throughput_vs_dims_1000_obs.html +++ b/docs/throughput_vs_dims_1000_obs.html @@ -1,2 +1,2 @@
-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/throughput_vs_dims_1000_obs.svg b/docs/throughput_vs_dims_1000_obs.svg index f6c5a1e..21c4d5c 100644 --- a/docs/throughput_vs_dims_1000_obs.svg +++ b/docs/throughput_vs_dims_1000_obs.svg @@ -1 +1 @@ -246250.01250.1251246100μ0.0010.010.11LinearScipy RegularGridInterpolator LinearInterpN MultilinearRegularInterpN MultilinearRectilinearInterpN NearestRegularInterpN NearestRectilinearNumpy InterpCubicScipy RegularGridInterpolator CubicInterpN MulticubicRegularInterpN MulticubicRectilinearScipy RectBivariateSpline CubicInterpolation on 4x...x4 N-Dimensional Grid1000 Observation PointsNumber of DimensionsNormalized ThroughputLinearCubic \ No newline at end of file +123456250.01250.12511234560.0010.010.11LinearScipyInterpNInterpNInterpNInterpNNumpy InterpCubicScipyInterpN CubicInterpN B-SplineInterpN B-SplineInterpN CubicScipy RectBivariateSpline CubicInterpolation on 4x...x4 N-Dimensional Grid1000 Observation PointsNumber of DimensionsNormalized ThroughputLinearCubic \ No newline at end of file diff --git a/docs/throughput_vs_dims_1_obs.html b/docs/throughput_vs_dims_1_obs.html index 8167e62..e61c68e 100644 --- a/docs/throughput_vs_dims_1_obs.html +++ b/docs/throughput_vs_dims_1_obs.html @@ -1,2 +1,2 @@
-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/throughput_vs_dims_1_obs.svg b/docs/throughput_vs_dims_1_obs.svg index a2ad561..d899f23 100644 --- a/docs/throughput_vs_dims_1_obs.svg +++ b/docs/throughput_vs_dims_1_obs.svg @@ -1 +1 @@ -2460.001250.01250.12512460.01250.1251LinearScipy RegularGridInterpolator LinearInterpN MultilinearRegularInterpN MultilinearRectilinearInterpN NearestRegularInterpN NearestRectilinearNumpy InterpCubicScipy RegularGridInterpolator CubicInterpN MulticubicRegularInterpN MulticubicRectilinearScipy RectBivariateSpline CubicInterpolation on 4x...x4 N-Dimensional Grid1 Observation PointNumber of DimensionsNormalized ThroughputLinearCubic \ No newline at end of file +123456250.01250.125121234560.01250.1251LinearScipyInterpNInterpNInterpNInterpNNumpy InterpCubicScipyInterpN CubicInterpN B-SplineInterpN B-SplineInterpN CubicScipy RectBivariateSpline CubicInterpolation on 4x...x4 N-Dimensional Grid1 Observation PointNumber of DimensionsNormalized ThroughputLinearCubic \ No newline at end of file diff --git a/examples/cubic_comparison.py b/examples/cubic_comparison.py index bc71b0c..894970f 100644 --- a/examples/cubic_comparison.py +++ b/examples/cubic_comparison.py @@ -7,7 +7,15 @@ import plotly.graph_objects as go from plotly.subplots import make_subplots -from interpn import MulticubicRegular, MulticubicRectilinear +from interpn import ( + MulticubicRegular, + MulticubicRectilinear, + MultiBsplineRegular, + MultiBsplineRectilinear, +) + +INTERPN_CUBIC_LABEL = "InterpN Cubic" +INTERPN_BSPLINE_LABEL = "InterpN B-Spline" def _step(x: np.ndarray) -> np.ndarray: @@ -76,10 +84,16 @@ def _axis_name(prefix: str, row: int, col: int, ncols: int) -> str: y_interpn = MulticubicRegular.new( dims, starts, steps, ydata, linearize_extrapolation=False ).eval([xinterp]) + y_bspline = MultiBsplineRegular.new( + dims, starts, steps, ydata, linearize_extrapolation=False + ).eval([xinterp]) else: y_interpn = MulticubicRectilinear.new( [xdata], ydata, linearize_extrapolation=False ).eval([xinterp]) + y_bspline = MultiBsplineRectilinear.new( + [xdata], ydata, linearize_extrapolation=False + ).eval([xinterp]) y_sp = RegularGridInterpolator( [xdata], ydata, bounds_error=None, fill_value=None, method="cubic" @@ -110,14 +124,30 @@ def _axis_name(prefix: str, row: int, col: int, ncols: int) -> str: y=y_interpn, mode="lines", line=dict(color="black", width=2), - name="InterpN", + name=INTERPN_CUBIC_LABEL, legendgroup="interpn", - showlegend="InterpN" not in legend_tracker, + showlegend=INTERPN_CUBIC_LABEL not in legend_tracker, ), row=1, col=col, ) - legend_tracker.add("InterpN") + legend_tracker.add(INTERPN_CUBIC_LABEL) + + if y_bspline is not None: + fig_1d.add_trace( + go.Scatter( + x=xinterp, + y=y_bspline, + mode="lines", + line=dict(color="#1f77b4", width=2, dash="dash"), + name=INTERPN_BSPLINE_LABEL, + legendgroup="multibspline", + showlegend=INTERPN_BSPLINE_LABEL not in legend_tracker, + ), + row=1, + col=col, + ) + legend_tracker.add(INTERPN_BSPLINE_LABEL) fig_1d.add_trace( go.Scatter( @@ -142,14 +172,30 @@ def _axis_name(prefix: str, row: int, col: int, ncols: int) -> str: y=y_interpn - truth, mode="lines", line=dict(color="black", width=2), - name="InterpN Error", + name=f"{INTERPN_CUBIC_LABEL} Error", legendgroup="interpn_err", - showlegend="InterpN Error" not in legend_tracker, + showlegend=f"{INTERPN_CUBIC_LABEL} Error" not in legend_tracker, ), row=2, col=col, ) - legend_tracker.add("InterpN Error") + legend_tracker.add(f"{INTERPN_CUBIC_LABEL} Error") + if y_bspline is not None: + fig_1d.add_trace( + go.Scatter( + x=xinterp, + y=y_bspline - truth, + mode="lines", + line=dict(color="#1f77b4", width=2, dash="dash"), + name=f"{INTERPN_BSPLINE_LABEL} Error", + legendgroup="multibspline_err", + showlegend=f"{INTERPN_BSPLINE_LABEL} Error" + not in legend_tracker, + ), + row=2, + col=col, + ) + legend_tracker.add(f"{INTERPN_BSPLINE_LABEL} Error") fig_1d.add_trace( go.Scatter( x=xinterp, @@ -190,11 +236,11 @@ def _axis_name(prefix: str, row: int, col: int, ncols: int) -> str: showgrid=False, zeroline=False, ) + title_methods = f"{INTERPN_CUBIC_LABEL} vs. {INTERPN_BSPLINE_LABEL} vs. Scipy" fig_1d.update_layout( title=dict( text=( - "Comparison — InterpN vs. Scipy" - f" w/ Cubic Interpolant
{kind} Grid" + f"Comparison — {title_methods} w/ Cubic Interpolant
{kind} Grid" ), y=0.97, yanchor="top", @@ -247,6 +293,13 @@ def _axis_name(prefix: str, row: int, col: int, ncols: int) -> str: .eval([xinterpmesh.flatten(), yinterpmesh.flatten()]) .reshape(xinterpmesh.shape) ) + z_bspline = ( + MultiBsplineRegular.new( + dims, starts, steps, zmesh, linearize_extrapolation=False + ) + .eval([xinterpmesh.flatten(), yinterpmesh.flatten()]) + .reshape(xinterpmesh.shape) + ) else: z_interpn = ( MulticubicRectilinear.new( @@ -255,37 +308,50 @@ def _axis_name(prefix: str, row: int, col: int, ncols: int) -> str: .eval([xinterpmesh.flatten(), yinterpmesh.flatten()]) .reshape(xinterpmesh.shape) ) + z_bspline = ( + MultiBsplineRectilinear.new( + [xdata, ydata], zmesh, linearize_extrapolation=False + ) + .eval([xinterpmesh.flatten(), yinterpmesh.flatten()]) + .reshape(xinterpmesh.shape) + ) z_sp = RegularGridInterpolator( [xdata, ydata], zmesh, bounds_error=None, fill_value=None, method="cubic" )((xinterpmesh, yinterpmesh)) + ncols_2d = 4 if z_bspline is not None else 3 + top_specs = [{"type": "heatmap"}] * ncols_2d + bottom_specs = [{"type": "heatmap"}] * ncols_2d + top_data = [ + (zinterp, "Truth"), + (z_interpn, INTERPN_CUBIC_LABEL), + ] + if z_bspline is not None: + top_data.append((z_bspline, INTERPN_BSPLINE_LABEL)) + top_data.append((z_sp, "Scipy")) + bottom_data = [ + (z_interpn - zinterp, f"Error, {INTERPN_CUBIC_LABEL}"), + ] + if z_bspline is not None: + bottom_data.append((z_bspline - zinterp, f"Error, {INTERPN_BSPLINE_LABEL}")) + bottom_data.append((z_sp - zinterp, "Error, Scipy")) + subplot_titles_2d = [name for _, name in top_data] + [ + "", + *[name for _, name in bottom_data], + ] + fig_2d = make_subplots( rows=2, - cols=3, - specs=[[{"type": "heatmap"}] * 3, [{"type": "heatmap"}] * 3], - subplot_titles=[ - "Truth", - "InterpN", - "Scipy", - "", - "Error, InterpN", - "Error, Scipy", - ], + cols=ncols_2d, + specs=[top_specs, bottom_specs], + subplot_titles=subplot_titles_2d, horizontal_spacing=0.06, vertical_spacing=0.18, ) - colorbar_x_top = {1: 1.02, 2: 1.09, 3: 1.16} - for col, (z_data, title) in enumerate( - [ - (zinterp, "Truth"), - (z_interpn, "InterpN"), - (z_sp, "Scipy"), - ], - start=1, - ): - showscale = col == 3 + for col, (z_data, title) in enumerate(top_data, start=1): + showscale = col == ncols_2d fig_2d.add_trace( go.Heatmap( x=xinterp, @@ -339,36 +405,20 @@ def _axis_name(prefix: str, row: int, col: int, ncols: int) -> str: col=col, ) - fig_2d.add_shape( - type="rect", - x0=-3.0, - x1=3.0, - y0=-3.0, - y1=3.0, - line=dict(color="white"), - row=2, - col=2, - ) - fig_2d.add_shape( - type="rect", - x0=-3.0, - x1=3.0, - y0=-3.0, - y1=3.0, - line=dict(color="white"), - row=2, - col=3, - ) + for col in range(2, ncols_2d + 1): + fig_2d.add_shape( + type="rect", + x0=-3.0, + x1=3.0, + y0=-3.0, + y1=3.0, + line=dict(color="white"), + row=2, + col=col, + ) - colorbar_x_bottom = {2: 1.02, 3: 1.09} - for col, (z_data, name) in enumerate( - [ - (z_interpn - zinterp, "Error, InterpN"), - (z_sp - zinterp, "Error, Scipy"), - ], - start=2, - ): - showscale = col == 3 + for col, (z_data, name) in enumerate(bottom_data, start=2): + showscale = col == ncols_2d fig_2d.add_trace( go.Heatmap( x=xinterp, @@ -383,7 +433,7 @@ def _axis_name(prefix: str, row: int, col: int, ncols: int) -> str: ) for row in (1, 2): - for col in (1, 2, 3): + for col in range(1, ncols_2d + 1): fig_2d.update_xaxes( showticklabels=False, title_text="", @@ -437,8 +487,11 @@ def _axis_name(prefix: str, row: int, col: int, ncols: int) -> str: ), font=dict(color="black"), ) - for row, col in [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3)]: - x_name = _axis_name("x", row, col, 3) + scale_axes = [(1, col) for col in range(1, ncols_2d + 1)] + [ + (2, col) for col in range(2, ncols_2d + 1) + ] + for row, col in scale_axes: + x_name = _axis_name("x", row, col, ncols_2d) fig_2d.update_yaxes( scaleanchor=x_name, scaleratio=1, diff --git a/examples/interpolation_explorer/.gitignore b/examples/interpolation_explorer/.gitignore new file mode 100644 index 0000000..adb443d --- /dev/null +++ b/examples/interpolation_explorer/.gitignore @@ -0,0 +1,2 @@ +/dist/ +/target/ diff --git a/examples/interpolation_explorer/Cargo.lock b/examples/interpolation_explorer/Cargo.lock new file mode 100644 index 0000000..939ee6e --- /dev/null +++ b/examples/interpolation_explorer/Cargo.lock @@ -0,0 +1,2606 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "any_spawner" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1384d3fe1eecb464229fcf6eebb72306591c56bf27b373561489458a7c73027d" +dependencies = [ + "futures", + "thiserror 2.0.18", + "wasm-bindgen-futures", +] + +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + +[[package]] +name = "askama" +version = "0.15.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b8246bcbf8eb97abef10c2d92166449680d41d55c0fc6978a91dec2e3619608" +dependencies = [ + "askama_macros", + "itoa", + "percent-encoding", + "serde", + "serde_json", +] + +[[package]] +name = "askama_derive" +version = "0.15.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f9670bc84a28bb3da91821ef74226949ab63f1265aff7c751634f1dd0e6f97c" +dependencies = [ + "askama_parser", + "basic-toml", + "memchr", + "proc-macro2", + "quote", + "rustc-hash", + "serde", + "serde_derive", + "syn", +] + +[[package]] +name = "askama_macros" +version = "0.15.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0756b45480437dded0565dfc568af62ccce146fb6cfe902e808ba86e445f44f" +dependencies = [ + "askama_derive", +] + +[[package]] +name = "askama_parser" +version = "0.15.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0af3691ba3af77949c0b5a3925444b85cb58a0184cc7fec16c68ba2e7be868" +dependencies = [ + "rustc-hash", + "serde", + "serde_derive", + "unicode-ident", + "winnow", +] + +[[package]] +name = "async-lock" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-once-cell" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288f83726785267c6f2ef073a3d83dc3f9b81464e9f99898240cced85fce35a" + +[[package]] +name = "async-trait" +version = "0.1.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "attribute-derive" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05832cdddc8f2650cc2cc187cc2e952b8c133a48eb055f35211f61ee81502d77" +dependencies = [ + "attribute-derive-macro", + "derive-where", + "manyhow", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "attribute-derive-macro" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a7cdbbd4bd005c5d3e2e9c885e6fa575db4f4a3572335b974d8db853b6beb61" +dependencies = [ + "collection_literals", + "interpolator", + "manyhow", + "proc-macro-utils", + "proc-macro2", + "quote", + "quote-use", + "syn", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base16" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27c3610c36aee21ce8ac510e6224498de4228ad772a171ed65643a24693a5a8" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "basic-toml" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a" +dependencies = [ + "serde", +] + +[[package]] +name = "bitflags" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "camino" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e629a66d692cb9ff1a1c664e41771b3dcaf961985a9774c0eb0bd1b51cf60a48" + +[[package]] +name = "cc" +version = "1.2.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "556e016178bb5662a08681bbe0f00f8e17631781a4dfc8c45e466e4b185ec27f" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "chrono" +version = "0.4.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0" +dependencies = [ + "iana-time-zone", + "num-traits", + "serde", + "windows-link", +] + +[[package]] +name = "codee" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9dbbdc4b4d349732bc6690de10a9de952bd39ba6a065c586e26600b6b0b91f5" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.18", +] + +[[package]] +name = "collection_literals" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2550f75b8cfac212855f6b1885455df8eaee8fe8e246b647d69146142e016084" + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "config" +version = "0.15.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f316c6237b2d38be61949ecd15268a4c6ca32570079394a2444d9ce2c72a72d8" +dependencies = [ + "convert_case 0.6.0", + "pathdiff", + "serde_core", + "toml", + "winnow", +] + +[[package]] +name = "console_error_panic_hook" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "const-str" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18f12cc9948ed9604230cdddc7c86e270f9401ccbe3c2e98a4378c5e7632212f" + +[[package]] +name = "const_format" +version = "0.2.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4481a617ad9a412be3b97c5d403fef8ed023103368908b9c50af598ff467cc1e" +dependencies = [ + "const_format_proc_macros", + "konst", +] + +[[package]] +name = "const_format_proc_macros" +version = "0.2.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d57c2eccfb16dbac1f4e61e206105db5820c9d26c3c472bc17c774259ef7744" +dependencies = [ + "proc-macro2", + "quote", + "unicode-xid", +] + +[[package]] +name = "const_str_slice_concat" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f67855af358fcb20fac58f9d714c94e2b228fe5694c1c9b4ead4a366343eda1b" + +[[package]] +name = "convert_case" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "convert_case" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "affbf0190ed2caf063e3def54ff444b449371d55c58e513a95ab98eca50adb49" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "convert_case_extras" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589c70f0faf8aa9d17787557d5eae854d7755cac50f5c3d12c81d3d57661cebb" +dependencies = [ + "convert_case 0.11.0", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "darling" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn", +] + +[[package]] +name = "darling_macro" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" +dependencies = [ + "darling_core", + "quote", + "syn", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "powerfmt", + "serde_core", +] + +[[package]] +name = "derive-where" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d08b3a0bcc0d079199cd476b2cae8435016ec11d1c0986c6901c5ac223041534" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "drain_filter_polyfill" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "669a445ee724c5c69b1b06fe0b63e70a1c84bc9bb7d9696cd4f4e3ec45050408" + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "either" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" + +[[package]] +name = "either_of" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5060e0a4cbf26a87550792688ade88e6b8aec9208613631a7a363bda7bc2d4cd" +dependencies = [ + "paste", + "pin-project-lite", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "erased" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1731451909bde27714eacba19c2566362a7f35224f52b153d3f42cf60f72472" + +[[package]] +name = "erased-serde" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "event-listener" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +dependencies = [ + "concurrent-queue", + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-executor" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-macro" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "wasip2", + "wasip3", + "wasm-bindgen", +] + +[[package]] +name = "gloo-net" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c06f627b1a58ca3d42b45d6104bf1e1a03799df472df00988b6ba21accc10580" +dependencies = [ + "futures-channel", + "futures-core", + "futures-sink", + "gloo-utils", + "http", + "js-sys", + "pin-project", + "serde", + "serde_json", + "thiserror 1.0.69", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "gloo-utils" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5555354113b18c547c1d3a98fbf7fb32a9ff4f6fa112ce823a21641a0ba3aa" +dependencies = [ + "js-sys", + "serde", + "serde_json", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "guardian" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17e2ac29387b1aa07a1e448f7bb4f35b500787971e965b02842b900afa5c8f6f" + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "html-escape" +version = "0.2.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d1ad449764d627e22bfd7cd5e8868264fc9236e07c752972b4080cd351cb476" +dependencies = [ + "utf8-width", +] + +[[package]] +name = "http" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be7462df143984c4598a256ef469b251d7d7f9e271135073e78fc535414f3d0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "hydration_context" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8714ae4adeaa846d838f380fbd72f049197de629948f91bf045329e0cf0a283" +dependencies = [ + "futures", + "once_cell", + "or_poisoned", + "pin-project-lite", + "serde", + "throw_error", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "interpn" +version = "0.12.0" +dependencies = [ + "crunchy", + "itertools", + "num-traits", +] + +[[package]] +name = "interpolation_explorer" +version = "0.1.0" +dependencies = [ + "console_error_panic_hook", + "interpn", + "leptos", + "plotly", + "wasm-bindgen-futures", +] + +[[package]] +name = "interpolator" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71dd52191aae121e8611f1e8dc3e324dd0dd1dee1e6dd91d10ee07a3cfb4d9d8" + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.99" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "142bc4740e452c1e57ade0cbc129f139c9093e354346f0872ef985f4f5cf5f11" +dependencies = [ + "cfg-if", + "futures-util", + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "konst" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "128133ed7824fcd73d6e7b17957c5eb7bacb885649bd8c69708b2331a10bcefb" +dependencies = [ + "konst_macro_rules", +] + +[[package]] +name = "konst_macro_rules" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "leptos" +version = "0.8.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "efa3982e7fe36c1de68f91f3c9083124f389a975523881f3d7e3363362feda41" +dependencies = [ + "any_spawner", + "cfg-if", + "either_of", + "futures", + "getrandom", + "hydration_context", + "leptos_config", + "leptos_dom", + "leptos_hot_reload", + "leptos_macro", + "leptos_server", + "oco_ref", + "or_poisoned", + "paste", + "reactive_graph", + "rustc-hash", + "rustc_version", + "send_wrapper", + "serde", + "serde_json", + "serde_qs", + "server_fn", + "slotmap", + "tachys", + "thiserror 2.0.18", + "throw_error", + "typed-builder", + "typed-builder-macro", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm_split_helpers", + "web-sys", +] + +[[package]] +name = "leptos_config" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c06f751315bccc0d193fab302ac01d25bcfcd97474d4676440e7e3250dc3fc3" +dependencies = [ + "config", + "regex", + "serde", + "thiserror 2.0.18", + "typed-builder", +] + +[[package]] +name = "leptos_dom" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35742e9ed8f8aaf9e549b454c68a7ac0992536e06856365639b111f72ab07884" +dependencies = [ + "js-sys", + "or_poisoned", + "reactive_graph", + "send_wrapper", + "tachys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "leptos_hot_reload" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d2a0f220c8a5ef3c51199dfb9cdd702bc0eb80d52fbe70c7890adfaaae8a4b1" +dependencies = [ + "anyhow", + "camino", + "indexmap 2.14.0", + "or_poisoned", + "proc-macro2", + "quote", + "rstml", + "serde", + "syn", + "walkdir", +] + +[[package]] +name = "leptos_macro" +version = "0.8.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9360df573fb57582384a8b7640a3de94ce6501d49be3b69f637cf11a42da484b" +dependencies = [ + "attribute-derive", + "cfg-if", + "convert_case 0.11.0", + "convert_case_extras", + "html-escape", + "itertools", + "leptos_hot_reload", + "prettyplease", + "proc-macro-error2", + "proc-macro2", + "quote", + "rstml", + "rustc_version", + "server_fn_macro", + "syn", + "uuid", +] + +[[package]] +name = "leptos_server" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da974775c5ccbb6bd64be7f53f75e8321542e28f21563a416574dbe4d5447eae" +dependencies = [ + "any_spawner", + "base64", + "codee", + "futures", + "hydration_context", + "or_poisoned", + "reactive_graph", + "send_wrapper", + "serde", + "serde_json", + "server_fn", + "tachys", +] + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "log" +version = "0.4.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "616ec5685824bcc94416c6d4a7a446eea774a31efd7062c8480ba6fd06d7a6e5" + +[[package]] +name = "manyhow" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b33efb3ca6d3b07393750d4030418d594ab1139cee518f0dc88db70fec873587" +dependencies = [ + "manyhow-macros", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "manyhow-macros" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46fce34d199b78b6e6073abf984c9cf5fd3e9330145a93ee0738a7443e371495" +dependencies = [ + "proc-macro-utils", + "proc-macro2", + "quote", +] + +[[package]] +name = "memchr" +version = "2.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8" + +[[package]] +name = "next_tuple" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60993920e071b0c9b66f14e2b32740a4e27ffc82854dcd72035887f336a09a28" + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "oco_ref" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed0423ff9973dea4d6bd075934fdda86ebb8c05bdf9d6b0507067d4a1226371d" +dependencies = [ + "serde", + "thiserror 2.0.18", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "or_poisoned" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c04f5d74368e4d0dfe06c45c8627c81bd7c317d52762d118fb9b3076f6420fd" + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pathdiff" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "plotly" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7291750f368f10b87422a0407c0db27acf50cbcc5864564b8ac17c9711ee6afe" +dependencies = [ + "askama", + "dyn-clone", + "erased-serde", + "once_cell", + "plotly_derive", + "rand", + "serde", + "serde-wasm-bindgen", + "serde_json", + "serde_repr", + "serde_with", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "plotly_derive" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eee829fde816615080d73fab040288d3844fecd2487d8936e2fd6d70c0b91db7" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "proc-macro-error-attr2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "proc-macro-error2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" +dependencies = [ + "proc-macro-error-attr2", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "proc-macro-utils" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eeaf08a13de400bc215877b5bdc088f241b12eb42f0a548d3390dc1c56bb7071" +dependencies = [ + "proc-macro2", + "quote", + "smallvec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proc-macro2-diagnostics" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "version_check", + "yansi", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "quote-use" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9619db1197b497a36178cfc736dc96b271fe918875fbf1344c436a7e93d0321e" +dependencies = [ + "quote", + "quote-use-macros", +] + +[[package]] +name = "quote-use-macros" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82ebfb7faafadc06a7ab141a6f67bcfb24cb8beb158c6fe933f2f035afa99f35" +dependencies = [ + "proc-macro-utils", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "reactive_graph" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00c5a025366836190c7030e883cc2bcd9e384ff555336e3c7954741ca411b177" +dependencies = [ + "any_spawner", + "async-lock", + "futures", + "guardian", + "hydration_context", + "indexmap 2.14.0", + "or_poisoned", + "paste", + "pin-project-lite", + "rustc-hash", + "rustc_version", + "send_wrapper", + "serde", + "slotmap", + "thiserror 2.0.18", + "web-sys", +] + +[[package]] +name = "reactive_stores" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c30fd35b7d299c591293bb69fed47a703eb2703b1cff0493e78b16ed007e5382" +dependencies = [ + "guardian", + "indexmap 2.14.0", + "itertools", + "or_poisoned", + "paste", + "reactive_graph", + "reactive_stores_macro", + "rustc-hash", + "send_wrapper", +] + +[[package]] +name = "reactive_stores_macro" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d8e790a5ae5ddf9b7fa380c728375b06858e0cca7d063a73b3408320c523e1" +dependencies = [ + "convert_case 0.11.0", + "proc-macro-error2", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "ref-cast" +version = "1.0.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "regex" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" + +[[package]] +name = "rstml" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61cf4616de7499fc5164570d40ca4e1b24d231c6833a88bff0fe00725080fd56" +dependencies = [ + "derive-where", + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "syn", + "syn_derive", + "thiserror 2.0.18", +] + +[[package]] +name = "rustc-hash" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "send_wrapper" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" +dependencies = [ + "futures-core", +] + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde-wasm-bindgen" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b" +dependencies = [ + "js-sys", + "serde", + "wasm-bindgen", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.150" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_qs" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3faaf9e727533a19351a43cc5a8de957372163c7d35cc48c90b75cdda13c352" +dependencies = [ + "percent-encoding", + "serde", + "thiserror 2.0.18", +] + +[[package]] +name = "serde_repr" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_with" +version = "3.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e72c1c2cb7b223fafb600a619537a871c2818583d619401b785e7c0b746ccde2" +dependencies = [ + "base64", + "bs58", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.14.0", + "schemars 0.9.0", + "schemars 1.2.1", + "serde_core", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b90c488738ecb4fb0262f41f43bc40efc5868d9fb744319ddf5f5317f417bfac" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "server_fn" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d60e4c1dfccd91fe0990141f69f1d5cf5679797ad53aa1b45e5bd658eb119f0" +dependencies = [ + "base64", + "bytes", + "const-str", + "const_format", + "futures", + "gloo-net", + "http", + "js-sys", + "or_poisoned", + "pin-project-lite", + "rustc_version", + "rustversion", + "send_wrapper", + "serde", + "serde_json", + "serde_qs", + "server_fn_macro_default", + "thiserror 2.0.18", + "throw_error", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "xxhash-rust", +] + +[[package]] +name = "server_fn_macro" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1295b54815397d30d986b63f93cfd515fa86d5e528e0bb589ce9d530502f9e0f" +dependencies = [ + "const_format", + "convert_case 0.11.0", + "proc-macro2", + "quote", + "rustc_version", + "syn", + "xxhash-rust", +] + +[[package]] +name = "server_fn_macro_default" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63eb08f80db903d3c42f64e60ebb3875e0305be502bdc064ec0a0eab42207f00" +dependencies = [ + "server_fn_macro", + "syn", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn_derive" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb066a04799e45f5d582e8fc6ec8e6d6896040d00898eb4e6a835196815b219" +dependencies = [ + "proc-macro-error2", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tachys" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2989c94c59db8497727875aa561d4d0daa3cc79b5774d5ced48263f7091beff1" +dependencies = [ + "any_spawner", + "async-trait", + "const_str_slice_concat", + "drain_filter_polyfill", + "either_of", + "erased", + "futures", + "html-escape", + "indexmap 2.14.0", + "itertools", + "js-sys", + "next_tuple", + "oco_ref", + "or_poisoned", + "paste", + "reactive_graph", + "reactive_stores", + "rustc-hash", + "rustc_version", + "send_wrapper", + "slotmap", + "throw_error", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl 2.0.18", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "throw_error" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0ed6038fcbc0795aca7c92963ddda636573b956679204e044492d2b13c8f64" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "time" +version = "0.3.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" + +[[package]] +name = "time-macros" +version = "0.2.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "toml" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81f3d15e84cbcd896376e6730314d59fb5a87f31e4b038454184435cd57defee" +dependencies = [ + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" +dependencies = [ + "winnow", +] + +[[package]] +name = "typed-builder" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31aa81521b70f94402501d848ccc0ecaa8f93c8eb6999eb9747e72287757ffda" +dependencies = [ + "typed-builder-macro", +] + +[[package]] +name = "typed-builder-macro" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "076a02dc54dd46795c2e9c8282ed40bcfb1e22747e955de9389a1de28190fb26" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-segmentation" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8-width" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1292c0d970b54115d14f2492fe0170adf21d68a1de108eebc51c1df4f346a091" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d258b83ceec21034727ecee8c382cfa6c3e133699b0742c64571814fb420c9f7" +dependencies = [ + "getrandom", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasip2" +version = "1.0.3+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" +dependencies = [ + "wit-bindgen 0.57.1", +] + +[[package]] +name = "wasip3" +version = "0.4.0+wasi-0.3.0-rc-2026-01-06" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" +dependencies = [ + "wit-bindgen 0.51.0", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.122" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ed04576f974d2b2fba0f38c51dbc5518011e38c36bf1143164be765528fd409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.72" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9473dbd2991ae90b6291c3c32c30c6187ac49aa32f9905d1cce280ec1e110b0f" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.122" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "916151b09da36bd82f6615cbf3a419e2f0ba23a03c6160e8e92eb6bd4aa1dec6" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.122" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "299047362ccbfce148b67ab7e73349f77748e00c8296f9542adfad2ad82c5c5e" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.122" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a929b2c61f11ba3e9bc35b50c1f25cb38e0e892c0c231ae2b8cf78d5dad4437" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap 2.14.0", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "wasm_split_helpers" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0cb6d1008be3c4c5abc31a407bfb8c8449ae14efc8561c1db821f79b9614b0a" +dependencies = [ + "async-once-cell", + "wasm_split_macros", +] + +[[package]] +name = "wasm_split_macros" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a659ffe5c7f4538aa6357c07e3d73221cc61eba03bd9a081e14bc91ed09b8c" +dependencies = [ + "base16", + "quote", + "sha2", + "syn", +] + +[[package]] +name = "wasmparser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap 2.14.0", + "semver", +] + +[[package]] +name = "web-sys" +version = "0.3.99" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d621441cfc37b84979402712047321980c178f299193a3589d05b99e8763436" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0592e1c9d151f854e6fd382574c3a0855250e1d9b2f99d9281c6e6391af352f1" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +dependencies = [ + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wit-bindgen-core" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" +dependencies = [ + "anyhow", + "heck", + "indexmap 2.14.0", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags", + "indexmap 2.14.0", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap 2.14.0", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "xxhash-rust" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdd20c5420375476fbd4394763288da7eb0cc0b8c11deed431a91562af7335d3" + +[[package]] +name = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" + +[[package]] +name = "yoke" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/examples/interpolation_explorer/Cargo.toml b/examples/interpolation_explorer/Cargo.toml new file mode 100644 index 0000000..2ec8381 --- /dev/null +++ b/examples/interpolation_explorer/Cargo.toml @@ -0,0 +1,16 @@ +[workspace] + +[package] +name = "interpolation_explorer" +version = "0.1.0" +edition = "2024" +publish = false + +[dependencies] +interpn = { path = "../..", default-features = false, features = ["std"] } + +plotly = "0.14.1" + +leptos = { version = "0.8.17", default-features = false, features = ["csr"] } +console_error_panic_hook = "0.1.7" +wasm-bindgen-futures = "0.4.55" diff --git a/examples/interpolation_explorer/README.md b/examples/interpolation_explorer/README.md new file mode 100644 index 0000000..72cf339 --- /dev/null +++ b/examples/interpolation_explorer/README.md @@ -0,0 +1,12 @@ +# interpolation_explorer + +Browser-hosted `interpn` example using Leptos, Trunk, and Plotly. + +```bash +rustup target add wasm32-unknown-unknown +cargo install trunk +cd examples/interpolation_explorer +trunk serve +``` + +The app contains a 1D interpolation comparison page and a B-spline knot-value panel. diff --git a/examples/interpolation_explorer/Trunk.toml b/examples/interpolation_explorer/Trunk.toml new file mode 100644 index 0000000..d75d73b --- /dev/null +++ b/examples/interpolation_explorer/Trunk.toml @@ -0,0 +1,3 @@ +[build] +dist = "dist" +public_url = "/" diff --git a/examples/interpolation_explorer/index.html b/examples/interpolation_explorer/index.html new file mode 100644 index 0000000..d6a893c --- /dev/null +++ b/examples/interpolation_explorer/index.html @@ -0,0 +1,15 @@ + + + + + + interpn interpolation explorer + + + + + + diff --git a/examples/interpolation_explorer/src/app.rs b/examples/interpolation_explorer/src/app.rs new file mode 100644 index 0000000..4e37e3d --- /dev/null +++ b/examples/interpolation_explorer/src/app.rs @@ -0,0 +1,811 @@ +use crate::plotly_support::use_plotly_chart; +use interpn::{ + GridInterpMethod, GridKind, Left1D, Linear1D, LinearHoldLast1D, MultiBsplineRectilinear, + MultiBsplineRegular, Nearest1D, RectilinearGrid1D, RegularGrid1D, Right1D, interpn_serial, + one_dim::Interp1D, +}; +use leptos::prelude::*; +use plotly::{ + Layout, Plot, Scatter, + common::{DashType, Line, Marker, Mode, Title}, + layout::Axis, +}; + +const SAMPLE_COUNT: usize = 500; +const BSPLINE_KNOTS: usize = 8; +const DEIMOS_PRIMARY: &str = "#8232ba"; +const DEIMOS_ACCENT: &str = "#ac37ff"; +const DEIMOS_WARNING: &str = "#ffd166"; +const DEIMOS_DANGER: &str = "#f26d7d"; +const REFERENCE_LINE: &str = "#000000"; + +#[component] +pub fn App() -> impl IntoView { + let (light_mode, set_light_mode) = signal(false); + let (truth_function, set_truth_function) = signal(TruthFunction::SineMix); + let (grid_kind, set_grid_kind) = signal(GridChoice::Regular); + let (method, set_method) = signal(MethodChoice::Linear); + let (grid_points, set_grid_points) = signal(10_usize); + let (show_error, set_show_error) = signal(false); + let (bspline_input_mode, set_bspline_input_mode) = signal(BsplineInputMode::NodalValues); + let (knot_values, set_knot_values) = + signal(vec![0.0, 0.55, 0.95, 0.35, -0.45, -0.9, -0.35, 0.25]); + + let comparison_inputs = move || ComparisonInputs { + truth_function: truth_function.get(), + grid_kind: grid_kind.get(), + method: method.get(), + grid_points: grid_points.get(), + show_error: show_error.get(), + }; + let comparison = Memo::new(move |_| build_comparison(comparison_inputs())); + let spline = + Memo::new(move |_| build_bspline_demo(bspline_input_mode.get(), knot_values.get())); + + use_plotly_chart("comparison-plot", move || { + build_comparison_plot(comparison.get()) + }); + use_plotly_chart("bspline-plot", move || build_bspline_plot(spline.get())); + + let comparison_status = move || comparison.get().status; + let spline_status = move || spline.get().status; + + view! { +
+ + +
+
+
+

"1D"

+

"Interpolation comparison"

+
+ +
+ + +
+
+
+
+
+ +
+
+

"B-Spline"

+

"Coefficient panel"

+
+ +
+ + +
+
+
+
+
+
+
+ } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum BsplineInputMode { + NodalValues, + Coefficients, +} + +impl BsplineInputMode { + const fn as_key(self) -> &'static str { + match self { + Self::NodalValues => "nodal_values", + Self::Coefficients => "coefficients", + } + } + + const fn slider_label(self) -> &'static str { + match self { + Self::NodalValues => "Data", + Self::Coefficients => "Coeff", + } + } + + const fn marker_label(self) -> &'static str { + match self { + Self::NodalValues => "nodal data", + Self::Coefficients => "B-spline coefficients", + } + } + + const fn plot_title(self) -> &'static str { + match self { + Self::NodalValues => "Cubic B-spline solved from nodal data", + Self::Coefficients => "Cubic B-spline from direct coefficients", + } + } + + fn from_form_value(value: &str) -> Self { + match value { + "coefficients" => Self::Coefficients, + _ => Self::NodalValues, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum TruthFunction { + SineMix, + Runge, + Corner, + Chirp, +} + +impl TruthFunction { + const fn as_key(self) -> &'static str { + match self { + Self::SineMix => "sine_mix", + Self::Runge => "runge", + Self::Corner => "corner", + Self::Chirp => "chirp", + } + } + + const fn label(self) -> &'static str { + match self { + Self::SineMix => "Sine mix", + Self::Runge => "Runge", + Self::Corner => "Corner", + Self::Chirp => "Chirp", + } + } + + fn from_form_value(value: &str) -> Self { + match value { + "runge" => Self::Runge, + "corner" => Self::Corner, + "chirp" => Self::Chirp, + _ => Self::SineMix, + } + } + + fn eval(self, x: f64) -> f64 { + match self { + Self::SineMix => { + (std::f64::consts::TAU * x).sin() + 0.28 * (5.0 * std::f64::consts::PI * x).cos() + } + Self::Runge => 1.0 / (1.0 + 18.0 * x * x), + Self::Corner => { + if x < -0.2 { + -0.55 + 0.25 * (4.0 * x).sin() + } else if x < 0.42 { + 0.25 + 1.1 * x + } else { + 1.05 - 0.8 * x + } + } + Self::Chirp => (8.0 * x * x + 1.5 * x).sin() * (-0.7 * (x + 1.0)).exp(), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum GridChoice { + Regular, + Rectilinear, +} + +impl GridChoice { + const fn as_key(self) -> &'static str { + match self { + Self::Regular => "regular", + Self::Rectilinear => "rectilinear", + } + } + + const fn label(self) -> &'static str { + match self { + Self::Regular => "regular", + Self::Rectilinear => "rectilinear", + } + } + + const fn grid_kind(self) -> GridKind { + match self { + Self::Regular => GridKind::Regular, + Self::Rectilinear => GridKind::Rectilinear, + } + } + + fn from_form_value(value: &str) -> Self { + match value { + "rectilinear" => Self::Rectilinear, + _ => Self::Regular, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum MethodChoice { + Linear, + LinearHoldLast, + Cubic, + Bspline, + Nearest, + Left, + Right, +} + +impl MethodChoice { + const fn as_key(self) -> &'static str { + match self { + Self::Linear => "linear", + Self::LinearHoldLast => "linear_hold_last", + Self::Cubic => "cubic", + Self::Bspline => "bspline", + Self::Nearest => "nearest", + Self::Left => "left", + Self::Right => "right", + } + } + + const fn label(self) -> &'static str { + match self { + Self::Linear => "Linear", + Self::LinearHoldLast => "Linear hold-last", + Self::Cubic => "Cubic Hermite", + Self::Bspline => "Cubic B-spline", + Self::Nearest => "Nearest", + Self::Left => "Left hold", + Self::Right => "Right hold", + } + } + + const fn grid_method(self) -> Option { + match self { + Self::Linear => Some(GridInterpMethod::Linear), + Self::Cubic => Some(GridInterpMethod::Cubic), + Self::Nearest => Some(GridInterpMethod::Nearest), + Self::Bspline | Self::LinearHoldLast | Self::Left | Self::Right => None, + } + } + + fn from_form_value(value: &str) -> Self { + match value { + "linear_hold_last" => Self::LinearHoldLast, + "cubic" => Self::Cubic, + "bspline" => Self::Bspline, + "nearest" => Self::Nearest, + "left" => Self::Left, + "right" => Self::Right, + _ => Self::Linear, + } + } +} + +#[derive(Clone, Copy)] +struct ComparisonInputs { + truth_function: TruthFunction, + grid_kind: GridChoice, + method: MethodChoice, + grid_points: usize, + show_error: bool, +} + +#[derive(Clone, PartialEq)] +struct ComparisonData { + title: String, + x_eval: Vec, + y_truth: Vec, + y_interp: Vec, + y_error: Vec, + x_grid: Vec, + y_grid: Vec, + show_error: bool, + status: String, +} + +#[derive(Clone, PartialEq)] +struct BsplineData { + x_eval: Vec, + y_curve: Vec, + x_nodes: Vec, + y_inputs: Vec, + y_curve_at_nodes: Vec, + input_label: &'static str, + title: &'static str, + status: String, +} + +fn build_comparison(inputs: ComparisonInputs) -> ComparisonData { + let x_eval = linspace(-1.15, 1.15, SAMPLE_COUNT); + let x_grid = build_grid(inputs.grid_kind, inputs.grid_points); + let y_grid = x_grid + .iter() + .map(|&x| inputs.truth_function.eval(x)) + .collect::>(); + let y_truth = x_eval + .iter() + .map(|&x| inputs.truth_function.eval(x)) + .collect::>(); + + let (y_interp, status) = + interpolate_curve(inputs.grid_kind, inputs.method, &x_grid, &y_grid, &x_eval) + .map(|values| { + let rms = rms_error(&values, &y_truth); + (values, format!("RMS error: {rms:.3e}")) + }) + .unwrap_or_else(|msg| (vec![f64::NAN; x_eval.len()], format!("Error: {msg}"))); + let y_error = y_interp + .iter() + .zip(y_truth.iter()) + .map(|(interp, truth)| (interp - truth).abs()) + .collect::>(); + + ComparisonData { + title: format!( + "{} on a {} grid with {}", + inputs.truth_function.label(), + inputs.grid_kind.label(), + inputs.method.label() + ), + x_eval, + y_truth, + y_interp, + y_error, + x_grid, + y_grid, + show_error: inputs.show_error, + status, + } +} + +fn interpolate_curve( + grid_kind: GridChoice, + method: MethodChoice, + x_grid: &[f64], + y_grid: &[f64], + x_eval: &[f64], +) -> Result, &'static str> { + if method == MethodChoice::Bspline { + return interpolate_bspline_curve(grid_kind, x_grid, y_grid, x_eval); + } + + match method.grid_method() { + Some(grid_method) => { + let grids = &[x_grid]; + let obs = &[x_eval]; + let mut out = vec![0.0; x_eval.len()]; + interpn_serial( + grids, + y_grid, + obs, + &mut out, + grid_method, + Some(grid_kind.grid_kind()), + true, + None, + )?; + Ok(out) + } + None => interpolate_one_dim(grid_kind, method, x_grid, y_grid, x_eval), + } +} + +fn interpolate_bspline_curve( + grid_kind: GridChoice, + x_grid: &[f64], + y_grid: &[f64], + x_eval: &[f64], +) -> Result, &'static str> { + let dims = [x_grid.len()]; + let mut out = vec![0.0; x_eval.len()]; + match grid_kind { + GridChoice::Regular => { + let mut coeffs = vec![0.0; MultiBsplineRegular::::coeff_storage_len(dims)]; + let mut scratch = + vec![0.0; MultiBsplineRegular::::construction_scratch_len(dims)]; + let interpolator = MultiBsplineRegular::from_values_with_workspace( + dims, + [x_grid[0]], + [x_grid[1] - x_grid[0]], + y_grid, + &mut coeffs, + &mut scratch, + true, + )?; + interpolator.interp(&[x_eval], &mut out)?; + } + GridChoice::Rectilinear => { + let grids = [x_grid]; + let mut coeffs = + vec![0.0; MultiBsplineRectilinear::::coeff_storage_len(dims)]; + let mut scratch = + vec![0.0; MultiBsplineRectilinear::::construction_scratch_len(dims)]; + let interpolator = MultiBsplineRectilinear::from_values_with_workspace( + &grids, + y_grid, + &mut coeffs, + &mut scratch, + true, + )?; + interpolator.interp(&[x_eval], &mut out)?; + } + } + Ok(out) +} + +fn interpolate_one_dim( + grid_kind: GridChoice, + method: MethodChoice, + x_grid: &[f64], + y_grid: &[f64], + x_eval: &[f64], +) -> Result, &'static str> { + let mut out = vec![0.0; x_eval.len()]; + match grid_kind { + GridChoice::Regular => { + let grid = RegularGrid1D::new(x_grid[0], x_grid[1] - x_grid[0], y_grid)?; + match method { + MethodChoice::LinearHoldLast => { + LinearHoldLast1D::new(grid).eval(x_eval, &mut out)? + } + MethodChoice::Left => Left1D::new(grid).eval(x_eval, &mut out)?, + MethodChoice::Right => Right1D::new(grid).eval(x_eval, &mut out)?, + _ => Linear1D::new(grid).eval(x_eval, &mut out)?, + } + } + GridChoice::Rectilinear => { + let grid = RectilinearGrid1D::new(x_grid, y_grid)?; + match method { + MethodChoice::LinearHoldLast => { + LinearHoldLast1D::new(grid).eval(x_eval, &mut out)? + } + MethodChoice::Left => Left1D::new(grid).eval(x_eval, &mut out)?, + MethodChoice::Right => Right1D::new(grid).eval(x_eval, &mut out)?, + MethodChoice::Nearest => Nearest1D::new(grid).eval(x_eval, &mut out)?, + _ => Linear1D::new(grid).eval(x_eval, &mut out)?, + } + } + } + Ok(out) +} + +fn build_bspline_demo(input_mode: BsplineInputMode, y_inputs: Vec) -> BsplineData { + let x_nodes = linspace(-1.0, 1.0, y_inputs.len()); + let x_eval = linspace(-1.1, 1.1, SAMPLE_COUNT); + let mut y_curve = vec![0.0; x_eval.len()]; + let mut y_curve_at_nodes = vec![0.0; x_nodes.len()]; + let eval_result = eval_bspline(input_mode, &x_nodes, &y_inputs, &x_eval, &mut y_curve) + .and_then(|()| { + eval_bspline( + input_mode, + &x_nodes, + &y_inputs, + &x_nodes, + &mut y_curve_at_nodes, + ) + }); + let status = eval_result + .map(|()| match input_mode { + BsplineInputMode::NodalValues => { + "Solved coefficients from nodal data; curve passes through the data values." + .to_string() + } + BsplineInputMode::Coefficients => { + "Passed coefficients directly; curve values at nodes are plotted separately." + .to_string() + } + }) + .unwrap_or_else(|msg| { + y_curve.fill(f64::NAN); + y_curve_at_nodes.fill(f64::NAN); + format!("Error: {msg}") + }); + + BsplineData { + x_eval, + y_curve, + x_nodes, + y_inputs, + y_curve_at_nodes, + input_label: input_mode.marker_label(), + title: input_mode.plot_title(), + status, + } +} + +fn eval_bspline( + input_mode: BsplineInputMode, + x_nodes: &[f64], + y_inputs: &[f64], + x_eval: &[f64], + out: &mut [f64], +) -> Result<(), &'static str> { + let dims = [x_nodes.len()]; + let starts = [x_nodes[0]]; + let steps = [x_nodes[1] - x_nodes[0]]; + match input_mode { + BsplineInputMode::NodalValues => { + let mut coeffs = vec![0.0; MultiBsplineRegular::::coeff_storage_len(dims)]; + let mut scratch = + vec![0.0; MultiBsplineRegular::::construction_scratch_len(dims)]; + let interpolator = MultiBsplineRegular::from_values_with_workspace( + dims, + starts, + steps, + y_inputs, + &mut coeffs, + &mut scratch, + true, + )?; + interpolator.interp(&[x_eval], out) + } + BsplineInputMode::Coefficients => MultiBsplineRegular::new( + dims, + starts, + steps, + y_inputs, + true, + )? + .interp(&[x_eval], out), + } +} + +fn build_comparison_plot(data: ComparisonData) -> Plot { + let mut plot = Plot::new(); + plot.add_trace( + Scatter::new(data.x_eval.clone(), data.y_truth) + .mode(Mode::Lines) + .name("truth") + .line(Line::new().color(REFERENCE_LINE).width(3.0)), + ); + plot.add_trace( + Scatter::new(data.x_eval.clone(), data.y_interp) + .mode(Mode::Lines) + .name("interpolated") + .line(Line::new().color(DEIMOS_PRIMARY).width(3.0)), + ); + plot.add_trace( + Scatter::new(data.x_grid, data.y_grid) + .mode(Mode::Markers) + .name("grid samples") + .marker(Marker::new().color(DEIMOS_DANGER).size(10)), + ); + if data.show_error { + plot.add_trace( + Scatter::new(data.x_eval, data.y_error) + .mode(Mode::Lines) + .name("absolute error") + .line( + Line::new() + .color(DEIMOS_WARNING) + .width(2.0) + .dash(DashType::Dash), + ), + ); + } + plot.set_layout(line_layout(&data.title, "x", "y")); + plot +} + +fn build_bspline_plot(data: BsplineData) -> Plot { + let mut plot = Plot::new(); + plot.add_trace( + Scatter::new(data.x_eval, data.y_curve) + .mode(Mode::Lines) + .name("B-spline curve") + .line(Line::new().color(DEIMOS_PRIMARY).width(3.0)), + ); + plot.add_trace( + Scatter::new(data.x_nodes.clone(), data.y_inputs) + .mode(Mode::Markers) + .name(data.input_label) + .marker(Marker::new().color(DEIMOS_DANGER).size(12)), + ); + plot.add_trace( + Scatter::new(data.x_nodes, data.y_curve_at_nodes) + .mode(Mode::Markers) + .name("curve at nodes") + .marker(Marker::new().color(DEIMOS_ACCENT).size(8)), + ); + plot.set_layout(line_layout(data.title, "x", "value")); + plot +} + +fn line_layout(title: &str, x_title: &str, y_title: &str) -> Layout { + Layout::new() + .title(Title::with_text(title)) + .x_axis(Axis::new().title(Title::with_text(x_title))) + .y_axis(Axis::new().title(Title::with_text(y_title))) +} + +fn build_grid(kind: GridChoice, n: usize) -> Vec { + match kind { + GridChoice::Regular => linspace(-1.0, 1.0, n), + GridChoice::Rectilinear => (0..n) + .map(|i| { + let t = i as f64 / (n - 1) as f64; + -1.0 + 2.0 * t.powf(1.35) + }) + .collect(), + } +} + +fn linspace(start: f64, stop: f64, n: usize) -> Vec { + match n { + 0 => Vec::new(), + 1 => vec![start], + _ => (0..n) + .map(|i| start + (stop - start) * i as f64 / (n - 1) as f64) + .collect(), + } +} + +fn rms_error(values: &[f64], reference: &[f64]) -> f64 { + let mse = values + .iter() + .zip(reference.iter()) + .map(|(value, reference)| { + let err = value - reference; + err * err + }) + .sum::() + / values.len().max(1) as f64; + mse.sqrt() +} diff --git a/examples/interpolation_explorer/src/main.rs b/examples/interpolation_explorer/src/main.rs new file mode 100644 index 0000000..ca420c3 --- /dev/null +++ b/examples/interpolation_explorer/src/main.rs @@ -0,0 +1,19 @@ +#![cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + +mod app; +mod plotly_support; + +#[cfg(target_arch = "wasm32")] +fn main() { + use leptos::{mount::mount_to_body, prelude::*}; + + console_error_panic_hook::set_once(); + mount_to_body(|| view! { }); +} + +#[cfg(not(target_arch = "wasm32"))] +fn main() { + eprintln!( + "This example app is intended for the wasm target. Run `trunk serve` in examples/interpolation_explorer/." + ); +} diff --git a/examples/interpolation_explorer/src/plotly_support.rs b/examples/interpolation_explorer/src/plotly_support.rs new file mode 100644 index 0000000..7f9fd5a --- /dev/null +++ b/examples/interpolation_explorer/src/plotly_support.rs @@ -0,0 +1,30 @@ +use plotly::Plot; + +pub fn use_plotly_chart

(id: &'static str, plot: P) +where + P: Fn() -> Plot + 'static, +{ + #[cfg(target_arch = "wasm32")] + { + use leptos::prelude::*; + + Effect::new(move |_| { + let mut next_plot = plot(); + let responsive_config = next_plot + .configuration() + .clone() + .responsive(true) + .autosizable(true) + .fill_frame(false); + next_plot.set_configuration(responsive_config); + wasm_bindgen_futures::spawn_local(async move { + plotly::bindings::new_plot(id, &next_plot).await; + }); + }); + } + + #[cfg(not(target_arch = "wasm32"))] + { + let _ = (id, plot); + } +} diff --git a/examples/interpolation_explorer/style.css b/examples/interpolation_explorer/style.css new file mode 100644 index 0000000..edd41ec --- /dev/null +++ b/examples/interpolation_explorer/style.css @@ -0,0 +1,309 @@ +:root { + --deimos-primary: #8232ba; + --deimos-accent: #ac37ff; + --app-background: + radial-gradient(circle at top left, rgba(172, 55, 255, 0.24), transparent 30%), + linear-gradient(180deg, #242833 0%, var(--bg) 100%); + --bg: #1e2129; + --panel: #2b2f3a; + --panel-strong: #363b48; + --sidebar-bg: rgba(31, 34, 43, 0.9); + --ink: #f2f0f6; + --muted: #b9b2c6; + --line: #47404f; + --accent: var(--deimos-primary); + --accent-soft: rgba(172, 55, 255, 0.18); + --accent-strong: var(--deimos-accent); + --warning: #ffd166; + --warning-bg: rgba(255, 209, 102, 0.16); + --success: #80ed99; + --success-bg: rgba(128, 237, 153, 0.14); + --shadow: 0 14px 34px rgba(7, 8, 12, 0.3); +} + +* { + box-sizing: border-box; +} + +html { + scroll-behavior: smooth; +} + +body { + margin: 0; + background: var(--bg); + color: var(--ink); + font-family: "IBM Plex Sans", "Avenir Next", "Segoe UI", sans-serif; +} + +button, +input, +select { + font: inherit; +} + +.app-shell { + min-height: 100vh; + display: grid; + grid-template-columns: 320px minmax(0, 1fr); + background: var(--app-background); + color: var(--ink); +} + +.app-shell.light-mode { + --app-background: + radial-gradient(circle at top left, rgba(130, 50, 186, 0.16), transparent 32%), + linear-gradient(180deg, #ffffff 0%, var(--bg) 100%); + --bg: #f6f7fb; + --panel: #ffffff; + --panel-strong: #eef1f7; + --sidebar-bg: rgba(255, 255, 255, 0.92); + --ink: #171922; + --muted: #586174; + --line: #d8deea; + --accent-soft: rgba(130, 50, 186, 0.11); + --warning: #8a5a00; + --warning-bg: rgba(255, 209, 102, 0.28); + --success: #197143; + --success-bg: rgba(25, 113, 67, 0.12); + --shadow: 0 14px 34px rgba(40, 45, 60, 0.12); +} + +.sidebar { + position: sticky; + top: 0; + height: 100vh; + padding: 1.5rem; + border-right: 1px solid var(--line); + background: var(--sidebar-bg); + backdrop-filter: blur(12px); +} + +.sidebar-title { + margin: 0 0 1rem; + font-size: 1.25rem; + font-weight: 700; + letter-spacing: 0.01em; +} + +.theme-toggle { + width: 100%; + display: flex; + align-items: center; + gap: 0.65rem; + margin-bottom: 1rem; + padding: 0.75rem 0.85rem; + border: 1px solid var(--line); + border-radius: 14px; + background: var(--panel); + color: var(--ink); + cursor: pointer; + font-weight: 700; + transition: + transform 120ms ease, + border-color 120ms ease, + background 120ms ease; +} + +.theme-toggle:hover { + transform: translateY(-1px); + border-color: var(--accent); +} + +.theme-toggle.active { + border-color: var(--accent); + background: var(--accent-soft); +} + +.theme-toggle-icon { + width: 2.25rem; + height: 1.25rem; + display: inline-flex; + align-items: center; + flex: 0 0 auto; + padding: 0.15rem; + border-radius: 999px; + background: var(--panel-strong); + border: 1px solid var(--line); +} + +.theme-toggle-icon::before { + content: ""; + width: 0.8rem; + height: 0.8rem; + border-radius: 50%; + background: var(--muted); + transition: + transform 120ms ease, + background 120ms ease; +} + +.theme-toggle.active .theme-toggle-icon::before { + transform: translateX(0.95rem); + background: var(--accent-strong); +} + +.sidebar nav { + display: grid; + gap: 0.5rem; +} + +.sidebar a { + display: block; + padding: 0.8rem 0.95rem; + border: 1px solid var(--line); + border-radius: 14px; + background: var(--panel); + color: var(--ink); + text-decoration: none; + font-weight: 650; + transition: + transform 120ms ease, + border-color 120ms ease, + background 120ms ease; +} + +.sidebar a:hover { + transform: translateY(-1px); + border-color: var(--accent); + color: var(--accent-strong); +} + +.content { + min-width: 0; + padding: 2rem; +} + +.section-block { + max-width: 1320px; + margin: 0 auto 2rem; +} + +.section-header { + margin-bottom: 0.9rem; +} + +.eyebrow { + margin: 0 0 0.25rem; + color: var(--muted); + font-size: 0.78rem; + font-weight: 750; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.section-header h2 { + margin: 0; + font-size: 1.7rem; + line-height: 1.15; + letter-spacing: 0; +} + +.control-layout { + display: grid; + grid-template-columns: 320px minmax(0, 1fr); + gap: 1rem; + min-width: 0; +} + +.control-card, +.plot-card { + border: 1px solid var(--line); + border-radius: 22px; + background: var(--panel); + box-shadow: var(--shadow); +} + +.control-card { + padding: 1rem; +} + +.control-row { + display: grid; + gap: 0.35rem; + margin-bottom: 0.85rem; +} + +.control-row label { + font-weight: 700; +} + +.control-row output, +.status-line { + color: var(--muted); + font-variant-numeric: tabular-nums; +} + +.control-row input[type="range"] { + width: 100%; + accent-color: var(--accent); +} + +.control-row select, +.control-row input[type="checkbox"] { + accent-color: var(--accent); +} + +.control-row select { + width: 100%; + padding: 0.55rem 0.65rem; + border: 1px solid var(--line); + border-radius: 8px; + background: var(--panel); + color: var(--ink); +} + +.checkbox-row { + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; +} + +.checkbox-row label { + min-width: 0; +} + +.status-line { + margin: 1rem 0 0; + padding-top: 0.8rem; + border-top: 1px solid var(--line); + line-height: 1.4; +} + +.plot-card { + min-width: 0; + overflow: hidden; +} + +.plot-surface { + min-height: 420px; + min-width: 0; + max-width: 100%; +} + +.plot-surface .js-plotly-plot, +.plot-surface .plot-container, +.plot-surface .svg-container { + width: 100% !important; + max-width: 100% !important; +} + +@media (max-width: 920px) { + .app-shell { + grid-template-columns: 1fr; + } + + .sidebar { + position: static; + height: auto; + border-right: 0; + border-bottom: 1px solid var(--line); + } + + .content { + padding: 1rem; + } + + .control-layout { + grid-template-columns: 1fr; + } +} diff --git a/pyproject.toml b/pyproject.toml index 3b90d16..7d65a4d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,18 +36,19 @@ test = [ "pyright == 1.1.407", "mktestdocs == 0.2.1", "scipy >= 1.11.4", + # More kaleido>1 crashes when used with plotly "kaleido==0.2.1", - "plotly>=5,<6", + "plotly>=6,<7", ] bench = [ "scipy >= 1.11.4", "kaleido==0.2.1", - "plotly>=5,<6", + "plotly>=6,<7", "memory_profiler >= 0.61.0", ] doc = [ "mkdocs >= 1.5.3", - "mkdocstrings-python >= 1.7.5", + "mkdocstrings-python >= 2.0.3", "mkdocs-material >= 9.4.10" ] @@ -56,7 +57,7 @@ cache-keys = [ { file = "pyproject.toml" }, { file = "Cargo.toml" }, { file = ".cargo/config.toml" }, - { file = "**/*.rs" }, + { file = "src/**/*.rs" }, { file = "scripts/pgo-profiles/interpn.profdata" }, { env = "RUSTFLAGS" }, ] diff --git a/scripts/profile_workload.py b/scripts/profile_workload.py index 267789a..ec09529 100644 --- a/scripts/profile_workload.py +++ b/scripts/profile_workload.py @@ -40,6 +40,7 @@ def _evaluate( grid_kind: str, max_threads: int | None, ) -> None: + # Run once without preallocated output to exercise allocating path interpn_fn( obs=points, grids=grids, @@ -49,6 +50,7 @@ def _evaluate( linearize_extrapolation=True, max_threads=max_threads, ) + # Run again with preallocated output out = np.empty_like(points[0]) interpn_fn( obs=points, @@ -80,6 +82,8 @@ def main() -> None: ("linear", "rectilinear", grids_rect), ("cubic", "regular", grids), ("cubic", "rectilinear", grids_rect), + ("bspline", "regular", grids), + ("bspline", "rectilinear", grids_rect), ("nearest", "regular", grids), ("nearest", "rectilinear", grids_rect), ) @@ -89,6 +93,11 @@ def main() -> None: for max_threads in (None, 1): for method, grid_kind, grids_in in cases: + # B-spline method has to do the fitting solve, + # so it's much slower than the others. + if method == "bspline": + nreps = max(nreps / 100, 1) + for _ in range(nreps): points = _observation_points(rng, ndims, nobs, dtype) _evaluate( @@ -110,5 +119,9 @@ def main() -> None: if __name__ == "__main__": main() + # Run the serial script separately. This will make another + # profile file that needs to be merged, but since we ran + # some threaded workloads, we already end up with several + # files to merge. script = Path(__file__).with_name("profile_workload_ser.py") subprocess.run([sys.executable, str(script)], check=True) diff --git a/scripts/profile_workload_ser.py b/scripts/profile_workload_ser.py index 87debc1..ecec337 100644 --- a/scripts/profile_workload_ser.py +++ b/scripts/profile_workload_ser.py @@ -6,6 +6,8 @@ import numpy as np from interpn import ( + MultiBsplineRectilinear, + MultiBsplineRegular, MulticubicRectilinear, MulticubicRegular, MultilinearRectilinear, @@ -68,11 +70,23 @@ def main() -> None: zgrid, linearize_extrapolation=True, ) + bspline_regular = MultiBsplineRegular.new( + dims, + starts, + steps, + zgrid, + linearize_extrapolation=True, + ) cubic_rect = MulticubicRectilinear.new( grids_rect, zgrid, linearize_extrapolation=True, ) + bspline_rect = MultiBsplineRectilinear.new( + grids_rect, + zgrid, + linearize_extrapolation=True, + ) nearest_regular = NearestRegular.new(dims, starts, steps, zgrid) nearest_rect = NearestRectilinear.new(grids_rect, zgrid) @@ -83,7 +97,9 @@ def main() -> None: linear_regular, linear_rect, cubic_regular, + bspline_regular, cubic_rect, + bspline_rect, nearest_regular, nearest_rect, ): diff --git a/src/interp_math.rs b/src/interp_math.rs new file mode 100644 index 0000000..9fe01fe --- /dev/null +++ b/src/interp_math.rs @@ -0,0 +1,26 @@ +use num_traits::Float; + +use crate::mul_add; + +#[inline] +pub(crate) fn dot4(weights: [T; 4], vals: [T; 4]) -> T { + let lo = mul_add(weights[1], vals[1], weights[0] * vals[0]); + let hi = mul_add(weights[3], vals[3], weights[2] * vals[2]); + lo + hi +} + +#[inline] +pub(crate) fn hermite_basis(t: T) -> [T; 4] { + let one = T::one(); + let two = one + one; + let three = two + one; + let t2 = t * t; + let t3 = t2 * t; + + [ + mul_add(two, t3, mul_add(-three, t2, one)), + mul_add(t, mul_add(t, t - two, one), T::zero()), + mul_add(-two, t3, three * t2), + mul_add(t2, t - one, T::zero()), + ] +} diff --git a/src/interpn/__init__.py b/src/interpn/__init__.py index 64cc2ef..29f3d50 100644 --- a/src/interpn/__init__.py +++ b/src/interpn/__init__.py @@ -23,6 +23,8 @@ from .multilinear_rectilinear import MultilinearRectilinear from .multicubic_regular import MulticubicRegular from .multicubic_rectilinear import MulticubicRectilinear + from .multibspline_regular import MultiBsplineRegular + from .multibspline_rectilinear import MultiBsplineRectilinear from .nearest_regular import NearestRegular from .nearest_rectilinear import NearestRectilinear @@ -43,6 +45,8 @@ "MultilinearRectilinear", "MulticubicRegular", "MulticubicRectilinear", + "MultiBsplineRegular", + "MultiBsplineRectilinear", "NearestRegular", "NearestRectilinear", ] @@ -76,7 +80,9 @@ def interpn( obs: Observation coordinates, one array per dimension. grids: Grid axis coordinates, one array per dimension. vals: Values defined on the full cartesian-product grid. - method: Interpolation kind, one of ``"linear"``, ``"cubic"``, or ``"nearest"``. + method: Interpolation kind, one of ``"linear"``, ``"cubic"``, or + ``"nearest"``. For B-spline interpolation, use + ``MultiBsplineRegular`` or ``MultiBsplineRectilinear``. out: Optional preallocated array that receives the result. linearize_extrapolation: Whether cubic extrapolation should fall back to linear behaviour outside the grid bounds. diff --git a/src/interpn/multibspline_rectilinear.py b/src/interpn/multibspline_rectilinear.py new file mode 100644 index 0000000..ac4e0f4 --- /dev/null +++ b/src/interpn/multibspline_rectilinear.py @@ -0,0 +1,166 @@ +from __future__ import annotations + +from functools import reduce + +import numpy as np +from numpy.typing import NDArray + +from pydantic import ( + model_validator, + ConfigDict, + BaseModel, +) + +from .serialization import Array, ArrayF32, ArrayF64 + +from .interpn import ( + coefficients_bspline_rectilinear_f64, + coefficients_bspline_rectilinear_f32, + _eval_bspline_rectilinear_f64, + _eval_bspline_rectilinear_f32, + check_bounds_rectilinear_f64, + check_bounds_rectilinear_f32, +) + + +class MultiBsplineRectilinear(BaseModel): + """ + Cubic B-spline interpolation on a rectilinear grid in up to 8 dimensions. + + This class owns generated B-spline coefficients as NumPy arrays. The Rust + implementation remains a borrowed interface over caller-provided storage. + + All array inputs must be of the same type, either np.float32 or np.float64, + and must be 1D and contiguous. Each dimension must have size at least 4. + """ + + model_config = ConfigDict(frozen=True, extra="forbid", arbitrary_types_allowed=True) + + grids: list[Array] + coeffs: Array + linearize_extrapolation: bool + + @classmethod + def new( + cls, + grids: list[NDArray], + vals: NDArray, + linearize_extrapolation: bool = True, + ) -> MultiBsplineRectilinear: + """ + Initialize an interpolator by generating B-spline coefficients from + nodal values. + """ + dtype = vals.dtype + arrtype = ArrayF64 if dtype == np.float64 else ArrayF32 + + vals_flat = np.ascontiguousarray(vals.flatten()) + coeffs = np.zeros_like(vals_flat) + scratch = np.zeros(2 * max(x.size for x in grids), dtype=dtype) + grids_flat = [np.ascontiguousarray(x.flatten()) for x in grids] + + if dtype == np.float64: + coefficients_bspline_rectilinear_f64(grids_flat, vals_flat, coeffs, scratch) + elif dtype == np.float32: + coefficients_bspline_rectilinear_f32(grids_flat, vals_flat, coeffs, scratch) + else: + raise TypeError(f"Unexpected data type: {dtype}") + + return cls( + grids=[arrtype(data=x) for x in grids_flat], + coeffs=arrtype(data=coeffs), + linearize_extrapolation=linearize_extrapolation, + ) + + @model_validator(mode="after") + def _validate_model(self): + ndims = self.ndims() + dims = self.dims() + assert ndims <= 8 and ndims >= 1, ( + "Number of dimensions must be at least 1 and no more than 8" + ) + assert all([x >= 4 for x in dims]), ( + "All grid dimensions must have at least 4 entries" + ) + assert self.coeffs.data.size == reduce(lambda acc, x: acc * x, dims), ( + "Size of coefficient array does not match grid dims" + ) + assert all([np.all(np.diff(x.data) > 0.0) for x in self.grids]), ( + "All grids must be monotonically increasing" + ) + assert all([x.data.dtype == self.coeffs.data.dtype for x in self.grids]), ( + "All grid inputs must be of the same data type (np.float32 or np.float64)" + ) + assert ( + all([x.data.data.contiguous for x in self.grids]) + and self.coeffs.data.data.contiguous + ), "Grid data must be contiguous" + + return self + + def ndims(self) -> int: + return len(self.grids) + + def dims(self) -> list[int]: + return [x.data.size for x in self.grids] + + def eval(self, obs: list[NDArray], out: NDArray | None = None) -> NDArray: + """Evaluate the interpolator at a set of observation points.""" + out_inner = out if out is not None else np.zeros_like(obs[0]) + self.eval_unchecked(obs, out_inner) + return out_inner + + def eval_unchecked(self, obs: list[NDArray], out: NDArray | None = None) -> NDArray: + """ + Evaluate the interpolator, skipping Python-side contiguity checks. + """ + dtype = self.coeffs.data.dtype + out_inner = out if out is not None else np.zeros_like(obs[0]) + + if dtype == np.float64: + _eval_bspline_rectilinear_f64( + [x.data for x in self.grids], + self.coeffs.data, + self.linearize_extrapolation, + obs, + out_inner, + ) + elif dtype == np.float32: + _eval_bspline_rectilinear_f32( + [x.data for x in self.grids], + self.coeffs.data, + self.linearize_extrapolation, + obs, + out_inner, + ) + else: + raise TypeError(f"Unexpected data type: {dtype}") + + return out_inner + + def check_bounds(self, obs: list[NDArray], atol: float) -> NDArray[np.bool_]: + """ + Check if the observation points violated the bounds on each dimension. + """ + ndims = self.ndims() + out = np.array([False] * ndims) + + dtype = self.coeffs.data.dtype + if dtype == np.float64: + check_bounds_rectilinear_f64( + [x.data for x in self.grids], + [x.flatten() for x in obs], + atol, + out, + ) + elif dtype == np.float32: + check_bounds_rectilinear_f32( + [x.data for x in self.grids], + [x.flatten() for x in obs], + atol, + out, + ) + else: + raise TypeError(f"Unexpected data type: {dtype}") + + return out diff --git a/src/interpn/multibspline_regular.py b/src/interpn/multibspline_regular.py new file mode 100644 index 0000000..10288da --- /dev/null +++ b/src/interpn/multibspline_regular.py @@ -0,0 +1,176 @@ +from __future__ import annotations + +from functools import reduce + +import numpy as np +from numpy.typing import NDArray + +from pydantic import ( + model_validator, + ConfigDict, + BaseModel, +) + +from .serialization import Array, ArrayF32, ArrayF64 + +from .interpn import ( + coefficients_bspline_regular_f64, + coefficients_bspline_regular_f32, + _eval_bspline_regular_f64, + _eval_bspline_regular_f32, + check_bounds_regular_f64, + check_bounds_regular_f32, +) + + +class MultiBsplineRegular(BaseModel): + """ + Cubic B-spline interpolation on a regular grid in up to 8 dimensions. + + This class owns generated B-spline coefficients as NumPy arrays. The Rust + implementation remains a borrowed interface over caller-provided storage. + + All array inputs must be of the same type, either np.float32 or np.float64, + and must be 1D and contiguous. Each dimension must have size at least 4. + """ + + model_config = ConfigDict(frozen=True, extra="forbid", arbitrary_types_allowed=True) + + dims: list[int] + starts: Array + steps: Array + coeffs: Array + linearize_extrapolation: bool + + @classmethod + def new( + cls, + dims: list[int], + starts: NDArray, + steps: NDArray, + vals: NDArray, + linearize_extrapolation: bool = True, + ) -> MultiBsplineRegular: + """ + Initialize an interpolator by generating B-spline coefficients from + nodal values. + """ + dtype = vals.dtype + arrtype = ArrayF64 if dtype == np.float64 else ArrayF32 + + vals_flat = np.ascontiguousarray(vals.flatten()) + coeffs = np.zeros_like(vals_flat) + scratch = np.zeros(2 * max(dims), dtype=dtype) + + if dtype == np.float64: + coefficients_bspline_regular_f64(dims, vals_flat, coeffs, scratch) + elif dtype == np.float32: + coefficients_bspline_regular_f32(dims, vals_flat, coeffs, scratch) + else: + raise TypeError(f"Unexpected data type: {dtype}") + + return cls( + dims=dims, + starts=arrtype(data=starts.flatten()), + steps=arrtype(data=steps.flatten()), + coeffs=arrtype(data=coeffs), + linearize_extrapolation=linearize_extrapolation, + ) + + @model_validator(mode="after") + def _validate_model(self): + ndims = self.ndims() + assert ndims <= 8 and ndims >= 1, ( + "Number of dimensions must be at least 1 and no more than 8" + ) + assert all([x >= 4 for x in self.dims]), ( + "All grid dimensions must have at least 4 entries" + ) + assert self.starts.data.size == ndims, "Grid dimension mismatch" + assert self.steps.data.size == ndims, "Grid dimension mismatch" + assert self.coeffs.data.size == reduce(lambda acc, x: acc * x, self.dims), ( + "Size of coefficient array does not match grid dims" + ) + assert all([x > 0.0 for x in self.steps.data]), ( + "All grid steps must be positive and nonzero" + ) + assert all( + [x.data.dtype == self.coeffs.data.dtype for x in [self.steps, self.coeffs]] + ), "All grid inputs must be of the same data type (np.float32 or np.float64)" + assert all( + [x.data.data.contiguous for x in [self.starts, self.steps, self.coeffs]] + ), "Grid data must be contiguous" + + return self + + def ndims(self) -> int: + return len(self.dims) + + def eval(self, obs: list[NDArray], out: NDArray | None = None) -> NDArray: + """Evaluate the interpolator at a set of observation points.""" + out_inner = out if out is not None else np.zeros_like(obs[0]) + self.eval_unchecked(obs, out_inner) + return out_inner + + def eval_unchecked(self, obs: list[NDArray], out: NDArray | None = None) -> NDArray: + """ + Evaluate the interpolator, skipping Python-side contiguity checks. + """ + dtype = self.coeffs.data.dtype + out_inner = out if out is not None else np.zeros_like(obs[0]) + + if dtype == np.float64: + _eval_bspline_regular_f64( + self.dims, + self.starts.data, + self.steps.data, + self.coeffs.data, + self.linearize_extrapolation, + obs, + out_inner, + ) + elif dtype == np.float32: + _eval_bspline_regular_f32( + self.dims, + self.starts.data, + self.steps.data, + self.coeffs.data, + self.linearize_extrapolation, + obs, + out_inner, + ) + else: + raise TypeError(f"Unexpected data type: {dtype}") + + return out_inner + + def check_bounds(self, obs: list[NDArray], atol: float) -> NDArray[np.bool_]: + """ + Check if the observation points violated the bounds on each dimension. + """ + ndims = self.ndims() + out = np.array([False] * ndims) + + dtype = self.coeffs.data.dtype + if dtype == np.float64: + check_bounds_regular_f64( + self.dims, + self.starts.data, + self.steps.data, + [x.flatten() for x in obs], + atol, + out, + ) + elif dtype == np.float32: + check_bounds_regular_f32( + self.dims, + self.starts.data, + self.steps.data, + [x.flatten() for x in obs], + atol, + out, + ) + else: + raise TypeError(f"Unexpected data type: {dtype}") + + return out diff --git a/src/interpn/raw.py b/src/interpn/raw.py index 3b80dac..35c3eb0 100644 --- a/src/interpn/raw.py +++ b/src/interpn/raw.py @@ -18,6 +18,10 @@ interpn_cubic_regular_f32, interpn_cubic_rectilinear_f64, interpn_cubic_rectilinear_f32, + coefficients_bspline_regular_f64, + coefficients_bspline_regular_f32, + coefficients_bspline_rectilinear_f64, + coefficients_bspline_rectilinear_f32, check_bounds_regular_f64, check_bounds_regular_f32, check_bounds_rectilinear_f64, @@ -39,6 +43,10 @@ "interpn_cubic_regular_f32", "interpn_cubic_rectilinear_f64", "interpn_cubic_rectilinear_f32", + "coefficients_bspline_regular_f64", + "coefficients_bspline_regular_f32", + "coefficients_bspline_rectilinear_f64", + "coefficients_bspline_rectilinear_f32", "check_bounds_regular_f64", "check_bounds_regular_f32", "check_bounds_rectilinear_f64", diff --git a/src/interpn/raw.pyi b/src/interpn/raw.pyi index e585c4c..77b474e 100644 --- a/src/interpn/raw.pyi +++ b/src/interpn/raw.pyi @@ -25,6 +25,10 @@ __all__ = [ "interpn_cubic_regular_f32", "interpn_cubic_rectilinear_f64", "interpn_cubic_rectilinear_f32", + "coefficients_bspline_regular_f64", + "coefficients_bspline_regular_f32", + "coefficients_bspline_rectilinear_f64", + "coefficients_bspline_rectilinear_f32", "check_bounds_regular_f64", "check_bounds_regular_f32", "check_bounds_rectilinear_f64", @@ -141,6 +145,30 @@ def interpn_cubic_rectilinear_f32( obs: Sequence[NDArrayF32], out: NDArrayF32, ) -> None: ... +def coefficients_bspline_regular_f64( + dims: IntArray, + vals: NDArrayF64, + coeffs: NDArrayF64, + scratch: NDArrayF64, +) -> None: ... +def coefficients_bspline_regular_f32( + dims: IntArray, + vals: NDArrayF32, + coeffs: NDArrayF32, + scratch: NDArrayF32, +) -> None: ... +def coefficients_bspline_rectilinear_f64( + grids: Sequence[NDArrayF64], + vals: NDArrayF64, + coeffs: NDArrayF64, + scratch: NDArrayF64, +) -> None: ... +def coefficients_bspline_rectilinear_f32( + grids: Sequence[NDArrayF32], + vals: NDArrayF32, + coeffs: NDArrayF32, + scratch: NDArrayF32, +) -> None: ... def check_bounds_regular_f64( dims: IntArray, starts: NDArrayF64, diff --git a/src/lib.rs b/src/lib.rs index aca68b1..b39ac61 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -90,12 +90,47 @@ use num_traits::Float; +pub(crate) mod interp_math; + +/// Returns `mul_lhs * mul_rhs + addend`. +/// +/// When the `fma` feature is enabled this uses `Float::mul_add`; otherwise it +/// falls back to the ordinary multiply-then-add expression. +#[inline] +pub(crate) fn mul_add(mul_lhs: T, mul_rhs: T, addend: T) -> T +where + T: Float, +{ + #[cfg(feature = "fma")] + { + mul_lhs.mul_add(mul_rhs, addend) + } + #[cfg(not(feature = "fma"))] + { + mul_lhs * mul_rhs + addend + } +} + +#[cfg(test)] +mod scalar_tests { + use super::mul_add; + + #[test] + fn mul_add_matches_plain_expression() { + assert_eq!(mul_add(1.25_f64, -3.0, 0.5), 1.25 * -3.0 + 0.5); + assert_eq!(mul_add(1.25_f32, -3.0, 0.5), 1.25 * -3.0 + 0.5); + } +} + pub mod multilinear; pub use multilinear::{MultilinearRectilinear, MultilinearRegular}; pub mod multicubic; pub use multicubic::{MulticubicRectilinear, MulticubicRegular}; +pub mod multibspline; +pub use multibspline::{MultiBsplineRectilinear, MultiBsplineRegular}; + pub mod linear { pub use crate::multilinear::rectilinear; pub use crate::multilinear::regular; @@ -134,7 +169,7 @@ pub(crate) mod testing; pub mod python; /// Interpolant function for multi-dimensional methods. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, PartialEq, Eq)] pub enum GridInterpMethod { /// Multi-linear interpolation. Linear, @@ -156,6 +191,7 @@ pub enum GridKind { const MAXDIMS: usize = 8; const MAXDIMS_ERR: &str = "Dimension exceeds maximum (8). Use interpolator struct directly for higher dimensions."; +#[cfg(feature = "par")] const MIN_CHUNK_SIZE: usize = 1024; /// The number of physical cores present on the machine; @@ -215,6 +251,7 @@ static PHYSICAL_CORES: LazyLock = LazyLock::new(num_cpus::get_physical); /// by an amount exceeding the provided tolerance. /// * `max_threads`: If provided, limit number of threads used to at most this number. Otherwise, /// use a heuristic to choose the number that will provide the best throughput. +/// #[cfg(feature = "par")] pub fn interpn( grids: &[&[T]], @@ -250,13 +287,8 @@ pub fn interpn( // We also use a minimum chunk size of 1024 as a heuristic, because below that limit, // single-threaded performance is usually faster due to a combination of thread spawning overhead, // memory page sizing, and improved vectorization over larger inputs. - let num_cores_physical = *PHYSICAL_CORES; // Real cores, populated on first access - let num_cores_pool = rayon::current_num_threads(); // Available cores from rayon thread pool - let num_cores_available = num_cores_physical.min(num_cores_pool).max(1); // Real max - let num_cores = match max_threads { - Some(num_cores_requested) => num_cores_requested.min(num_cores_available), - None => num_cores_available, - }; + let num_cores = parallel_thread_count(max_threads); + let chunk = MIN_CHUNK_SIZE.max(n / num_cores); // Make a shared error indicator @@ -325,6 +357,21 @@ pub fn interpn( } } +/// Resolve the effective parallelism cap used by top-level threaded dispatch. +/// +/// The caller-facing `max_threads` is clamped to at least one thread and no more +/// than the smaller of Rayon worker count and physical core count. +#[cfg(feature = "par")] +fn parallel_thread_count(max_threads: Option) -> usize { + let num_cores_physical = *PHYSICAL_CORES; // Real cores, populated on first access + let num_cores_pool = rayon::current_num_threads(); // Available cores from rayon thread pool + let num_cores_available = num_cores_physical.min(num_cores_pool).max(1); // Real max + match max_threads { + Some(num_cores_requested) => num_cores_requested.max(1).min(num_cores_available), + None => num_cores_available, + } +} + /// Allocating variant of [interpn]. /// It is recommended to pre-allocate outputs and use the non-allocating variant /// whenever possible. @@ -364,6 +411,7 @@ pub fn interpn_alloc( } /// Single-threaded, non-allocating variant of [interpn] available without `par` feature. +/// pub fn interpn_serial( grids: &[&[T]], vals: &[T], @@ -382,62 +430,11 @@ pub fn interpn_serial( // Resolve grid kind, checking the grid if the kind is not provided by the user. let kind = resolve_grid_kind(assume_grid_kind, grids)?; - // Extract regular grid params - let get_regular_grid = || { - let mut dims = [0_usize; MAXDIMS]; - let mut starts = [T::zero(); MAXDIMS]; - let mut steps = [T::zero(); MAXDIMS]; - - for (i, grid) in grids.iter().enumerate() { - if grid.len() < 2 { - return Err("All grids must have at least two entries"); - } - dims[i] = grid.len(); - starts[i] = grid[0]; - steps[i] = grid[1] - grid[0]; - } - - Ok((dims, starts, steps)) - }; - - // Bounds checks for regular grid, if requested - let maybe_check_bounds_regular = |dims: &[usize], starts: &[T], steps: &[T], obs: &[&[T]]| { - if let Some(atol) = check_bounds_with_atol { - let mut bounds = [false; MAXDIMS]; - let out = &mut bounds[..ndims]; - multilinear::regular::check_bounds( - &dims[..ndims], - &starts[..ndims], - &steps[..ndims], - obs, - atol, - out, - )?; - if bounds.iter().any(|x| *x) { - return Err("At least one observation point is outside the grid."); - } - } - Ok(()) - }; - - // Bounds checks for rectilinear grid, if requested - let maybe_check_bounds_rectilinear = |grids, obs| { - if let Some(atol) = check_bounds_with_atol { - let mut bounds = [false; MAXDIMS]; - let out = &mut bounds[..ndims]; - multilinear::rectilinear::check_bounds(grids, obs, atol, out)?; - if bounds.iter().any(|x| *x) { - return Err("At least one observation point is outside the grid."); - } - } - Ok(()) - }; - // Select lower-level method match (method, kind) { (GridInterpMethod::Linear, GridKind::Regular) => { - let (dims, starts, steps) = get_regular_grid()?; - maybe_check_bounds_regular(&dims, &starts, &steps, obs)?; + let (dims, starts, steps) = regular_grid_params(grids)?; + maybe_check_bounds_regular(&dims, &starts, &steps, obs, ndims, check_bounds_with_atol)?; linear::regular::interpn( &dims[..ndims], &starts[..ndims], @@ -448,12 +445,12 @@ pub fn interpn_serial( ) } (GridInterpMethod::Linear, GridKind::Rectilinear) => { - maybe_check_bounds_rectilinear(grids, obs)?; + maybe_check_bounds_rectilinear(grids, obs, ndims, check_bounds_with_atol)?; linear::rectilinear::interpn(grids, vals, obs, out) } (GridInterpMethod::Cubic, GridKind::Regular) => { - let (dims, starts, steps) = get_regular_grid()?; - maybe_check_bounds_regular(&dims, &starts, &steps, obs)?; + let (dims, starts, steps) = regular_grid_params(grids)?; + maybe_check_bounds_regular(&dims, &starts, &steps, obs, ndims, check_bounds_with_atol)?; cubic::regular::interpn( &dims[..ndims], &starts[..ndims], @@ -465,12 +462,12 @@ pub fn interpn_serial( ) } (GridInterpMethod::Cubic, GridKind::Rectilinear) => { - maybe_check_bounds_rectilinear(grids, obs)?; + maybe_check_bounds_rectilinear(grids, obs, ndims, check_bounds_with_atol)?; cubic::rectilinear::interpn(grids, vals, linearize_extrapolation, obs, out) } (GridInterpMethod::Nearest, GridKind::Regular) => { - let (dims, starts, steps) = get_regular_grid()?; - maybe_check_bounds_regular(&dims, &starts, &steps, obs)?; + let (dims, starts, steps) = regular_grid_params(grids)?; + maybe_check_bounds_regular(&dims, &starts, &steps, obs, ndims, check_bounds_with_atol)?; nearest::regular::interpn( &dims[..ndims], &starts[..ndims], @@ -481,12 +478,81 @@ pub fn interpn_serial( ) } (GridInterpMethod::Nearest, GridKind::Rectilinear) => { - maybe_check_bounds_rectilinear(grids, obs)?; + maybe_check_bounds_rectilinear(grids, obs, ndims, check_bounds_with_atol)?; nearest::rectilinear::interpn(grids, vals, obs, out) } } } +/// Extract regular-grid dimensions, starts, and steps from rectilinear-style +/// grid slices. +/// +/// This keeps top-level dispatch paths consistent while still allowing callers +/// to pass grids in the same shape for all methods. +fn regular_grid_params( + grids: &[&[T]], +) -> Result<([usize; MAXDIMS], [T; MAXDIMS], [T; MAXDIMS]), &'static str> { + let mut dims = [0_usize; MAXDIMS]; + let mut starts = [T::zero(); MAXDIMS]; + let mut steps = [T::zero(); MAXDIMS]; + + for (i, grid) in grids.iter().enumerate() { + if grid.len() < 2 { + return Err("All grids must have at least two entries"); + } + dims[i] = grid.len(); + starts[i] = grid[0]; + steps[i] = grid[1] - grid[0]; + } + + Ok((dims, starts, steps)) +} + +/// Run the optional top-level bounds check for regular-grid dispatch. +fn maybe_check_bounds_regular( + dims: &[usize; MAXDIMS], + starts: &[T; MAXDIMS], + steps: &[T; MAXDIMS], + obs: &[&[T]], + ndims: usize, + check_bounds_with_atol: Option, +) -> Result<(), &'static str> { + if let Some(atol) = check_bounds_with_atol { + let mut bounds = [false; MAXDIMS]; + let out = &mut bounds[..ndims]; + multilinear::regular::check_bounds( + &dims[..ndims], + &starts[..ndims], + &steps[..ndims], + obs, + atol, + out, + )?; + if bounds.iter().any(|x| *x) { + return Err("At least one observation point is outside the grid."); + } + } + Ok(()) +} + +/// Run the optional top-level bounds check for rectilinear-grid dispatch. +fn maybe_check_bounds_rectilinear( + grids: &[&[T]], + obs: &[&[T]], + ndims: usize, + check_bounds_with_atol: Option, +) -> Result<(), &'static str> { + if let Some(atol) = check_bounds_with_atol { + let mut bounds = [false; MAXDIMS]; + let out = &mut bounds[..ndims]; + multilinear::rectilinear::check_bounds(grids, obs, atol, out)?; + if bounds.iter().any(|x| *x) { + return Err("At least one observation point is outside the grid."); + } + } + Ok(()) +} + /// Figure out whether a grid is regular or rectilinear. fn resolve_grid_kind( assume_grid_kind: Option, diff --git a/src/multibspline/mod.rs b/src/multibspline/mod.rs new file mode 100644 index 0000000..a4a4e09 --- /dev/null +++ b/src/multibspline/mod.rs @@ -0,0 +1,117 @@ +//! Tensor-product cubic B-spline interpolation. +//! +//! The regular-grid implementation stores one B-spline coefficient tensor with +//! the same shape and C-style memory order as the input values. Coefficients are +//! generated by applying a one-dimensional tridiagonal solve along each axis. +//! +//! For an interior regular-grid span, four neighboring B-spline coefficients +//! define the local cubic polynomial. If `t = (x - x[i]) / h` and the footprint +//! coefficients are +//! +//! ```text +//! c0 = c[i - 1] +//! c1 = c[i] +//! c2 = c[i + 1] +//! c3 = c[i + 2] +//! ``` +//! +//! then evaluation uses the cardinal cubic B-spline basis: +//! +//! ```text +//! S(t) = c0*w0(t) + c1*w1(t) + c2*w2(t) + c3*w3(t) +//! +//! w0 = (1 - 3t + 3t^2 - t^3) / 6 +//! w1 = (4 - 6t^2 + 3t^3) / 6 +//! w2 = (1 + 3t + 3t^2 - 3t^3) / 6 +//! w3 = t^3 / 6 +//! ``` +//! +//! Equivalently, in power-basis form `S(t) = a0 + a1*t + a2*t^2 + a3*t^3`, +//! the polynomial coefficients are +//! +//! ```text +//! a0 = (c0 + 4c1 + c2) / 6 +//! a1 = (c2 - c0) / 2 +//! a2 = (c0 - 2c1 + c2) / 2 +//! a3 = (-c0 + 3c1 - 3c2 + c3) / 6 +//! ``` +//! +//! Boundary spans and rectilinear grids use the same local-footprint idea, but +//! with boundary ghost coefficients folded into the stored coefficients or with +//! nonuniform-grid basis weights. +//! +//! For a rectilinear-grid interior span, the polynomial mapping is +//! span-dependent because the local knot spacing affects the nonuniform +//! B-spline basis. For span `s`, define +//! +//! ```text +//! h = grid[s + 1] - grid[s] +//! t = (x - grid[s]) / h +//! ``` +//! +//! and let the four footprint coefficients multiply the fixed-span nonuniform +//! basis weights: +//! +//! ```text +//! S(t) = c0*b0(t) + c1*b1(t) + c2*b2(t) + c3*b3(t) +//! ``` +//! +//! where `b0..b3` are computed by the rectilinear `basis_span_weights` routine +//! for that span. To convert this span to a normalized power-basis polynomial, +//! sample the local spline at four normalized positions: +//! +//! ```text +//! t0 = 0 +//! t1 = 1/3 +//! t2 = 2/3 +//! t3 = 1 +//! +//! xr = grid[s] + tr*h +//! yr = b0(xr)*c0 + b1(xr)*c1 + b2(xr)*c2 + b3(xr)*c3 +//! ``` +//! +//! Then, for `S(t) = a0 + a1*t + a2*t^2 + a3*t^3`, +//! +//! ```text +//! a0 = y0 +//! a1 = (-11*y0 + 18*y1 - 9*y2 + 2*y3) / 2 +//! a2 = (18*y0 - 45*y1 + 36*y2 - 9*y3) / 2 +//! a3 = (-9*y0 + 27*y1 - 27*y2 + 9*y3) / 2 +//! ``` +//! +//! In physical coordinates `u = x - grid[s]`, the same polynomial is +//! +//! ```text +//! S(u) = A0 + A1*u + A2*u^2 + A3*u^3 +//! +//! A0 = a0 +//! A1 = a1 / h +//! A2 = a2 / h^2 +//! A3 = a3 / h^3 +//! ``` +//! +//! Boundary spans use the same conversion after replacing the raw nonuniform +//! basis weights with the low- or high-boundary weights that fold ghost +//! coefficients into the stored coefficient footprint. + +pub mod rectilinear; +pub mod regular; + +pub use rectilinear::MultiBsplineRectilinear; +pub use regular::MultiBsplineRegular; + +// `usize::max` is not const-stable on this MSRV, so use a local helper in +// const scratch-sizing methods. +#[cfg(feature = "par")] +pub(crate) const fn max_usize(a: usize, b: usize) -> usize { + if a > b { a } else { b } +} + +#[derive(Clone, Copy, PartialEq)] +pub(crate) enum Saturation { + None, + InsideLow, + OutsideLow, + InsideHigh, + OutsideHigh, +} diff --git a/src/multibspline/rectilinear.rs b/src/multibspline/rectilinear.rs new file mode 100644 index 0000000..5d91b00 --- /dev/null +++ b/src/multibspline/rectilinear.rs @@ -0,0 +1,1460 @@ +//! An arbitrary-dimensional cubic B-spline interpolator / extrapolator on a +//! rectilinear grid. +//! +//! Boundary spans use ghost coefficients: virtual B-spline coefficients just +//! outside the stored coefficient line. A cubic span needs four coefficients, +//! so the low boundary span naturally references `c[-1], c[0], c[1], c[2]`, +//! while the high boundary span references `c[n - 3], c[n - 2], c[n - 1], c[n]`. +//! The ghost coefficients are not stored. They are derived from the boundary +//! condition that the boundary span has zero third derivative. +//! +//! On a rectilinear grid, the ghost relations depend on the local nonuniform +//! knot spacing. The low-side relation is computed from the third derivatives +//! of the fixed-span basis weights: +//! +//! ```text +//! q[-1]*c[-1] + q[0]*c[0] + q[1]*c[1] + q[2]*c[2] = 0 +//! c[-1] = p[0]*c[0] + p[1]*c[1] + p[2]*c[2] +//! p[j] = -q[j] / q[-1] +//! ``` +//! +//! Evaluation folds the ghost coefficient into the stored coefficient footprint +//! by substitution. On the low side, the raw span expression is +//! +//! ```text +//! S = w0*c[-1] + w1*c[0] + w2*c[1] + w3*c[2] +//! ``` +//! +//! Substituting the low ghost relation and collecting terms gives stored-only +//! weights: +//! +//! ```text +//! S = (w1 + w0*p[0])*c[0] +//! + (w2 + w0*p[1])*c[1] +//! + (w3 + w0*p[2])*c[2] +//! +//! folded weights = [w1 + w0*p[0], w2 + w0*p[1], w3 + w0*p[2], 0] +//! ``` +//! +//! The high side is analogous. If +//! `c[n] = s[0]*c[n - 3] + s[1]*c[n - 2] + s[2]*c[n - 1]`, then +//! +//! ```text +//! folded weights = [ +//! 0, +//! w0 + w3*s[0], +//! w1 + w3*s[1], +//! w2 + w3*s[2], +//! ] +//! ``` +//! +//! In the uniform-grid limit these relations reduce to the regular-grid +//! formulas `c[-1] = 3c[0] - 3c[1] + c[2]` and +//! `c[n] = c[n - 3] - 3c[n - 2] + 3c[n - 1]`. + +use super::Saturation; +#[cfg(feature = "par")] +use super::max_usize; +use crate::{index_arr_fixed_dims, interp_math::dot4, mul_add}; +use crunchy::unroll; +use num_traits::Float; + +/// Construct cubic B-spline coefficients from nodal values on a rectilinear grid. +/// +/// The input values are immutable. The generated coefficients are written into +/// `coeffs`. The `scratch` buffer must have length at least +/// [`MultiBsplineRectilinear::construction_scratch_len`] for the provided +/// dimensions. +pub fn coefficients( + grids: &[&[T]; N], + vals: &[T], + coeffs: &mut [T], + scratch: &mut [T], +) -> Result<(), &'static str> { + let dims = dims_from_grids(grids); + check_dims(grids, coeffs)?; + if vals.len() != coeffs.len() { + return Err("Dimension mismatch"); + } + + let scratch_len = MultiBsplineRectilinear::::construction_scratch_len(dims); + if scratch.len() < scratch_len { + return Err("Scratch buffer is too small"); + } + + coeffs.copy_from_slice(vals); + + let max_dim = max_dim(dims); + let (upper, rhs) = scratch.split_at_mut(max_dim); + + let mut dimprod = [1_usize; N]; + populate_dimprod(dims, &mut dimprod); + + for axis in 0..N { + solve_axis(grids, dims, dimprod, axis, coeffs, upper, rhs)?; + } + + Ok(()) +} + +/// Construct cubic B-spline coefficients from nodal values on a rectilinear +/// grid, solving independent coefficient slabs in parallel. +/// +/// This is the nonallocating parallel construction path. The `scratch` buffer +/// must have length at least +/// [`MultiBsplineRectilinear::parallel_construction_scratch_len`] for the +/// provided dimensions and `max_threads`. +/// +/// Parallelism is applied one axis at a time. For each axis, the coefficient +/// tensor is divided into contiguous slabs that can be written independently. +/// In C-style memory order, the leading axis forms a single slab and falls back +/// to the serial solve for that axis. +/// +/// `max_threads` is clamped to at least one worker and to the current Rayon +/// pool size. The function does not allocate; each worker borrows its own +/// tridiagonal `upper` and `rhs` slices from `scratch`. +#[cfg(feature = "par")] +pub fn coefficients_par( + grids: &[&[T]; N], + vals: &[T], + coeffs: &mut [T], + scratch: &mut [T], + max_threads: usize, +) -> Result<(), &'static str> { + let dims = dims_from_grids(grids); + check_dims(grids, coeffs)?; + if vals.len() != coeffs.len() { + return Err("Dimension mismatch"); + } + + let scratch_len = + MultiBsplineRectilinear::::parallel_construction_scratch_len(dims, max_threads); + if scratch_len == 0 || scratch.len() < scratch_len { + return Err("Scratch buffer is too small"); + } + + coeffs.copy_from_slice(vals); + + let mut dimprod = [1_usize; N]; + populate_dimprod(dims, &mut dimprod); + + let tasks = max_threads.max(1).min(rayon::current_num_threads()).max(1); + for axis in 0..N { + solve_axis_par(grids, dims, dimprod, axis, coeffs, scratch, tasks)?; + } + + Ok(()) +} + +/// An N-dimensional cubic B-spline interpolator / extrapolator on a +/// rectilinear grid. +pub struct MultiBsplineRectilinear<'a, T: Float, const N: usize> { + /// x, y, ... coordinate grids, each entry of size dims[i] + grids: &'a [&'a [T]], + + /// Size of each dimension + dims: [usize; N], + + /// Low-side ghost coefficient relation for each axis. + low_ghost_coeffs: [[T; 3]; N], + + /// High-side ghost coefficient relation for each axis. + high_ghost_coeffs: [[T; 3]; N], + + /// B-spline coefficients, size prod(dims) + coeffs: &'a [T], + + /// Whether to extrapolate linearly instead of continuing the boundary segment + linearize_extrapolation: bool, +} + +impl<'a, T: Float, const N: usize> MultiBsplineRectilinear<'a, T, N> { + /// Number of coefficients required for `dims`. + /// + /// Returns zero if any dimension is invalid for this interpolator, if + /// `N == 0`, or if the product overflows `usize`. + pub const fn coeff_storage_len(dims: [usize; N]) -> usize { + if N == 0 { + return 0; + } + + coeff_storage_len_inner(dims, 0, 1) + } + + /// Number of scratch values required to construct coefficients for `dims`. + /// + /// Returns zero if any dimension is invalid for this interpolator, if + /// `N == 0`, or if the scratch length overflows `usize`. + pub const fn construction_scratch_len(dims: [usize; N]) -> usize { + if N == 0 { + return 0; + } + + match max_valid_dim(dims, 0, 0).checked_mul(2) { + Some(v) => v, + None => 0, + } + } + + /// Number of scratch values required to construct coefficients with + /// [`coefficients_par`] using at most `max_threads` worker tasks. + /// + /// The returned length is the maximum per-axis scratch requirement for the + /// slab decomposition used by [`coefficients_par`], not simply + /// `construction_scratch_len(dims) * max_threads`. In C-style memory order, + /// an axis can only use as many independent contiguous slabs as there are + /// prefix elements before that axis, so early axes may require less scratch + /// than the requested thread count. + /// + /// A `max_threads` value of zero is treated as one worker. + /// + /// Returns zero if any dimension is invalid for this interpolator, if + /// `N == 0`, or if the scratch length overflows `usize`. + #[cfg(feature = "par")] + pub const fn parallel_construction_scratch_len(dims: [usize; N], max_threads: usize) -> usize { + if N == 0 { + return 0; + } + + let max_threads = max_usize(max_threads, 1); + parallel_construction_scratch_len_inner(dims, max_threads, 0, 1, 0) + } + + /// Build an interpolator from precomputed coefficients. + /// + /// # Errors + /// * If dimensions do not match + /// * If any dimension has fewer than four entries + /// * If any grid is not monotonically increasing + pub fn new( + grids: &'a [&'a [T]; N], + coeffs: &'a [T], + linearize_extrapolation: bool, + ) -> Result { + check_dims(grids, coeffs)?; + let dims = dims_from_grids(grids); + let (low_ghost_coeffs, high_ghost_coeffs) = ghost_coeffs_by_axis(grids); + + Ok(Self { + grids, + dims, + low_ghost_coeffs, + high_ghost_coeffs, + coeffs, + linearize_extrapolation, + }) + } + + /// Build coefficients from nodal values using caller-provided storage, then + /// return a borrowed interpolator over those coefficients. + /// + /// This is the nonallocating construction path. `vals` is immutable input, + /// `coeffs` receives generated B-spline coefficients, and `scratch` is used + /// only during construction. + pub fn from_values_with_workspace( + grids: &'a [&'a [T]; N], + vals: &[T], + coeffs: &'a mut [T], + scratch: &mut [T], + linearize_extrapolation: bool, + ) -> Result { + coefficients(grids, vals, coeffs, scratch)?; + Self::new(grids, coeffs, linearize_extrapolation) + } + + /// Build coefficients from nodal values using caller-provided storage and a + /// caller-provided parallel construction scratch buffer, then return a + /// borrowed interpolator over those coefficients. + /// + /// This preserves the borrowed, nonallocating Rust API while allowing + /// coefficient construction to use Rayon. The caller owns `coeffs` for the + /// lifetime of the returned interpolator and owns `scratch` only during + /// construction. + #[cfg(feature = "par")] + pub fn from_values_with_workspace_par( + grids: &'a [&'a [T]; N], + vals: &[T], + coeffs: &'a mut [T], + scratch: &mut [T], + max_threads: usize, + linearize_extrapolation: bool, + ) -> Result + where + T: Send + Sync, + { + coefficients_par(grids, vals, coeffs, scratch, max_threads)?; + Self::new(grids, coeffs, linearize_extrapolation) + } + + /// Interpolate on a contiguous list of observation points. + pub fn interp(&self, x: &[&[T]; N], out: &mut [T]) -> Result<(), &'static str> { + let n = out.len(); + for i in 0..N { + if x[i].len() != n { + return Err("Dimension mismatch"); + } + } + + let mut tmp = [T::zero(); N]; + for i in 0..n { + (0..N).for_each(|j| tmp[j] = x[j][i]); + out[i] = self.interp_one(tmp)?; + } + + Ok(()) + } + + /// Interpolate the value at one point. + pub fn interp_one(&self, x: [T; N]) -> Result { + let mut origin = [0_usize; N]; + let mut span = [0_usize; N]; + let mut sat = [Saturation::None; N]; + let mut weights = [[T::zero(); FP]; N]; + let mut dimprod = [1_usize; N]; + let mut loc = [0_usize; N]; + let mut store = [[T::zero(); FP]; N]; + + populate_dimprod(self.dims, &mut dimprod); + + for i in 0..N { + (origin[i], span[i], sat[i]) = self.get_loc(x[i], i); + weights[i] = interp_weights( + self.grids[i], + span[i], + x[i], + sat[i], + self.linearize_extrapolation, + self.low_ghost_coeffs[i], + self.high_ghost_coeffs[i], + ); + } + + let nverts = const { FP.pow(N as u32) }; + + macro_rules! unroll_vertices_body { + ($i:ident) => { + for j in 0..N { + if j == 0 { + for k in 0..N { + let offset: usize = ($i & (3 << (2 * k))) >> (2 * k); + loc[k] = origin[k] + offset; + } + let store_ind: usize = $i % FP; + store[0][store_ind] = index_arr_fixed_dims(loc, dimprod, self.coeffs); + } else { + let q: usize = FP.pow(j as u32); + let level: bool = ($i + 1).is_multiple_of(q); + let p: usize = (($i + 1) / q).saturating_sub(1) % FP; + let ind: usize = j.saturating_sub(1); + + if level { + store[j][p] = dot4(weights[ind], store[ind]); + } + } + } + }; + } + + #[cfg(not(feature = "deep-unroll"))] + if N <= 3 { + unroll! { + for i < 64 in 0..nverts { + unroll_vertices_body!(i); + } + } + } else { + for i in 0..nverts { + unroll_vertices_body!(i); + } + } + + #[cfg(feature = "deep-unroll")] + if N <= 4 { + unroll! { + for i < 256 in 0..nverts { + unroll_vertices_body!(i); + } + } + } else { + for i in 0..nverts { + unroll_vertices_body!(i); + } + } + + Ok(dot4(weights[N - 1], store[N - 1])) + } + + /// Return the stored coefficient origin, knot span, and saturation region. + #[inline] + fn get_loc(&self, v: T, dim: usize) -> (usize, usize, Saturation) { + let grid = self.grids[dim]; + let n = self.dims[dim]; + let iloc: isize = grid.partition_point(|x| *x < v) as isize - 2; + + if iloc < -1 { + (0, 0, Saturation::OutsideLow) + } else if iloc == -1 { + (0, 0, Saturation::InsideLow) + } else if iloc > n as isize - 3 { + (n - 4, n - 2, Saturation::OutsideHigh) + } else if iloc == n as isize - 3 { + (n - 4, n - 2, Saturation::InsideHigh) + } else { + let span = (iloc + 1) as usize; + (span - 1, span, Saturation::None) + } + } +} + +const FP: usize = 4; + +/// Extract dimension lengths from a fixed-size array of grid slices. +fn dims_from_grids(grids: &[&[T]; N]) -> [usize; N] { + let mut dims = [0_usize; N]; + for i in 0..N { + dims[i] = grids[i].len(); + } + dims +} + +/// Precompute boundary ghost coefficient relations for each axis. +fn ghost_coeffs_by_axis(grids: &[&[T]; N]) -> ([[T; 3]; N], [[T; 3]; N]) { + let mut low = [[T::zero(); 3]; N]; + let mut high = [[T::zero(); 3]; N]; + + for i in 0..N { + low[i] = low_ghost_coeffs(grids[i]); + high[i] = high_ghost_coeffs(grids[i]); + } + + (low, high) +} + +/// Validate dimensions, coefficient storage length, and grid monotonicity. +fn check_dims(grids: &[&[T]; N], data: &[T]) -> Result<(), &'static str> { + let dims = dims_from_grids(grids); + let nvals = MultiBsplineRectilinear::::coeff_storage_len(dims); + if nvals == 0 || data.len() != nvals { + return Err("Dimension mismatch"); + } + for grid in grids { + if !grid.windows(2).all(|w| w[1] > w[0]) { + return Err("All grids must be monotonically increasing"); + } + } + Ok(()) +} + +/// Recursive implementation for [`MultiBsplineRectilinear::coeff_storage_len`]. +/// +/// This is recursive rather than a `for` loop so the public sizing function can +/// remain `const fn` on stable Rust. +const fn coeff_storage_len_inner( + dims: [usize; N], + axis: usize, + out: usize, +) -> usize { + if axis == N { + return out; + } + if dims[axis] < 4 { + return 0; + } + + match out.checked_mul(dims[axis]) { + Some(v) => coeff_storage_len_inner(dims, axis + 1, v), + None => 0, + } +} + +/// Return the largest valid dimension, or zero if any dimension is invalid. +/// +/// This is recursive rather than a `for` loop so it can be called from `const fn`. +const fn max_valid_dim(dims: [usize; N], axis: usize, max: usize) -> usize { + if axis == N { + return max; + } + if dims[axis] < 4 { + return 0; + } + + let next_max = if dims[axis] > max { dims[axis] } else { max }; + max_valid_dim(dims, axis + 1, next_max) +} + +#[cfg(feature = "par")] +/// Recursive implementation for the parallel construction scratch length. +/// +/// Each axis can use at most the number of independent prefix slabs available in +/// C-style memory order, so this tracks both the prefix slab count and the +/// largest per-axis scratch requirement. +const fn parallel_construction_scratch_len_inner( + dims: [usize; N], + max_threads: usize, + axis: usize, + prefix_slabs: usize, + max_scratch: usize, +) -> usize { + if axis == N { + return max_scratch; + } + if dims[axis] < 4 { + return 0; + } + + let tasks = if prefix_slabs < max_threads { + prefix_slabs + } else { + max_threads + }; + let scratch = match dims[axis].checked_mul(2) { + Some(v) => match v.checked_mul(tasks) { + Some(v) => v, + None => return 0, + }, + None => return 0, + }; + let next_max_scratch = if scratch > max_scratch { + scratch + } else { + max_scratch + }; + let next_prefix_slabs = match prefix_slabs.checked_mul(dims[axis]) { + Some(v) => v, + None => return 0, + }; + + parallel_construction_scratch_len_inner( + dims, + max_threads, + axis + 1, + next_prefix_slabs, + next_max_scratch, + ) +} + +/// Return the largest dimension length for runtime scratch splitting. +fn max_dim(dims: [usize; N]) -> usize { + let mut max = 0_usize; + for dim in dims { + if dim > max { + max = dim; + } + } + max +} + +/// Populate C-order strides for each dimension. +/// +/// `dimprod[axis]` is the distance in the flattened coefficient buffer between +/// neighboring coefficients along `axis`. +fn populate_dimprod(dims: [usize; N], dimprod: &mut [usize; N]) { + let mut acc = 1; + for i in 0..N { + if i > 0 { + acc *= dims[N - i]; + } + dimprod[N - i - 1] = acc; + } +} + +/// Solve every one-dimensional coefficient line along one axis. +fn solve_axis( + grids: &[&[T]; N], + dims: [usize; N], + dimprod: [usize; N], + axis: usize, + coeffs: &mut [T], + upper: &mut [T], + rhs: &mut [T], +) -> Result<(), &'static str> { + let low_ghost = low_ghost_coeffs(grids[axis]); + let high_ghost = high_ghost_coeffs(grids[axis]); + let n = dims[axis]; + let stride = dimprod[axis]; + let nlines = coeffs.len() / n; + + for line in 0..nlines { + let base = line_base_index(dims, dimprod, axis, line); + solve_line( + grids[axis], + low_ghost, + high_ghost, + base, + stride, + coeffs, + upper, + rhs, + )?; + } + + Ok(()) +} + +#[cfg(feature = "par")] +/// Solve one axis by splitting independent contiguous slabs across workers. +fn solve_axis_par( + grids: &[&[T]; N], + dims: [usize; N], + dimprod: [usize; N], + axis: usize, + coeffs: &mut [T], + scratch: &mut [T], + max_tasks: usize, +) -> Result<(), &'static str> { + let low_ghost = low_ghost_coeffs(grids[axis]); + let high_ghost = high_ghost_coeffs(grids[axis]); + let n = dims[axis]; + let stride = dimprod[axis]; + let slab_len = n * stride; + let nslabs = coeffs.len() / slab_len; + let tasks = max_tasks.min(nslabs).max(1); + let scratch_len = 2 * n * tasks; + let scratch = &mut scratch[..scratch_len]; + + if tasks == 1 { + let (upper, rhs) = scratch.split_at_mut(n); + solve_axis_slabs( + grids[axis], + low_ghost, + high_ghost, + coeffs, + slab_len, + stride, + upper, + rhs, + ) + } else { + solve_axis_slabs_par( + grids[axis], + low_ghost, + high_ghost, + coeffs, + slab_len, + stride, + scratch, + tasks, + ) + } +} + +#[cfg(feature = "par")] +/// Recursively split slab ranges so each Rayon branch owns disjoint coeff/scratch slices. +fn solve_axis_slabs_par( + grid: &[T], + low_ghost: [T; 3], + high_ghost: [T; 3], + coeffs: &mut [T], + slab_len: usize, + stride: usize, + scratch: &mut [T], + tasks: usize, +) -> Result<(), &'static str> { + let nslabs = coeffs.len() / slab_len; + if tasks <= 1 || nslabs <= 1 { + let n = grid.len(); + let (upper, rhs) = scratch.split_at_mut(n); + return solve_axis_slabs( + grid, low_ghost, high_ghost, coeffs, slab_len, stride, upper, rhs, + ); + } + + let left_slabs = nslabs / 2; + let left_tasks = tasks / 2; + let right_tasks = tasks - left_tasks; + + let n = grid.len(); + let coeff_split = left_slabs * slab_len; + let scratch_split = 2 * n * left_tasks; + let (left_coeffs, right_coeffs) = coeffs.split_at_mut(coeff_split); + let (left_scratch, right_scratch) = scratch.split_at_mut(scratch_split); + + let (left, right) = rayon::join( + || { + solve_axis_slabs_par( + grid, + low_ghost, + high_ghost, + left_coeffs, + slab_len, + stride, + left_scratch, + left_tasks, + ) + }, + || { + solve_axis_slabs_par( + grid, + low_ghost, + high_ghost, + right_coeffs, + slab_len, + stride, + right_scratch, + right_tasks, + ) + }, + ); + left?; + right +} + +#[cfg(feature = "par")] +/// Solve all coefficient lines contained in a contiguous set of slabs. +fn solve_axis_slabs( + grid: &[T], + low_ghost: [T; 3], + high_ghost: [T; 3], + coeffs: &mut [T], + slab_len: usize, + stride: usize, + upper: &mut [T], + rhs: &mut [T], +) -> Result<(), &'static str> { + for slab in coeffs.chunks_mut(slab_len) { + for base in 0..stride { + solve_line(grid, low_ghost, high_ghost, base, stride, slab, upper, rhs)?; + } + } + + Ok(()) +} + +/// Convert a line number, excluding one active axis, into a flattened base index. +fn line_base_index( + dims: [usize; N], + dimprod: [usize; N], + axis: usize, + line: usize, +) -> usize { + let mut rem = line; + let mut base = 0_usize; + + for d in (0..N).rev() { + if d != axis { + let coord = rem % dims[d]; + rem /= dims[d]; + base += coord * dimprod[d]; + } + } + + base +} + +/// Solve one nonuniform cubic B-spline coefficient line. +/// +/// The direct coefficient system remains tridiagonal with the same coefficient +/// alignment used by `MultiBsplineRegular`. At node `x[i]`, the fixed-span +/// cubic B-spline collocation row has the raw local form: +/// +/// ```text +/// l[i] c[i - 1] + m[i] c[i] + r[i] c[i + 1] = y[i] +/// ``` +/// +/// The low endpoint row initially contains the ghost coefficient: +/// +/// ```text +/// l[0] c[-1] + m[0] c[0] + r[0] c[1] = y[0] +/// ``` +/// +/// On the low boundary interval, the third derivative is constant and linear +/// in active coefficients: +/// +/// ```text +/// q[-1] c[-1] + q[0] c[0] + q[1] c[1] + q[2] c[2] = S_0''' +/// ``` +/// +/// The zero-third-derivative boundary condition gives: +/// +/// ```text +/// c[-1] = p[0] c[0] + p[1] c[1] + p[2] c[2] +/// p[j] = -q[j] / q[-1] +/// ``` +/// +/// Substituting this relation creates a temporary endpoint row involving +/// `c[0]`, `c[1]`, and `c[2]`. Combining it with the adjacent collocation row +/// eliminates `c[2]`, leaving a tridiagonal first row. The high endpoint is +/// symmetric: derive `c[n]` from the last interval's zero third derivative and +/// combine with the adjacent row to eliminate `c[n - 3]`. +/// +/// In the uniform-grid limit, the ghost relations reduce to: +/// +/// ```text +/// c[-1] = 3c[0] - 3c[1] + c[2] +/// c[n] = c[n - 3] - 3c[n - 2] + 3c[n - 1] +/// ``` +/// +/// and the row combinations reduce to the regular-grid rows: +/// +/// ```text +/// row 0: c[0] - c[1] = y[0] - y[1] +/// row 1..n-2: c[i - 1] + 4c[i] + c[i + 1] = 6y[i] +/// row n-1: -c[n - 2] + c[n - 1] = y[n - 1] - y[n - 2] +/// ``` +fn solve_line( + grid: &[T], + low_ghost: [T; 3], + high_ghost: [T; 3], + base: usize, + stride: usize, + coeffs: &mut [T], + upper: &mut [T], + rhs: &mut [T], +) -> Result<(), &'static str> { + let n = grid.len(); + if n < 4 || upper.len() < n || rhs.len() < n { + return Err("Dimension mismatch"); + } + + let (diag0, upper0, rhs0) = first_row(grid, low_ghost, coeffs[base], coeffs[base + stride]); + upper[0] = upper0 / diag0; + rhs[0] = rhs0 / diag0; + + for i in 1..n { + let (lower, diag, upper_i, y) = if i == n - 1 { + last_row( + grid, + high_ghost, + coeffs[base + (n - 2) * stride], + coeffs[base + (n - 1) * stride], + ) + } else { + let w = basis_span_weights(grid, i, grid[i]); + (w[0], w[1], w[2], coeffs[base + i * stride]) + }; + + let denom = diag - lower * upper[i - 1]; + upper[i] = upper_i / denom; + rhs[i] = (y - lower * rhs[i - 1]) / denom; + } + + for i in (0..n - 1).rev() { + rhs[i] = rhs[i] - upper[i] * rhs[i + 1]; + } + + for i in 0..n { + coeffs[base + i * stride] = rhs[i]; + } + + Ok(()) +} + +/// Build the first tridiagonal row after folding in the low ghost coefficient. +fn first_row(grid: &[T], low_ghost: [T; 3], y0: T, y1: T) -> (T, T, T) { + let w0 = basis_span_weights(grid, 0, grid[0]); + let e0 = w0[1] + w0[0] * low_ghost[0]; + let e1 = w0[2] + w0[0] * low_ghost[1]; + let e2 = w0[3] + w0[0] * low_ghost[2]; + + let w1 = basis_span_weights(grid, 1, grid[1]); + let factor = e2 / w1[2]; + (e0 - factor * w1[0], e1 - factor * w1[1], y0 - factor * y1) +} + +/// Build the last tridiagonal row after folding in the high ghost coefficient. +fn last_row(grid: &[T], high_ghost: [T; 3], y_prev: T, y_last: T) -> (T, T, T, T) { + let n = grid.len(); + let w = basis_span_weights(grid, n - 2, grid[n - 1]); + + let e0 = w[0] + w[3] * high_ghost[0]; + let e1 = w[1] + w[3] * high_ghost[1]; + let e2 = w[2] + w[3] * high_ghost[2]; + + let wadj = basis_span_weights(grid, n - 2, grid[n - 2]); + let factor = e0 / wadj[0]; + ( + e1 - factor * wadj[1], + e2 - factor * wadj[2], + T::zero(), + y_last - factor * y_prev, + ) +} + +#[inline] +/// Select the appropriate four local B-spline weights for an interpolation region. +fn interp_weights( + grid: &[T], + span: usize, + x: T, + sat: Saturation, + linearize_extrapolation: bool, + low_ghost: [T; 3], + high_ghost: [T; 3], +) -> [T; 4] { + match sat { + Saturation::None => basis_span_weights(grid, span, x), + Saturation::InsideLow => low_boundary_weights(grid, x, false, low_ghost), + Saturation::OutsideLow => low_boundary_weights(grid, x, linearize_extrapolation, low_ghost), + Saturation::InsideHigh => high_boundary_weights(grid, x, false, high_ghost), + Saturation::OutsideHigh => { + high_boundary_weights(grid, x, linearize_extrapolation, high_ghost) + } + } +} + +#[inline] +/// Low-boundary weights with the ghost coefficient folded into stored coefficients. +fn low_boundary_weights( + grid: &[T], + x: T, + linearize_extrapolation: bool, + low_ghost: [T; 3], +) -> [T; 4] { + let raw = if linearize_extrapolation { + linearized_boundary_weights(grid, 0, grid[0], x) + } else { + basis_span_weights(grid, 0, x) + }; + + [ + mul_add(raw[0], low_ghost[0], raw[1]), + mul_add(raw[0], low_ghost[1], raw[2]), + mul_add(raw[0], low_ghost[2], raw[3]), + T::zero(), + ] +} + +#[inline] +/// High-boundary weights with the ghost coefficient folded into stored coefficients. +fn high_boundary_weights( + grid: &[T], + x: T, + linearize_extrapolation: bool, + high_ghost: [T; 3], +) -> [T; 4] { + let n = grid.len(); + let raw = if linearize_extrapolation { + linearized_boundary_weights(grid, n - 2, grid[n - 1], x) + } else { + basis_span_weights(grid, n - 2, x) + }; + + [ + T::zero(), + mul_add(raw[3], high_ghost[0], raw[0]), + mul_add(raw[3], high_ghost[1], raw[1]), + mul_add(raw[3], high_ghost[2], raw[2]), + ] +} + +#[inline] +/// Affine continuation of a boundary span's value and first derivative. +fn linearized_boundary_weights(grid: &[T], span: usize, endpoint: T, x: T) -> [T; 4] { + let weights = basis_span_weights(grid, span, endpoint); + let derivs = basis_span_weight_derivatives(grid, span, endpoint); + let dx = x - endpoint; + [ + mul_add(dx, derivs[0], weights[0]), + mul_add(dx, derivs[1], weights[1]), + mul_add(dx, derivs[2], weights[2]), + mul_add(dx, derivs[3], weights[3]), + ] +} + +#[cfg(test)] +/// Evaluate the low ghost coefficient relation for tests. +fn low_ghost(grid: &[T], vals: &[T; 4]) -> T { + let p = low_ghost_coeffs(grid); + mul_add(p[2], vals[2], mul_add(p[1], vals[1], p[0] * vals[0])) +} + +#[cfg(test)] +/// Evaluate the high ghost coefficient relation for tests. +fn high_ghost(grid: &[T], vals: &[T; 4]) -> T { + let s = high_ghost_coeffs(grid); + mul_add(s[2], vals[3], mul_add(s[1], vals[2], s[0] * vals[1])) +} + +/// Coefficients expressing the low ghost as a linear combination of stored coeffs. +fn low_ghost_coeffs(grid: &[T]) -> [T; 3] { + let q = span_weight_third_derivatives(grid, 0); + [-q[1] / q[0], -q[2] / q[0], -q[3] / q[0]] +} + +/// Coefficients expressing the high ghost as a linear combination of stored coeffs. +fn high_ghost_coeffs(grid: &[T]) -> [T; 3] { + let q = span_weight_third_derivatives(grid, grid.len() - 2); + [-q[0] / q[3], -q[1] / q[3], -q[2] / q[3]] +} + +/// Third derivatives of the four fixed-span basis weights on one span. +fn span_weight_third_derivatives(grid: &[T], span: usize) -> [T; 4] { + let xs = span_samples(grid, span); + let mut values = [[T::zero(); 4]; 4]; + for i in 0..4 { + values[i] = basis_span_weights(grid, span, xs[i]); + } + + let six = T::from(6.0).unwrap(); + let mut out = [T::zero(); 4]; + for j in 0..4 { + let f = [values[0][j], values[1][j], values[2][j], values[3][j]]; + out[j] = six * third_divided_difference(xs, f); + } + out +} + +/// First derivatives of the four fixed-span basis weights at `x`. +fn basis_span_weight_derivatives(grid: &[T], span: usize, x: T) -> [T; 4] { + let xs = span_samples(grid, span); + let mut values = [[T::zero(); 4]; 4]; + for i in 0..4 { + values[i] = basis_span_weights(grid, span, xs[i]); + } + + let mut out = [T::zero(); 4]; + for j in 0..4 { + let f = [values[0][j], values[1][j], values[2][j], values[3][j]]; + out[j] = lagrange_derivative(xs, f, x); + } + out +} + +/// Four sample locations spanning one knot interval. +fn span_samples(grid: &[T], span: usize) -> [T; 4] { + let three = T::from(3.0).unwrap(); + let a = grid[span]; + let h = grid[span + 1] - a; + [a, a + h / three, a + (h + h) / three, a + h] +} + +/// Third divided difference of four samples. +fn third_divided_difference(x: [T; 4], f: [T; 4]) -> T { + let d01 = (f[1] - f[0]) / (x[1] - x[0]); + let d12 = (f[2] - f[1]) / (x[2] - x[1]); + let d23 = (f[3] - f[2]) / (x[3] - x[2]); + let d012 = (d12 - d01) / (x[2] - x[0]); + let d123 = (d23 - d12) / (x[3] - x[1]); + (d123 - d012) / (x[3] - x[0]) +} + +/// Derivative of the cubic Lagrange interpolant through four samples. +fn lagrange_derivative(x: [T; 4], f: [T; 4], at: T) -> T { + let mut out = T::zero(); + for j in 0..4 { + let mut basis_deriv = T::zero(); + for m in 0..4 { + if m == j { + continue; + } + let mut term = T::one() / (x[j] - x[m]); + for k in 0..4 { + if k != j && k != m { + term = term * (at - x[k]) / (x[j] - x[k]); + } + } + basis_deriv = basis_deriv + term; + } + out = out + f[j] * basis_deriv; + } + out +} + +/// Fixed-span cubic B-spline basis weights. +/// +/// The returned weights multiply coefficients +/// `c[span - 1]..c[span + 2]`, with ghost coefficients allowed at the two +/// boundaries. The span is held fixed, so this also gives the polynomial +/// continuation of the boundary span during extrapolation. +fn basis_span_weights(grid: &[T], span: usize, x: T) -> [T; 4] { + let i = span as isize; + let mut n = [T::zero(); 4]; + let mut left = [T::zero(); 4]; + let mut right = [T::zero(); 4]; + n[0] = T::one(); + + for j in 1..=3 { + left[j] = x - knot(grid, i + 1 - j as isize); + right[j] = knot(grid, i + j as isize) - x; + let mut saved = T::zero(); + for r in 0..j { + let denom = right[r + 1] + left[j - r]; + let temp = n[r] / denom; + n[r] = saved + right[r + 1] * temp; + saved = left[j - r] * temp; + } + n[j] = saved; + } + + n +} + +/// Return an extrapolated open-uniform knot for boundary spans. +fn knot(grid: &[T], index: isize) -> T { + let n = grid.len() as isize; + if index < 0 { + grid[0] + T::from(index).unwrap() * (grid[1] - grid[0]) + } else if index >= n { + grid[(n - 1) as usize] + + T::from(index - n + 1).unwrap() * (grid[(n - 1) as usize] - grid[(n - 2) as usize]) + } else { + grid[index as usize] + } +} + +#[cfg(test)] +mod test { + use super::*; + use crate::multibspline::regular::MultiBsplineRegular; + use crate::utils::meshgrid; + + fn reconstruct_values(grids: &[&[f64]; N], coeffs: &[f64]) -> Vec { + let dims = dims_from_grids(grids); + let mut out = coeffs.to_vec(); + let mut tmp = vec![0.0; max_dim(dims)]; + let mut dimprod = [1_usize; N]; + populate_dimprod(dims, &mut dimprod); + + for axis in 0..N { + let n = dims[axis]; + let stride = dimprod[axis]; + let nlines = out.len() / n; + + for line in 0..nlines { + let base = line_base_index(dims, dimprod, axis, line); + for i in 0..n { + tmp[i] = out[base + i * stride]; + } + + for i in 0..n { + let value = if i == 0 { + let ghost = low_ghost(grids[axis], (&tmp[0..4]).try_into().unwrap()); + let w = basis_span_weights(grids[axis], 0, grids[axis][0]); + dot4(w, [ghost, tmp[0], tmp[1], tmp[2]]) + } else if i == n - 1 { + let ghost = high_ghost(grids[axis], (&tmp[n - 4..n]).try_into().unwrap()); + let w = basis_span_weights(grids[axis], n - 2, grids[axis][n - 1]); + dot4(w, [tmp[n - 3], tmp[n - 2], tmp[n - 1], ghost]) + } else { + let w = basis_span_weights(grids[axis], i, grids[axis][i]); + dot4(w, [tmp[i - 1], tmp[i], tmp[i + 1], tmp[(i + 2).min(n - 1)]]) + }; + out[base + i * stride] = value; + } + } + } + + out + } + + fn assert_linear_extrapolation(values: [f64; 3]) { + assert!( + (values[2] - 2.0 * values[1] + values[0]).abs() < 1e-10, + "extrapolated values are not linear: {values:?}" + ); + } + + #[test] + fn test_uniform_rows_reduce_to_regular_rows() { + let grid = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]; + let p = low_ghost_coeffs(&grid); + let s = high_ghost_coeffs(&grid); + for (got, expected) in p.iter().zip([3.0, -3.0, 1.0]) { + assert!((got - expected).abs() < 1e-10, "{got} != {expected}"); + } + for (got, expected) in s.iter().zip([1.0, -3.0, 3.0]) { + assert!((got - expected).abs() < 1e-10, "{got} != {expected}"); + } + + let (d0, u0, r0) = first_row(&grid, p, 7.0, 11.0); + assert!((d0 - 1.0).abs() < 1e-10); + assert!((u0 + 1.0).abs() < 1e-10); + assert!((r0 - (7.0 - 11.0)).abs() < 1e-10); + + let (ll, dl, _, rl) = last_row(&grid, s, 13.0, 17.0); + assert!((ll + 1.0).abs() < 1e-10); + assert!((dl - 1.0).abs() < 1e-10); + assert!((rl - (17.0 - 13.0)).abs() < 1e-10); + } + + #[test] + fn test_storage_lengths() { + assert_eq!( + MultiBsplineRectilinear::::coeff_storage_len([4, 5]), + 20 + ); + assert_eq!( + MultiBsplineRectilinear::::construction_scratch_len([4, 5]), + 10 + ); + #[cfg(feature = "par")] + assert_eq!( + MultiBsplineRectilinear::::parallel_construction_scratch_len([4, 5], 4), + 40 + ); + assert_eq!( + MultiBsplineRectilinear::::coeff_storage_len([3, 5]), + 0 + ); + #[cfg(feature = "par")] + assert_eq!( + MultiBsplineRectilinear::::parallel_construction_scratch_len([4, 5], 0), + MultiBsplineRectilinear::::parallel_construction_scratch_len([4, 5], 1) + ); + } + + #[cfg(feature = "par")] + #[test] + fn test_parallel_coefficients_match_serial() { + let dims = [5_usize, 6, 7]; + let xs: Vec> = (0..3) + .map(|i| { + (0..dims[i]) + .map(|j| -1.0 + i as f64 + j as f64 * 0.31 + (j as f64).powi(2) * 0.03) + .collect() + }) + .collect(); + let grids: Vec<&[f64]> = xs.iter().map(|x| &x[..]).collect(); + let grids_ref: &[&[f64]; 3] = grids.as_slice().try_into().unwrap(); + let grid = meshgrid((0..3).map(|i| &xs[i]).collect()); + let vals: Vec = grid + .iter() + .map(|x| { + x.iter() + .enumerate() + .map(|(i, v)| (i as f64 + 0.5) * v.sin() + v * v) + .sum() + }) + .collect(); + + let nvals = MultiBsplineRectilinear::::coeff_storage_len(dims); + let serial_scratch_len = MultiBsplineRectilinear::::construction_scratch_len(dims); + let parallel_scratch_len = + MultiBsplineRectilinear::::parallel_construction_scratch_len(dims, 4); + + let mut serial_coeffs = vec![0.0; nvals]; + let mut serial_scratch = vec![0.0; serial_scratch_len]; + coefficients(grids_ref, &vals, &mut serial_coeffs, &mut serial_scratch).unwrap(); + + let mut parallel_coeffs = vec![0.0; nvals]; + let mut parallel_scratch = vec![0.0; parallel_scratch_len]; + coefficients_par( + grids_ref, + &vals, + &mut parallel_coeffs, + &mut parallel_scratch, + 4, + ) + .unwrap(); + + for i in 0..nvals { + assert!( + (serial_coeffs[i] - parallel_coeffs[i]).abs() < 1e-12, + "coefficient mismatch at {i}: {} vs {}", + serial_coeffs[i], + parallel_coeffs[i] + ); + } + } + + #[test] + fn test_coefficients_reconstruct_values_1d_to_3d() { + for ndims in 1..=3 { + crate::dispatch_ndims!(ndims, "bad dims", [1, 2, 3], |N| { + let dims = [6_usize; N]; + let xs: Vec> = (0..N) + .map(|i| { + let start = -1.5 * (i as f64 + 1.0); + (0..dims[i]) + .map(|j| start + (j as f64).powi(2) * 0.21 + j as f64 * 0.37) + .collect() + }) + .collect(); + let grids: Vec<&[f64]> = xs.iter().map(|x| &x[..]).collect(); + let grid = meshgrid((0..N).map(|i| &xs[i]).collect()); + let vals: Vec = grid + .iter() + .map(|x| { + x.iter() + .enumerate() + .map(|(i, v)| (i as f64 + 1.0) * v * v + 0.25 * v) + .sum() + }) + .collect(); + + let nvals = MultiBsplineRectilinear::::coeff_storage_len(dims); + let scratch_len = MultiBsplineRectilinear::::construction_scratch_len(dims); + let mut coeffs = vec![0.0; nvals]; + let mut scratch = vec![0.0; scratch_len]; + let grids_ref: &[&[f64]; N] = grids.as_slice().try_into().unwrap(); + coefficients::(grids_ref, &vals, &mut coeffs, &mut scratch).unwrap(); + let reconstructed = reconstruct_values::(grids_ref, &coeffs); + + for i in 0..vals.len() { + assert!( + (vals[i] - reconstructed[i]).abs() < 1e-9, + "{ndims}D mismatch at {i}: {} vs {}", + vals[i], + reconstructed[i] + ); + } + Ok(()) + }) + .unwrap(); + } + } + + #[test] + fn test_interp_reproduces_grid_values_1d_to_3d() { + for ndims in 1..=3 { + crate::dispatch_ndims!(ndims, "bad dims", [1, 2, 3], |N| { + let dims = [6_usize; N]; + let xs: Vec> = (0..N) + .map(|i| { + (0..dims[i]) + .map(|j| -1.0 + j as f64 * 0.4 + (j as f64).powi(2) * 0.05) + .collect() + }) + .collect(); + let grids: Vec<&[f64]> = xs.iter().map(|x| &x[..]).collect(); + let grid = meshgrid((0..N).map(|i| &xs[i]).collect()); + let vals: Vec = grid + .iter() + .map(|x| x.iter().map(|v| v * v + 0.3 * v).sum()) + .collect(); + let obs: Vec> = (0..N) + .map(|i| grid.iter().map(|x| x[i]).collect()) + .collect(); + let obs_ref: Vec<&[f64]> = obs.iter().map(|x| &x[..]).collect(); + + let nvals = MultiBsplineRectilinear::::coeff_storage_len(dims); + let scratch_len = MultiBsplineRectilinear::::construction_scratch_len(dims); + let mut coeffs = vec![0.0; nvals]; + let mut scratch = vec![0.0; scratch_len]; + let grids_ref: &[&[f64]; N] = grids.as_slice().try_into().unwrap(); + let obs_ref: &[&[f64]; N] = obs_ref.as_slice().try_into().unwrap(); + let interp: MultiBsplineRectilinear<'_, f64, N> = + MultiBsplineRectilinear::from_values_with_workspace( + grids_ref, + &vals, + &mut coeffs, + &mut scratch, + false, + ) + .unwrap(); + + let mut out = vec![0.0; vals.len()]; + interp.interp(obs_ref, &mut out).unwrap(); + + for i in 0..vals.len() { + assert!((vals[i] - out[i]).abs() < 1e-9); + } + Ok(()) + }) + .unwrap(); + } + } + + #[test] + fn test_uniform_grid_matches_regular() { + let dims = [6_usize, 5]; + let starts = [-0.5_f64, 1.25]; + let steps = [0.4_f64, 0.7]; + let xs: Vec> = (0..2) + .map(|i| { + (0..dims[i]) + .map(|j| starts[i] + steps[i] * j as f64) + .collect() + }) + .collect(); + let grids: Vec<&[f64]> = xs.iter().map(|x| &x[..]).collect(); + let grids_ref: &[&[f64]; 2] = grids.as_slice().try_into().unwrap(); + let grid = meshgrid(vec![&xs[0], &xs[1]]); + let vals: Vec = grid + .iter() + .map(|x| x[0] * x[0] + 0.25 * x[1] * x[1] + x[0] * x[1]) + .collect(); + + let nvals = MultiBsplineRectilinear::::coeff_storage_len(dims); + let scratch_len = MultiBsplineRectilinear::::construction_scratch_len(dims); + let mut rect_coeffs = vec![0.0; nvals]; + let mut rect_scratch = vec![0.0; scratch_len]; + coefficients::(grids_ref, &vals, &mut rect_coeffs, &mut rect_scratch).unwrap(); + + let mut reg_coeffs = vec![0.0; nvals]; + let mut reg_scratch = + vec![0.0; MultiBsplineRegular::::construction_scratch_len(dims)]; + crate::multibspline::regular::coefficients(dims, &vals, &mut reg_coeffs, &mut reg_scratch) + .unwrap(); + + for i in 0..nvals { + assert!((rect_coeffs[i] - reg_coeffs[i]).abs() < 1e-9); + } + } + + #[test] + fn test_quadratic_truth_with_extrapolation() { + let x = [-1.0, -0.35, 0.2, 0.95, 1.8, 3.0]; + let y = [-2.0, -1.25, -0.1, 0.55, 1.7]; + let grids = [&x[..], &y[..]]; + let dims = [x.len(), y.len()]; + let x_vec = x.to_vec(); + let y_vec = y.to_vec(); + let grid = meshgrid(vec![&x_vec, &y_vec]); + let truth = |p: &[f64]| 0.5 * p[0] * p[0] + 0.25 * p[1] * p[1] + p[0] * p[1] - 0.3; + let vals: Vec = grid.iter().map(|p| truth(p)).collect(); + + let nvals = MultiBsplineRectilinear::::coeff_storage_len(dims); + let scratch_len = MultiBsplineRectilinear::::construction_scratch_len(dims); + let mut coeffs = vec![0.0; nvals]; + let mut scratch = vec![0.0; scratch_len]; + let interp = MultiBsplineRectilinear::from_values_with_workspace( + &grids, + &vals, + &mut coeffs, + &mut scratch, + false, + ) + .unwrap(); + + let xobs = [-1.5, -0.7, 0.0, 1.2, 3.4]; + let yobs = [-2.4, -0.9, 0.2, 1.2, 2.2]; + let obs = [&xobs[..], &yobs[..]]; + let mut out = vec![0.0; xobs.len()]; + interp.interp(&obs, &mut out).unwrap(); + + for i in 0..out.len() { + let expected = truth(&[xobs[i], yobs[i]]); + assert!( + (out[i] - expected).abs() < 1e-9, + "{} != {} at {i}", + out[i], + expected + ); + } + } + + #[test] + fn test_linearized_extrapolation_is_linear_outside_grid() { + let x = [-1.0_f64, -0.2, 0.35, 1.4, 2.8, 4.0]; + let grids = [&x[..]]; + let dims = [x.len()]; + let vals: Vec = x + .iter() + .map(|&x| x * x * x - 0.5 * x * x + 2.0 * x) + .collect(); + let mut coeffs = vec![0.0; MultiBsplineRectilinear::::coeff_storage_len(dims)]; + let mut scratch = + vec![0.0; MultiBsplineRectilinear::::construction_scratch_len(dims)]; + + let interp = MultiBsplineRectilinear::from_values_with_workspace( + &grids, + &vals, + &mut coeffs, + &mut scratch, + true, + ) + .unwrap(); + + assert_linear_extrapolation([ + interp.interp_one([-1.0]).unwrap(), + interp.interp_one([-1.6]).unwrap(), + interp.interp_one([-2.2]).unwrap(), + ]); + assert_linear_extrapolation([ + interp.interp_one([4.0]).unwrap(), + interp.interp_one([4.7]).unwrap(), + interp.interp_one([5.4]).unwrap(), + ]); + } +} diff --git a/src/multibspline/regular.rs b/src/multibspline/regular.rs new file mode 100644 index 0000000..6499a16 --- /dev/null +++ b/src/multibspline/regular.rs @@ -0,0 +1,1121 @@ +//! An arbitrary-dimensional cubic B-spline interpolator / extrapolator on a regular grid. +//! +//! Boundary spans use ghost coefficients: virtual B-spline coefficients just +//! outside the stored coefficient line. A cubic span needs four coefficients, +//! so the low boundary span naturally references `c[-1], c[0], c[1], c[2]`, +//! while the high boundary span references `c[n - 3], c[n - 2], c[n - 1], c[n]`. +//! The ghost coefficients are not stored. They are derived from the boundary +//! condition that the boundary span has zero third derivative: +//! +//! ```text +//! c[-1] = 3c[0] - 3c[1] + c[2] +//! c[n] = c[n - 3] - 3c[n - 2] + 3c[n - 1] +//! ``` +//! +//! Evaluation folds each ghost coefficient into the stored coefficient +//! footprint by substitution. On the low side, the raw span expression is +//! +//! ```text +//! S = w0*c[-1] + w1*c[0] + w2*c[1] + w3*c[2] +//! ``` +//! +//! Substituting the low ghost relation and collecting terms gives stored-only +//! weights: +//! +//! ```text +//! S = (w1 + 3w0)*c[0] + (w2 - 3w0)*c[1] + (w3 + w0)*c[2] +//! +//! folded weights = [w1 + 3w0, w2 - 3w0, w3 + w0, 0] +//! ``` +//! +//! The high side is analogous: +//! +//! ```text +//! S = w0*c[n - 3] + w1*c[n - 2] + w2*c[n - 1] + w3*c[n] +//! +//! folded weights = [0, w0 + w3, w1 - 3w3, w2 + 3w3] +//! ``` +//! +//! This keeps the evaluator using the same four-slot local footprint while +//! avoiding storage for coefficients outside the grid. + +use super::Saturation; +#[cfg(feature = "par")] +use super::max_usize; +use crate::{index_arr_fixed_dims, interp_math::dot4, mul_add}; +use crunchy::unroll; +use num_traits::{Float, NumCast}; + +/// Construct cubic B-spline coefficients from nodal values on a regular grid. +/// +/// The input values are immutable. The generated coefficients are written into `coeffs`. +/// The `scratch` buffer must have length at least +/// [`MultiBsplineRegular::construction_scratch_len`] for the provided dimensions. +pub fn coefficients( + dims: [usize; N], + vals: &[T], + coeffs: &mut [T], + scratch: &mut [T], +) -> Result<(), &'static str> { + check_dims(dims, coeffs)?; + if vals.len() != coeffs.len() { + return Err("Dimension mismatch"); + } + + let scratch_len = MultiBsplineRegular::::construction_scratch_len(dims); + if scratch.len() < scratch_len { + return Err("Scratch buffer is too small"); + } + + coeffs.copy_from_slice(vals); + + let max_dim = max_dim(dims); + let (upper, rhs) = scratch.split_at_mut(max_dim); + + let mut dimprod = [1_usize; N]; + populate_dimprod(dims, &mut dimprod); + + for axis in 0..N { + solve_axis(dims, dimprod, axis, coeffs, upper, rhs)?; + } + + Ok(()) +} + +/// Construct cubic B-spline coefficients from nodal values on a regular grid, +/// solving independent coefficient slabs in parallel. +/// +/// This is the nonallocating parallel construction path. The `scratch` buffer +/// must have length at least +/// [`MultiBsplineRegular::parallel_construction_scratch_len`] for the provided +/// dimensions and `max_threads`. +/// +/// Parallelism is applied one axis at a time. For each axis, the coefficient +/// tensor is divided into contiguous slabs that can be written independently. +/// In C-style memory order, the leading axis forms a single slab and falls back +/// to the serial solve for that axis. +/// +/// `max_threads` is clamped to at least one worker and to the current Rayon +/// pool size. The function does not allocate; each worker borrows its own +/// tridiagonal `upper` and `rhs` slices from `scratch`. +#[cfg(feature = "par")] +pub fn coefficients_par( + dims: [usize; N], + vals: &[T], + coeffs: &mut [T], + scratch: &mut [T], + max_threads: usize, +) -> Result<(), &'static str> { + check_dims(dims, coeffs)?; + if vals.len() != coeffs.len() { + return Err("Dimension mismatch"); + } + + let scratch_len = + MultiBsplineRegular::::parallel_construction_scratch_len(dims, max_threads); + if scratch_len == 0 || scratch.len() < scratch_len { + return Err("Scratch buffer is too small"); + } + + coeffs.copy_from_slice(vals); + + let mut dimprod = [1_usize; N]; + populate_dimprod(dims, &mut dimprod); + + let tasks = max_threads.max(1).min(rayon::current_num_threads()).max(1); + for axis in 0..N { + solve_axis_par(dims, dimprod, axis, coeffs, scratch, tasks)?; + } + + Ok(()) +} + +/// An N-dimensional cubic B-spline interpolator / extrapolator on a regular grid. +/// +/// Assumes C-style ordering of coeffs (z(x0, y0), z(x0, y1), ..., z(x0, yn), z(x1, y0), ...). +pub struct MultiBsplineRegular<'a, T: Float, const N: usize> { + /// Size of each dimension + dims: [usize; N], + + /// Starting point of each dimension + starts: [T; N], + + /// Step size for each dimension + steps: [T; N], + + /// B-spline coefficients, size prod(dims) + coeffs: &'a [T], + + /// Whether to extrapolate linearly instead of continuing the boundary segment + linearize_extrapolation: bool, +} + +impl<'a, T: Float, const N: usize> MultiBsplineRegular<'a, T, N> { + /// Number of coefficients required for `dims`. + /// + /// Returns zero if any dimension is invalid for this interpolator, if `N == 0`, + /// or if the product overflows `usize`. + pub const fn coeff_storage_len(dims: [usize; N]) -> usize { + if N == 0 { + return 0; + } + + coeff_storage_len_inner(dims, 0, 1) + } + + /// Number of scratch values required to construct coefficients for `dims`. + /// + /// Returns zero if any dimension is invalid for this interpolator, if `N == 0`, + /// or if the scratch length overflows `usize`. + pub const fn construction_scratch_len(dims: [usize; N]) -> usize { + if N == 0 { + return 0; + } + + match max_valid_dim(dims, 0, 0).checked_mul(2) { + Some(v) => v, + None => 0, + } + } + + /// Number of scratch values required to construct coefficients with + /// [`coefficients_par`] using at most `max_threads` worker tasks. + /// + /// The returned length is the maximum per-axis scratch requirement for the + /// slab decomposition used by [`coefficients_par`], not simply + /// `construction_scratch_len(dims) * max_threads`. In C-style memory order, + /// an axis can only use as many independent contiguous slabs as there are + /// prefix elements before that axis, so early axes may require less scratch + /// than the requested thread count. + /// + /// A `max_threads` value of zero is treated as one worker. + /// + /// Returns zero if any dimension is invalid for this interpolator, if + /// `N == 0`, or if the scratch length overflows `usize`. + #[cfg(feature = "par")] + pub const fn parallel_construction_scratch_len(dims: [usize; N], max_threads: usize) -> usize { + if N == 0 { + return 0; + } + + let max_threads = max_usize(max_threads, 1); + parallel_construction_scratch_len_inner(dims, max_threads, 0, 1, 0) + } + + /// Build an interpolator from precomputed coefficients. + /// + /// # Errors + /// * If dimensions do not match + /// * If any dimension has fewer than four entries + /// * If any step size is zero or negative + pub fn new( + dims: [usize; N], + starts: [T; N], + steps: [T; N], + coeffs: &'a [T], + linearize_extrapolation: bool, + ) -> Result { + check_dims(dims, coeffs)?; + if !steps.iter().all(|&x| x > T::zero()) { + return Err("All grids must be monotonically increasing"); + } + + let mut steps_local = [T::zero(); N]; + let mut starts_local = [T::zero(); N]; + let mut dims_local = [0_usize; N]; + steps_local[..N].copy_from_slice(&steps[..N]); + starts_local[..N].copy_from_slice(&starts[..N]); + dims_local[..N].copy_from_slice(&dims[..N]); + + Ok(Self { + dims: dims_local, + starts: starts_local, + steps: steps_local, + coeffs, + linearize_extrapolation, + }) + } + + /// Build coefficients from nodal values using caller-provided storage, then + /// return a borrowed interpolator over those coefficients. + /// + /// This is the nonallocating construction path. `vals` is immutable input, + /// `coeffs` receives generated B-spline coefficients, and `scratch` is used + /// only during construction. + pub fn from_values_with_workspace( + dims: [usize; N], + starts: [T; N], + steps: [T; N], + vals: &[T], + coeffs: &'a mut [T], + scratch: &mut [T], + linearize_extrapolation: bool, + ) -> Result { + coefficients(dims, vals, coeffs, scratch)?; + Self::new(dims, starts, steps, coeffs, linearize_extrapolation) + } + + /// Build coefficients from nodal values using caller-provided storage and a + /// caller-provided parallel construction scratch buffer, then return a + /// borrowed interpolator over those coefficients. + /// + /// This preserves the borrowed, nonallocating Rust API while allowing + /// coefficient construction to use Rayon. The caller owns `coeffs` for the + /// lifetime of the returned interpolator and owns `scratch` only during + /// construction. + #[cfg(feature = "par")] + pub fn from_values_with_workspace_par( + dims: [usize; N], + starts: [T; N], + steps: [T; N], + vals: &[T], + coeffs: &'a mut [T], + scratch: &mut [T], + max_threads: usize, + linearize_extrapolation: bool, + ) -> Result + where + T: Send + Sync, + { + coefficients_par(dims, vals, coeffs, scratch, max_threads)?; + Self::new(dims, starts, steps, coeffs, linearize_extrapolation) + } + + /// Interpolate on a contiguous list of observation points. + /// + /// Assumes C-style ordering of coeffs. + pub fn interp(&self, x: &[&[T]; N], out: &mut [T]) -> Result<(), &'static str> { + let n = out.len(); + for i in 0..N { + if x[i].len() != n { + return Err("Dimension mismatch"); + } + } + + let mut tmp = [T::zero(); N]; + for i in 0..n { + (0..N).for_each(|j| tmp[j] = x[j][i]); + out[i] = self.interp_one(tmp)?; + } + + Ok(()) + } + + /// Interpolate the value at one point. + /// + /// Uses fixed-size intermediate storage of O(N) and no allocation. + pub fn interp_one(&self, x: [T; N]) -> Result { + let mut origin = [0_usize; N]; + let mut sat = [Saturation::None; N]; + let mut weights = [[T::zero(); FP]; N]; + let mut dimprod = [1_usize; N]; + let mut loc = [0_usize; N]; + let mut store = [[T::zero(); FP]; N]; + + populate_dimprod(self.dims, &mut dimprod); + + for i in 0..N { + (origin[i], sat[i]) = self.get_loc(x[i], i)?; + let origin_f = + ::from(origin[i] + 1).ok_or("Unrepresentable coordinate value")?; + let index_one_loc = mul_add(self.steps[i], origin_f, self.starts[i]); + let t = (x[i] - index_one_loc) / self.steps[i]; + weights[i] = interp_weights(t, sat[i], self.linearize_extrapolation); + } + + let nverts = const { FP.pow(N as u32) }; + + macro_rules! unroll_vertices_body { + ($i:ident) => { + for j in 0..N { + if j == 0 { + for k in 0..N { + let offset: usize = ($i & (3 << (2 * k))) >> (2 * k); + loc[k] = origin[k] + offset; + } + let store_ind: usize = $i % FP; + store[0][store_ind] = index_arr_fixed_dims(loc, dimprod, self.coeffs); + } else { + let q: usize = FP.pow(j as u32); + let level: bool = ($i + 1).is_multiple_of(q); + let p: usize = (($i + 1) / q).saturating_sub(1) % FP; + let ind: usize = j.saturating_sub(1); + + if level { + store[j][p] = dot4(weights[ind], store[ind]); + } + } + } + }; + } + + #[cfg(not(feature = "deep-unroll"))] + if N <= 3 { + unroll! { + for i < 64 in 0..nverts { + unroll_vertices_body!(i); + } + } + } else { + for i in 0..nverts { + unroll_vertices_body!(i); + } + } + + #[cfg(feature = "deep-unroll")] + if N <= 4 { + unroll! { + for i < 256 in 0..nverts { + unroll_vertices_body!(i); + } + } + } else { + for i in 0..nverts { + unroll_vertices_body!(i); + } + } + + Ok(dot4(weights[N - 1], store[N - 1])) + } + + /// Get the two-lower index along this dimension where `x` is found, + /// saturating to the bounds at the edges if necessary. + #[inline] + fn get_loc(&self, v: T, dim: usize) -> Result<(usize, Saturation), &'static str> { + let floc = ((v - self.starts[dim]) / self.steps[dim]).floor(); + let iloc = ::from(floc).ok_or("Unrepresentable coordinate value")? - 1; + + let n = self.dims[dim] as isize; + let dimmax = n.saturating_sub(4).max(0); + let loc = iloc.max(0).min(dimmax) as usize; + + let saturation = if iloc < -1 { + Saturation::OutsideLow + } else if iloc == -1 { + Saturation::InsideLow + } else if iloc > n - 3 { + Saturation::OutsideHigh + } else if iloc == n - 3 { + Saturation::InsideHigh + } else { + Saturation::None + }; + + Ok((loc, saturation)) + } +} + +const FP: usize = 4; + +/// Validate that dimensions and coefficient storage agree. +fn check_dims(dims: [usize; N], data: &[T]) -> Result<(), &'static str> { + let nvals = MultiBsplineRegular::::coeff_storage_len(dims); + if nvals == 0 || data.len() != nvals { + return Err("Dimension mismatch"); + } + Ok(()) +} + +/// Recursive implementation for [`MultiBsplineRegular::coeff_storage_len`]. +/// +/// This is recursive rather than a `for` loop so the public sizing function can +/// remain `const fn` on stable Rust. +const fn coeff_storage_len_inner( + dims: [usize; N], + axis: usize, + out: usize, +) -> usize { + if axis == N { + return out; + } + if dims[axis] < 4 { + return 0; + } + + match out.checked_mul(dims[axis]) { + Some(v) => coeff_storage_len_inner(dims, axis + 1, v), + None => 0, + } +} + +/// Return the largest valid dimension, or zero if any dimension is invalid. +/// +/// This is recursive rather than a `for` loop so it can be called from `const fn`. +const fn max_valid_dim(dims: [usize; N], axis: usize, max: usize) -> usize { + if axis == N { + return max; + } + if dims[axis] < 4 { + return 0; + } + + let next_max = if dims[axis] > max { dims[axis] } else { max }; + max_valid_dim(dims, axis + 1, next_max) +} + +#[cfg(feature = "par")] +/// Recursive implementation for the parallel construction scratch length. +/// +/// Each axis can use at most the number of independent prefix slabs available in +/// C-style memory order, so this tracks both the prefix slab count and the +/// largest per-axis scratch requirement. +const fn parallel_construction_scratch_len_inner( + dims: [usize; N], + max_threads: usize, + axis: usize, + prefix_slabs: usize, + max_scratch: usize, +) -> usize { + if axis == N { + return max_scratch; + } + if dims[axis] < 4 { + return 0; + } + + let tasks = if prefix_slabs < max_threads { + prefix_slabs + } else { + max_threads + }; + let scratch = match dims[axis].checked_mul(2) { + Some(v) => match v.checked_mul(tasks) { + Some(v) => v, + None => return 0, + }, + None => return 0, + }; + let next_max_scratch = if scratch > max_scratch { + scratch + } else { + max_scratch + }; + let next_prefix_slabs = match prefix_slabs.checked_mul(dims[axis]) { + Some(v) => v, + None => return 0, + }; + + parallel_construction_scratch_len_inner( + dims, + max_threads, + axis + 1, + next_prefix_slabs, + next_max_scratch, + ) +} + +/// Return the largest dimension length for runtime scratch splitting. +fn max_dim(dims: [usize; N]) -> usize { + let mut max = 0_usize; + for dim in dims { + if dim > max { + max = dim; + } + } + max +} + +/// Populate C-order strides for each dimension. +/// +/// `dimprod[axis]` is the distance in the flattened coefficient buffer between +/// neighboring coefficients along `axis`. +fn populate_dimprod(dims: [usize; N], dimprod: &mut [usize; N]) { + let mut acc = 1; + for i in 0..N { + if i > 0 { + acc *= dims[N - i]; + } + dimprod[N - i - 1] = acc; + } +} + +/// Solve every one-dimensional coefficient line along one axis. +fn solve_axis( + dims: [usize; N], + dimprod: [usize; N], + axis: usize, + coeffs: &mut [T], + upper: &mut [T], + rhs: &mut [T], +) -> Result<(), &'static str> { + let n = dims[axis]; + let stride = dimprod[axis]; + let nlines = coeffs.len() / n; + + for line in 0..nlines { + let base = line_base_index(dims, dimprod, axis, line); + solve_line(base, stride, n, coeffs, upper, rhs)?; + } + + Ok(()) +} + +#[cfg(feature = "par")] +/// Solve one axis by splitting independent contiguous slabs across workers. +fn solve_axis_par( + dims: [usize; N], + dimprod: [usize; N], + axis: usize, + coeffs: &mut [T], + scratch: &mut [T], + max_tasks: usize, +) -> Result<(), &'static str> { + let n = dims[axis]; + let stride = dimprod[axis]; + let slab_len = n * stride; + let nslabs = coeffs.len() / slab_len; + let tasks = max_tasks.min(nslabs).max(1); + let scratch_len = 2 * n * tasks; + let scratch = &mut scratch[..scratch_len]; + + if tasks == 1 { + let (upper, rhs) = scratch.split_at_mut(n); + solve_axis_slabs(coeffs, slab_len, stride, n, upper, rhs) + } else { + solve_axis_slabs_par(coeffs, slab_len, stride, n, scratch, tasks) + } +} + +#[cfg(feature = "par")] +/// Recursively split slab ranges so each Rayon branch owns disjoint coeff/scratch slices. +fn solve_axis_slabs_par( + coeffs: &mut [T], + slab_len: usize, + stride: usize, + n: usize, + scratch: &mut [T], + tasks: usize, +) -> Result<(), &'static str> { + let nslabs = coeffs.len() / slab_len; + if tasks <= 1 || nslabs <= 1 { + let (upper, rhs) = scratch.split_at_mut(n); + return solve_axis_slabs(coeffs, slab_len, stride, n, upper, rhs); + } + + let left_slabs = nslabs / 2; + let left_tasks = tasks / 2; + let right_tasks = tasks - left_tasks; + + let coeff_split = left_slabs * slab_len; + let scratch_split = 2 * n * left_tasks; + let (left_coeffs, right_coeffs) = coeffs.split_at_mut(coeff_split); + let (left_scratch, right_scratch) = scratch.split_at_mut(scratch_split); + + let (left, right) = rayon::join( + || solve_axis_slabs_par(left_coeffs, slab_len, stride, n, left_scratch, left_tasks), + || { + solve_axis_slabs_par( + right_coeffs, + slab_len, + stride, + n, + right_scratch, + right_tasks, + ) + }, + ); + left?; + right +} + +#[cfg(feature = "par")] +/// Solve all coefficient lines contained in a contiguous set of slabs. +fn solve_axis_slabs( + coeffs: &mut [T], + slab_len: usize, + stride: usize, + n: usize, + upper: &mut [T], + rhs: &mut [T], +) -> Result<(), &'static str> { + for slab in coeffs.chunks_mut(slab_len) { + for base in 0..stride { + solve_line(base, stride, n, slab, upper, rhs)?; + } + } + + Ok(()) +} + +/// Convert a line number, excluding one active axis, into a flattened base index. +fn line_base_index( + dims: [usize; N], + dimprod: [usize; N], + axis: usize, + line: usize, +) -> usize { + let mut rem = line; + let mut base = 0_usize; + + for d in (0..N).rev() { + if d != axis { + let coord = rem % dims[d]; + rem /= dims[d]; + base += coord * dimprod[d]; + } + } + + base +} + +/// Solve one regular-grid cubic B-spline coefficient line. +/// +/// The cubic cardinal B-spline interpolation equations for interior nodes are: +/// +/// ```text +/// (c[i - 1] + 4c[i] + c[i + 1]) / 6 = y[i] +/// ``` +/// +/// At the endpoints, we use one ghost coefficient on each side and impose zero +/// third derivative at the boundary interval: +/// +/// ```text +/// -c[-1] + 3c[0] - 3c[1] + c[2] = 0 +/// c[-1] = 3c[0] - 3c[1] + c[2] +/// +/// -c[n - 3] + 3c[n - 2] - 3c[n - 1] + c[n] = 0 +/// c[n] = c[n - 3] - 3c[n - 2] + 3c[n - 1] +/// ``` +/// +/// Substituting those ghosts into the endpoint interpolation equations gives: +/// +/// ```text +/// 7c[0] - 2c[1] + c[2] = 6y[0] +/// c[n - 3] - 2c[n - 2] + 7c[n - 1] = 6y[n - 1] +/// ``` +/// +/// These are not tridiagonal as written. Combining each with its adjacent +/// interior row gives equivalent tridiagonal boundary rows: +/// +/// ```text +/// c[0] - c[1] = y[0] - y[1] +/// -c[n - 2] + c[n - 1] = y[n - 1] - y[n - 2] +/// ``` +/// +/// Therefore the Thomas solve uses: +/// +/// ```text +/// row 0: diag = 1, upper = -1, rhs = y[0] - y[1] +/// row 1..n-2: lower = 1, diag = 4, upper = 1, rhs = 6y[i] +/// row n-1: lower = -1, diag = 1, rhs = y[n - 1] - y[n - 2] +/// ``` +fn solve_line( + base: usize, + stride: usize, + n: usize, + coeffs: &mut [T], + upper: &mut [T], + rhs: &mut [T], +) -> Result<(), &'static str> { + if n < 4 || upper.len() < n || rhs.len() < n { + return Err("Dimension mismatch"); + } + + let one = T::one(); + let two = one + one; + let four = two + two; + let six = four + two; + + let y0 = coeffs[base]; + let y1 = coeffs[base + stride]; + upper[0] = -one; + rhs[0] = y0 - y1; + + for i in 1..n { + let last = i == n - 1; + let lower = if last { -one } else { one }; + let diag = if last { one } else { four }; + let upper_i = if last { T::zero() } else { one }; + let y = if last { + coeffs[base + i * stride] - coeffs[base + (i - 1) * stride] + } else { + six * coeffs[base + i * stride] + }; + + let denom = diag - lower * upper[i - 1]; + upper[i] = upper_i / denom; + rhs[i] = (y - lower * rhs[i - 1]) / denom; + } + + for i in (0..n - 1).rev() { + rhs[i] = rhs[i] - upper[i] * rhs[i + 1]; + } + + for i in 0..n { + coeffs[base + i * stride] = rhs[i]; + } + + Ok(()) +} + +#[inline] +/// Select the appropriate four local B-spline weights for an interpolation region. +fn interp_weights(t: T, sat: Saturation, linearize_extrapolation: bool) -> [T; 4] { + match sat { + Saturation::None => cubic_bspline_weights(t), + Saturation::InsideLow => low_boundary_weights(t + T::one(), false), + Saturation::OutsideLow => low_boundary_weights(t + T::one(), linearize_extrapolation), + Saturation::InsideHigh => high_boundary_weights(t - T::one(), false), + Saturation::OutsideHigh => high_boundary_weights(t - T::one(), linearize_extrapolation), + } +} + +#[inline] +/// Cubic cardinal B-spline weights for an interior unit-width span. +fn cubic_bspline_weights(t: T) -> [T; 4] { + let one = T::one(); + let two = one + one; + let three = two + one; + let six = three + three; + + let t2 = t * t; + let t3 = t2 * t; + [ + (one - three * t + three * t2 - t3) / six, + ((two + two) - six * t2 + three * t3) / six, + (one + three * t + three * t2 - three * t3) / six, + t3 / six, + ] +} + +#[inline] +/// Low-boundary weights with the ghost coefficient folded into stored coefficients. +fn low_boundary_weights(t: T, linearize_extrapolation: bool) -> [T; 4] { + let raw = if linearize_extrapolation { + low_linearized_boundary_weights(t) + } else { + cubic_bspline_weights(t) + }; + + // The low-side ghost coefficient is 3*c0 - 3*c1 + c2. Fold the + // ghost's contribution into the four stored coefficients. + let three = T::one() + T::one() + T::one(); + [ + mul_add(three, raw[0], raw[1]), + mul_add(-three, raw[0], raw[2]), + raw[0] + raw[3], + T::zero(), + ] +} + +#[inline] +/// High-boundary weights with the ghost coefficient folded into stored coefficients. +fn high_boundary_weights(t: T, linearize_extrapolation: bool) -> [T; 4] { + let raw = if linearize_extrapolation { + high_linearized_boundary_weights(t) + } else { + cubic_bspline_weights(t) + }; + + // The high-side ghost coefficient is c1 - 3*c2 + 3*c3. Fold the + // ghost's contribution into the four stored coefficients. + let three = T::one() + T::one() + T::one(); + [ + T::zero(), + raw[0] + raw[3], + mul_add(-three, raw[3], raw[1]), + mul_add(three, raw[3], raw[2]), + ] +} + +#[inline] +/// Low-side affine continuation of the boundary span's value and first derivative. +fn low_linearized_boundary_weights(t: T) -> [T; 4] { + let one = T::one(); + let two = one + one; + let three = two + one; + let six = three + three; + + [ + one / six - t / two, + (two + two) / six, + one / six + t / two, + T::zero(), + ] +} + +#[inline] +/// High-side affine continuation of the boundary span's value and first derivative. +fn high_linearized_boundary_weights(t: T) -> [T; 4] { + let one = T::one(); + let two = one + one; + let three = two + one; + let six = three + three; + let u = t - one; + + [ + T::zero(), + one / six - u / two, + (two + two) / six, + one / six + u / two, + ] +} + +#[cfg(test)] +mod test { + use super::*; + use crate::utils::{linspace, meshgrid}; + + fn reconstruct_values(dims: [usize; N], coeffs: &[f64]) -> Vec { + let mut out = coeffs.to_vec(); + let mut tmp = vec![0.0; max_dim(dims)]; + let mut dimprod = [1_usize; N]; + populate_dimprod(dims, &mut dimprod); + + for axis in 0..N { + let n = dims[axis]; + let stride = dimprod[axis]; + let nlines = out.len() / n; + + for line in 0..nlines { + let base = line_base_index(dims, dimprod, axis, line); + for i in 0..n { + tmp[i] = out[base + i * stride]; + } + + for i in 0..n { + out[base + i * stride] = if i == 0 { + let ghost = 3.0 * tmp[0] - 3.0 * tmp[1] + tmp[2]; + (ghost + 4.0 * tmp[0] + tmp[1]) / 6.0 + } else if i == n - 1 { + let ghost = tmp[n - 3] - 3.0 * tmp[n - 2] + 3.0 * tmp[n - 1]; + (tmp[n - 2] + 4.0 * tmp[n - 1] + ghost) / 6.0 + } else { + (tmp[i - 1] + 4.0 * tmp[i] + tmp[i + 1]) / 6.0 + }; + } + } + } + + out + } + + fn assert_linear_extrapolation(values: [f64; 3]) { + assert!( + (values[2] - 2.0 * values[1] + values[0]).abs() < 1e-10, + "extrapolated values are not linear: {values:?}" + ); + } + + #[test] + fn test_storage_lengths() { + assert_eq!(MultiBsplineRegular::::coeff_storage_len([4, 5]), 20); + assert_eq!( + MultiBsplineRegular::::construction_scratch_len([4, 5]), + 10 + ); + #[cfg(feature = "par")] + assert_eq!( + MultiBsplineRegular::::parallel_construction_scratch_len([4, 5], 4), + 40 + ); + assert_eq!(MultiBsplineRegular::::coeff_storage_len([3, 5]), 0); + assert_eq!( + MultiBsplineRegular::::construction_scratch_len([3, 5]), + 0 + ); + #[cfg(feature = "par")] + assert_eq!( + MultiBsplineRegular::::parallel_construction_scratch_len([4, 5], 0), + MultiBsplineRegular::::parallel_construction_scratch_len([4, 5], 1) + ); + } + + #[cfg(feature = "par")] + #[test] + fn test_parallel_coefficients_match_serial() { + let dims = [5_usize, 6, 7]; + let nvals = MultiBsplineRegular::::coeff_storage_len(dims); + let serial_scratch_len = MultiBsplineRegular::::construction_scratch_len(dims); + let parallel_scratch_len = + MultiBsplineRegular::::parallel_construction_scratch_len(dims, 4); + let xs: Vec> = (0..3) + .map(|i| linspace(-1.0 + i as f64, 2.0 + i as f64, dims[i])) + .collect(); + let grid = meshgrid((0..3).map(|i| &xs[i]).collect()); + let vals: Vec = grid + .iter() + .map(|x| { + x.iter() + .enumerate() + .map(|(i, v)| (i as f64 + 0.5) * v.sin() + v * v) + .sum() + }) + .collect(); + + let mut serial_coeffs = vec![0.0; nvals]; + let mut serial_scratch = vec![0.0; serial_scratch_len]; + coefficients(dims, &vals, &mut serial_coeffs, &mut serial_scratch).unwrap(); + + let mut parallel_coeffs = vec![0.0; nvals]; + let mut parallel_scratch = vec![0.0; parallel_scratch_len]; + coefficients_par(dims, &vals, &mut parallel_coeffs, &mut parallel_scratch, 4).unwrap(); + + for i in 0..nvals { + assert!( + (serial_coeffs[i] - parallel_coeffs[i]).abs() < 1e-12, + "coefficient mismatch at {i}: {} vs {}", + serial_coeffs[i], + parallel_coeffs[i] + ); + } + } + + #[test] + fn test_coefficients_reconstruct_values_1d_to_3d() { + for ndims in 1..=3 { + crate::dispatch_ndims!(ndims, "bad dims", [1, 2, 3], |N| { + let dims = [6_usize; N]; + let nvals = MultiBsplineRegular::::coeff_storage_len(dims); + let scratch_len = MultiBsplineRegular::::construction_scratch_len(dims); + + let xs: Vec> = (0..N) + .map(|i| linspace(-1.5 * (i as f64 + 1.0), 2.0 * (i as f64 + 1.0), dims[i])) + .collect(); + let grid = meshgrid((0..N).map(|i| &xs[i]).collect()); + let vals: Vec = grid + .iter() + .map(|x| { + x.iter() + .enumerate() + .map(|(i, v)| (i as f64 + 1.0) * v * v + 0.25 * v) + .sum() + }) + .collect(); + + let mut coeffs = vec![0.0; nvals]; + let mut scratch = vec![0.0; scratch_len]; + coefficients(dims, &vals, &mut coeffs, &mut scratch).unwrap(); + let reconstructed = reconstruct_values(dims, &coeffs); + + for i in 0..vals.len() { + assert!( + (vals[i] - reconstructed[i]).abs() < 1e-10, + "{ndims}D mismatch at {i}: {} vs {}", + vals[i], + reconstructed[i] + ); + } + Ok(()) + }) + .unwrap(); + } + } + + #[test] + fn test_interp_reproduces_grid_values_1d_to_3d() { + for ndims in 1..=3 { + crate::dispatch_ndims!(ndims, "bad dims", [1, 2, 3], |N| { + let dims = [6_usize; N]; + let nvals = MultiBsplineRegular::::coeff_storage_len(dims); + let scratch_len = MultiBsplineRegular::::construction_scratch_len(dims); + let starts = [0.0_f64; N]; + let steps = [0.5_f64; N]; + + let xs: Vec> = (0..N) + .map(|i| { + (0..dims[i]) + .map(|j| starts[i] + steps[i] * j as f64) + .collect() + }) + .collect(); + let grid = meshgrid((0..N).map(|i| &xs[i]).collect()); + let vals: Vec = grid + .iter() + .map(|x| x.iter().map(|v| v * v + 0.3 * v).sum()) + .collect(); + let obs: Vec> = (0..N) + .map(|i| grid.iter().map(|x| x[i]).collect()) + .collect(); + let obs_ref: Vec<&[f64]> = obs.iter().map(|x| &x[..]).collect(); + + let mut coeffs = vec![0.0; nvals]; + let mut scratch = vec![0.0; scratch_len]; + let interp = MultiBsplineRegular::from_values_with_workspace( + dims, + starts, + steps, + &vals, + &mut coeffs, + &mut scratch, + false, + ) + .unwrap(); + + let mut out = vec![0.0; vals.len()]; + interp + .interp(obs_ref.as_slice().try_into().unwrap(), &mut out) + .unwrap(); + + for i in 0..vals.len() { + assert!((vals[i] - out[i]).abs() < 1e-10); + } + Ok(()) + }) + .unwrap(); + } + } + + #[test] + fn test_linearized_extrapolation_is_linear() { + let dims = [6_usize]; + let starts = [0.0_f64]; + let steps = [1.0_f64]; + let vals: Vec = (0..dims[0]).map(|i| (i as f64) * (i as f64)).collect(); + let mut coeffs = vec![0.0; MultiBsplineRegular::::coeff_storage_len(dims)]; + let mut scratch = vec![0.0; MultiBsplineRegular::::construction_scratch_len(dims)]; + + let interp = MultiBsplineRegular::from_values_with_workspace( + dims, + starts, + steps, + &vals, + &mut coeffs, + &mut scratch, + true, + ) + .unwrap(); + + let y_hi = interp.interp_one([5.0]).unwrap(); + let y_hi_far = interp.interp_one([6.0]).unwrap(); + let y_hi_farther = interp.interp_one([7.0]).unwrap(); + assert!(((y_hi_farther - y_hi_far) - (y_hi_far - y_hi)).abs() < 1e-12); + } + + #[test] + fn test_linearized_extrapolation_is_linear_outside_grid() { + let dims = [6_usize]; + let starts = [0.0_f64]; + let steps = [1.0_f64]; + let vals: Vec = (0..dims[0]) + .map(|i| { + let x = i as f64; + x * x * x - 0.5 * x * x + 2.0 * x + }) + .collect(); + let mut coeffs = vec![0.0; MultiBsplineRegular::::coeff_storage_len(dims)]; + let mut scratch = vec![0.0; MultiBsplineRegular::::construction_scratch_len(dims)]; + + let interp = MultiBsplineRegular::from_values_with_workspace( + dims, + starts, + steps, + &vals, + &mut coeffs, + &mut scratch, + true, + ) + .unwrap(); + + assert_linear_extrapolation([ + interp.interp_one([0.0]).unwrap(), + interp.interp_one([-1.0]).unwrap(), + interp.interp_one([-2.0]).unwrap(), + ]); + assert_linear_extrapolation([ + interp.interp_one([5.0]).unwrap(), + interp.interp_one([6.0]).unwrap(), + interp.interp_one([7.0]).unwrap(), + ]); + } +} diff --git a/src/multicubic/mod.rs b/src/multicubic/mod.rs index e1bbba5..0773322 100644 --- a/src/multicubic/mod.rs +++ b/src/multicubic/mod.rs @@ -46,6 +46,8 @@ //! but can tolerate some discontinuity in the second derivative use num_traits::Float; +use crate::mul_add; + pub mod rectilinear; pub mod regular; @@ -64,6 +66,7 @@ pub(crate) enum Saturation { /// Evaluate a hermite spline function on an interval from x0 to x1, /// with imposed slopes k0 and k1 at the endpoints, and normalized /// coordinate t = (x - x0) / (x1 - x0). +#[allow(dead_code)] #[inline] pub(crate) fn normalized_hermite_spline(t: T, y0: T, dy: T, k0: T, k1: T) -> T { // `a` and `b` are the difference between this function and a linear one going @@ -76,38 +79,5 @@ pub(crate) fn normalized_hermite_spline(t: T, y0: T, dy: T, k0: T, k1: let c3 = a - b; // Horner's method - #[cfg(not(feature = "fma"))] - { - y0 + t * (c1 + t * (c2 + t * c3)) - } - #[cfg(feature = "fma")] - { - c3.mul_add(t, c2).mul_add(t, c1).mul_add(t, y0) - } -} - -/// Second-order central difference on non-uniform grid per -/// -/// A. E. P. Veldman and K. Rinzema, “Playing with nonuniform grids”. -/// https://pure.rug.nl/ws/portalfiles/portal/3332271/1992JEngMathVeldman.pdf -/// -/// Method B, -/// which is essentially a distance-weighted average of the forward and backward -/// differences s.t. the closer points have more influence on the estimate -/// of the derivative. -#[inline] -pub(crate) fn centered_difference_nonuniform(y0: T, y1: T, y2: T, h01: T, h12: T) -> T { - let a = h01 / (h01 + h12); - let b = (y2 - y1) / h12; - let c = h12 / (h12 + h01); - let d = (y1 - y0) / h01; - - #[cfg(not(feature = "fma"))] - { - a * b + c * d - } - #[cfg(feature = "fma")] - { - a.mul_add(b, c * d) - } + mul_add(mul_add(mul_add(c3, t, c2), t, c1), t, y0) } diff --git a/src/multicubic/rectilinear.rs b/src/multicubic/rectilinear.rs index cb963a6..613bdf8 100644 --- a/src/multicubic/rectilinear.rs +++ b/src/multicubic/rectilinear.rs @@ -29,8 +29,12 @@ //! References //! * A. E. P. Veldman and K. Rinzema, “Playing with nonuniform grids”. //! https://pure.rug.nl/ws/portalfiles/portal/3332271/1992JEngMathVeldman.pdf -use super::{Saturation, centered_difference_nonuniform, normalized_hermite_spline}; -use crate::index_arr_fixed_dims; +use super::Saturation; +use crate::{ + index_arr_fixed_dims, + interp_math::{dot4, hermite_basis}, + mul_add, +}; use crunchy::unroll; use num_traits::Float; @@ -231,6 +235,7 @@ impl<'a, T: Float, const N: usize> MulticubicRectilinear<'a, T, N> { // and does not increase peak stack usage. let mut origin = [0_usize; N]; // Indices of lower corner of hypercub let mut sat = [Saturation::None; N]; // Saturation none/high/low flags for each dim + let mut weights = [[T::zero(); FP]; N]; let mut dimprod = [1_usize; N]; let mut loc = [0_usize; N]; let mut store = [[T::zero(); FP]; N]; @@ -249,6 +254,13 @@ impl<'a, T: Float, const N: usize> MulticubicRectilinear<'a, T, N> { // Populate lower corner and saturation flag for each dimension (origin[i], sat[i]) = self.get_loc(x[i], i)?; + let grid_cell = &self.grids[i][origin[i]..origin[i] + 4]; + weights[i] = interp_weights( + grid_cell.try_into().unwrap(), + x[i], + sat[i], + self.linearize_extrapolation, + ); } // Recursive interpolation of one dependency tree at a time @@ -282,16 +294,7 @@ impl<'a, T: Float, const N: usize> MulticubicRectilinear<'a, T, N> { if level { // const branch - let grid_cell = &self.grids[ind][origin[ind]..origin[ind] + 4]; - let interped = interp_inner::( - store[ind], - grid_cell.try_into().unwrap(), - x[ind], - sat[ind], - self.linearize_extrapolation, - ); - - store[j][p] = interped; + store[j][p] = dot4(weights[ind], store[ind]); } } } @@ -325,15 +328,7 @@ impl<'a, T: Float, const N: usize> MulticubicRectilinear<'a, T, N> { } // Interpolate the final value - let grid_cell = &self.grids[N - 1][origin[N - 1]..origin[N - 1] + 4]; - let interped = interp_inner::( - store[N - 1], - grid_cell.try_into().unwrap(), - x[N - 1], - sat[N - 1], - self.linearize_extrapolation, - ); - Ok(interped) + Ok(dot4(weights[N - 1], store[N - 1])) } /// Get the two-lower index along this dimension where `x` is found, @@ -389,30 +384,29 @@ impl<'a, T: Float, const N: usize> MulticubicRectilinear<'a, T, N> { } } -/// Calculate slopes and offsets & select evaluation method +/// Calculate one-dimensional interpolation weights for a fixed grid cell. +/// +/// For cases on the interior, use two slopes from a nonuniform-grid centered +/// difference and two values as the Hermite boundary conditions. +/// +/// For locations near an edge, take one centered difference for the inside +/// derivative, then impose a natural spline boundary condition on the +/// derivative at the edge, meaning the third derivative q'''(t) = 0 at the +/// last grid point. This produces a quadratic in the last cell, reducing wobble +/// that would be caused by enforcing the use of a cubic function where there is +/// not enough information to support it. +/// +/// The returned weights multiply the four local values directly. This keeps the +/// same interpolant as the direct Hermite evaluation, but lets the N-dimensional +/// reduction reuse the weights for every child group on the same axis. #[inline] -fn interp_inner( - vals: [T; 4], +fn interp_weights( grid_cell: &[T; 4], x: T, sat: Saturation, linearize_extrapolation: bool, -) -> T { - // Construct some constants using generic methods +) -> [T; 4] { let one = T::one(); - let two = one + one; - - // For cases on the interior, use two slopes (from centered difference) and two values - // as the BCs. - // - // For locations falling near and edge, take one centered - // difference for the inside derivative, - // then for the derivative at the edge, impose a natural - // spline constraint, meaning the third derivative q'''(t) = 0 - // at the last grid point, which produces a quadratic in the - // last cell, reducing wobble that would be cause by enforcing - // the use of a cubic function where there is not enough information - // to support it. match sat { Saturation::None => { @@ -420,117 +414,165 @@ fn interp_inner( // --|---|---|---|-- // x // - // This is the nominal case - let y0 = vals[1]; - let dy = vals[2] - vals[1]; - + // This is the nominal case. let h01 = grid_cell[1] - grid_cell[0]; let h12 = grid_cell[2] - grid_cell[1]; let h23 = grid_cell[3] - grid_cell[2]; - let k0 = centered_difference_nonuniform(vals[0], vals[1], vals[2], h01 / h12, T::one()); - let k1 = centered_difference_nonuniform(vals[1], vals[2], vals[3], T::one(), h23 / h12); - let t = (x - grid_cell[1]) / h12; - - normalized_hermite_spline(t, y0, dy, k0, k1) + let [h00, h10, h01_basis, h11] = hermite_basis(t); + let k0 = centered_difference_weights(h01 / h12, one); + let k1 = centered_difference_weights(one, h23 / h12); + + [ + h10 * k0[0], + h00 + h10 * k0[1] + h11 * k1[0], + h01_basis + h10 * k0[2] + h11 * k1[1], + h11 * k1[2], + ] } Saturation::InsideLow => { // t <-| // --|---|---|---|-- // x // - // Flip direction to maintain symmetry - // with the InsideHigh case. - - let y0 = vals[1]; // Same starting point, opposite direction - let dy = vals[0] - vals[1]; - + // Flip direction to maintain symmetry with the InsideHigh case. let h01 = grid_cell[1] - grid_cell[0]; let h12 = grid_cell[2] - grid_cell[1]; - let k0 = - -centered_difference_nonuniform(vals[0], vals[1], vals[2], T::one(), h12 / h01); - let k1 = two * dy - k0; // Natural spline boundary condition - let t = -(x - grid_cell[1]) / h01; - normalized_hermite_spline(t, y0, dy, k0, k1) + low_weights(t, h12 / h01, false) } Saturation::OutsideLow => { // t <-| // --|---|---|---|-- // x // - // Flip direction to maintain symmetry - // with the InsideHigh case. - - let y0 = vals[1]; - let y1 = vals[0]; - let dy = vals[0] - vals[1]; - + // Flip direction to maintain symmetry with the OutsideHigh case. let h01 = grid_cell[1] - grid_cell[0]; let h12 = grid_cell[2] - grid_cell[1]; - let k0 = - -centered_difference_nonuniform(vals[0], vals[1], vals[2], T::one(), h12 / h01); - let k1 = two * dy - k0; // Natural spline boundary condition - let t = -(x - grid_cell[1]) / h01; - // If we are linearizing the interpolant under extrapolation, - // hold the last slope outside the grid - if linearize_extrapolation { - y1 + k1 * (t - one) - } else { - normalized_hermite_spline(t, y0, dy, k0, k1) - } + low_weights(t, h12 / h01, linearize_extrapolation) } Saturation::InsideHigh => { // |-> t // --|---|---|---|-- // x - let y0 = vals[2]; - let dy = vals[3] - vals[2]; - let h12 = grid_cell[2] - grid_cell[1]; let h23 = grid_cell[3] - grid_cell[2]; - let k0 = centered_difference_nonuniform(vals[1], vals[2], vals[3], h12 / h23, T::one()); - let k1 = two * dy - k0; // Natural spline boundary condition - let t = (x - grid_cell[2]) / h23; - normalized_hermite_spline(t, y0, dy, k0, k1) + high_weights(t, h12 / h23, false) } Saturation::OutsideHigh => { // |-> t // --|---|---|---|-- // x - let y0 = vals[2]; - let y1 = vals[3]; - let dy = vals[3] - vals[2]; - let h12 = grid_cell[2] - grid_cell[1]; let h23 = grid_cell[3] - grid_cell[2]; - let k0 = centered_difference_nonuniform(vals[1], vals[2], vals[3], h12 / h23, T::one()); - let k1 = two * dy - k0; // Natural spline boundary condition - let t = (x - grid_cell[2]) / h23; - // If we are linearizing the interpolant under extrapolation, - // hold the last slope outside the grid - if linearize_extrapolation { - y1 + k1 * (t - one) - } else { - normalized_hermite_spline(t, y0, dy, k0, k1) - } + high_weights(t, h12 / h23, linearize_extrapolation) } } } +#[inline] +fn low_weights(t: T, h12_over_h01: T, linearize_extrapolation: bool) -> [T; 4] { + let one = T::one(); + let two = one + one; + let k0 = centered_difference_weights(one, h12_over_h01); + + // If we are linearizing the interpolant under extrapolation, hold the last + // slope outside the grid. Otherwise, continue the natural-boundary spline. + if linearize_extrapolation { + let s = t - one; + [ + one + s * (two + k0[0]), + s * (-two + k0[1]), + s * k0[2], + T::zero(), + ] + } else { + let [h00, h10, h01, h11] = hermite_basis(t); + let slope_factor = h11 - h10; + [ + h01 + two * h11 + slope_factor * k0[0], + h00 - two * h11 + slope_factor * k0[1], + slope_factor * k0[2], + T::zero(), + ] + } +} + +#[inline] +fn high_weights(t: T, h12_over_h23: T, linearize_extrapolation: bool) -> [T; 4] { + let one = T::one(); + let two = one + one; + let k0 = centered_difference_weights(h12_over_h23, one); + + // If we are linearizing the interpolant under extrapolation, hold the last + // slope outside the grid. Otherwise, continue the natural-boundary spline. + if linearize_extrapolation { + let s = t - one; + [ + T::zero(), + -s * k0[0], + s * (-two - k0[1]), + one + s * (two - k0[2]), + ] + } else { + let [h00, h10, h01, h11] = hermite_basis(t); + let slope_factor = h10 - h11; + [ + T::zero(), + slope_factor * k0[0], + h00 - two * h11 + slope_factor * k0[1], + h01 + two * h11 + slope_factor * k0[2], + ] + } +} + +/// Second-order central difference weights on a nonuniform grid per +/// +/// A. E. P. Veldman and K. Rinzema, "Playing with nonuniform grids". +/// https://pure.rug.nl/ws/portalfiles/portal/3332271/1992JEngMathVeldman.pdf +/// +/// Method B, which is essentially a distance-weighted average of the forward +/// and backward differences s.t. the closer points have more influence on the +/// derivative estimate. +/// +/// The returned weights multiply `[y0, y1, y2]` and produce the same result as: +/// +/// ```text +/// a = h01 / (h01 + h12) +/// b = (y2 - y1) / h12 +/// c = h12 / (h12 + h01) +/// d = (y1 - y0) / h01 +/// derivative = a * b + c * d +/// ``` +#[inline] +fn centered_difference_weights(h01: T, h12: T) -> [T; 3] { + let denom = h01 + h12; + let a = h01 / denom; + let c = h12 / denom; + + [-c / h01, mul_add(c, T::one() / h01, -a / h12), a / h12] +} + #[cfg(test)] mod test { - use super::interpn; + use super::{MulticubicRectilinear, interpn}; use crate::testing::*; use crate::utils::*; + fn assert_linear_extrapolation(values: [f64; 3]) { + assert!( + (values[2] - 2.0 * values[1] + values[0]).abs() < 1e-12, + "extrapolated values are not linear: {values:?}" + ); + } + /// Iterate from 1 to 8 dimensions, making a minimum-sized grid for each one /// to traverse every combination of interpolating or extrapolating high or low on each dimension. /// Each test evaluates at 5^ndims locations, largely extrapolated in corner regions, so it @@ -584,6 +626,28 @@ mod test { } } + #[test] + fn test_linearized_extrapolation_is_linear_outside_grid() { + let x = [-1.0_f64, -0.2, 0.35, 1.4, 2.8, 4.0]; + let grids = [&x[..]]; + let vals: Vec = x + .iter() + .map(|&x| x * x * x - 0.5 * x * x + 2.0 * x) + .collect(); + let interp = MulticubicRectilinear::new(&grids, &vals, true).unwrap(); + + assert_linear_extrapolation([ + interp.interp_one([-1.0]).unwrap(), + interp.interp_one([-1.6]).unwrap(), + interp.interp_one([-2.2]).unwrap(), + ]); + assert_linear_extrapolation([ + interp.interp_one([4.0]).unwrap(), + interp.interp_one([4.7]).unwrap(), + interp.interp_one([5.4]).unwrap(), + ]); + } + /// Under both interpolation and extrapolation, a hermite spline with natural boundary condition /// can reproduce an N-dimensional quadratic function exactly #[test] diff --git a/src/multicubic/regular.rs b/src/multicubic/regular.rs index 32a1d31..56d13a2 100644 --- a/src/multicubic/regular.rs +++ b/src/multicubic/regular.rs @@ -30,8 +30,11 @@ //! let linearize_extrapolation = false; //! regular::interpn_alloc(&dims, &starts, &steps, &z, linearize_extrapolation, &obs).unwrap(); //! ``` -use super::{Saturation, normalized_hermite_spline}; -use crate::index_arr_fixed_dims; +use super::Saturation; +use crate::{ + index_arr_fixed_dims, + interp_math::{dot4, hermite_basis}, +}; use crunchy::unroll; use num_traits::{Float, NumCast}; @@ -264,7 +267,7 @@ impl<'a, T: Float, const N: usize> MulticubicRegular<'a, T, N> { // and does not increase peak stack usage. let mut origin = [0_usize; N]; // Indices of lower corner of hypercube let mut sat = [Saturation::None; N]; // Saturation none/high/low flags for each dim - let mut dts = [T::zero(); N]; // Normalized coordinate storage + let mut weights = [[T::zero(); FP]; N]; let mut dimprod = [1_usize; N]; let mut loc = [0_usize; N]; let mut store = [[T::zero(); FP]; N]; @@ -291,7 +294,8 @@ impl<'a, T: Float, const N: usize> MulticubicRegular<'a, T, N> { + self.steps[i] * ::from(origin[i] + 1) .ok_or("Unrepresentable coordinate value")?; - dts[i] = (x[i] - index_one_loc) / self.steps[i]; + let t = (x[i] - index_one_loc) / self.steps[i]; + weights[i] = interp_weights(t, sat[i], self.linearize_extrapolation); } // Recursive interpolation of one dependency tree at a time @@ -325,14 +329,7 @@ impl<'a, T: Float, const N: usize> MulticubicRegular<'a, T, N> { if level { // const branch - let interped = interp_inner::( - &store[ind], - dts[ind], - sat[ind], - self.linearize_extrapolation, - ); - - store[j][p] = interped; + store[j][p] = dot4(weights[ind], store[ind]); } } } @@ -366,13 +363,7 @@ impl<'a, T: Float, const N: usize> MulticubicRegular<'a, T, N> { } // Interpolate the final value - let interped = interp_inner::( - &store[N - 1], - dts[N - 1], - sat[N - 1], - self.linearize_extrapolation, - ); - Ok(interped) + Ok(dot4(weights[N - 1], store[N - 1])) } /// Get the two-lower index along this dimension where `x` is found, @@ -423,30 +414,23 @@ impl<'a, T: Float, const N: usize> MulticubicRegular<'a, T, N> { } } -/// Calculate slopes and offsets & select evaluation method +/// Calculate one-dimensional interpolation weights for a fixed regular-grid cell. +/// +/// For cases on the interior, use two slopes from centered difference and two +/// values as the Hermite boundary conditions. +/// +/// For locations falling near an edge, take one centered difference for the +/// inside derivative, then for the derivative at the edge, impose a natural +/// spline constraint, meaning the third derivative q'''(t) = 0 at the last grid +/// point. This produces a quadratic in the last cell, reducing wobble that +/// would be caused by enforcing the use of a cubic function where there is not +/// enough information to support it. +/// +/// The returned weights multiply the four local values directly. This keeps the +/// same interpolant as the direct Hermite evaluation, but lets the N-dimensional +/// reduction reuse the weights for every child group on the same axis. #[inline] -fn interp_inner( - vals: &[T; 4], - t: T, - sat: Saturation, - linearize_extrapolation: bool, -) -> T { - // Construct some constants using generic methods - let one = T::one(); - let two = one + one; - - // For cases on the interior, use two slopes (from centered difference) and two values - // as the BCs. - // - // For locations falling near and edge, take one centered - // difference for the inside derivative, - // then for the derivative at the edge, impose a natural - // spline constraint, meaning the third derivative q'''(t) = 0 - // at the last grid point, which produces a quadratic in the - // last cell, reducing wobble that would be cause by enforcing - // the use of a cubic function where there is not enough information - // to support it. - +fn interp_weights(t: T, sat: Saturation, linearize_extrapolation: bool) -> [T; 4] { match sat { Saturation::None => { // |-> t @@ -454,14 +438,9 @@ fn interp_inner( // x // // This is the nominal case - let y0 = vals[1]; - let dy = vals[2] - vals[1]; - - // Take slopes from centered difference - let k0 = (vals[2] - vals[0]) / two; - let k1 = (vals[3] - vals[1]) / two; - - normalized_hermite_spline(t, y0, dy, k0, k1) + let [h00, h10, h01, h11] = hermite_basis(t); + let two = T::one() + T::one(); + [-h10 / two, h00 - h11 / two, h01 + h10 / two, h11 / two] } Saturation::InsideLow => { // t <-| @@ -470,18 +449,8 @@ fn interp_inner( // // Flip direction to maintain symmetry // with the InsideHigh case - let t = -t; // `t` always w.r.t. index 1 of cube - let y0 = vals[1]; // Same starting point, opposite direction - let dy = vals[0] - vals[1]; - - let k0 = -(vals[2] - vals[0]) / two; - - #[cfg(not(feature = "fma"))] - let k1 = two * dy - k0; // Natural spline boundary condition - #[cfg(feature = "fma")] - let k1 = two.mul_add(dy, -k0); // Natural spline boundary condition - - normalized_hermite_spline(t, y0, dy, k0, k1) + let t = -t; // `t` is initially w.r.t. index 1 of cube + low_weights(t, false) } Saturation::OutsideLow => { // t <-| @@ -490,32 +459,8 @@ fn interp_inner( // // Flip direction to maintain symmetry // with the InsideHigh case - let t = -t; // `t` always w.r.t. index 1 of cube - let y0 = vals[1]; // Same starting point, opposite direction - let y1 = vals[0]; - let dy = vals[0] - vals[1]; - - let k0 = -(vals[2] - vals[0]) / two; - - #[cfg(not(feature = "fma"))] - let k1 = two * dy - k0; // Natural spline boundary condition - #[cfg(feature = "fma")] - let k1 = two.mul_add(dy, -k0); // Natural spline boundary condition - - // If we are linearizing the interpolant under extrapolation, - // hold the last slope outside the grid - if linearize_extrapolation { - #[cfg(not(feature = "fma"))] - { - y1 + k1 * (t - one) - } - #[cfg(feature = "fma")] - { - k1.mul_add(t - one, y1) - } - } else { - normalized_hermite_spline(t, y0, dy, k0, k1) - } + let t = -t; // `t` is initially w.r.t. index 1 of cube + low_weights(t, linearize_extrapolation) } Saturation::InsideHigh => { // |-> t @@ -525,18 +470,8 @@ fn interp_inner( // Shift cell up an index // and offset `t`, which has value between 1 and 2 // because it is calculated w.r.t. index 1 - let t = t - one; - let y0 = vals[2]; - let dy = vals[3] - vals[2]; - - let k0 = (vals[3] - vals[1]) / two; - - #[cfg(not(feature = "fma"))] - let k1 = two * dy - k0; // Natural spline boundary condition - #[cfg(feature = "fma")] - let k1 = two.mul_add(dy, -k0); // Natural spline boundary condition - - normalized_hermite_spline(t, y0, dy, k0, k1) + let t = t - T::one(); + high_weights(t, false) } Saturation::OutsideHigh => { // |-> t @@ -546,41 +481,66 @@ fn interp_inner( // Shift cell up an index // and offset `t`, which has value between 1 and 2 // because it is calculated w.r.t. index 1 - let t = t - one; - let y0 = vals[2]; - let y1 = vals[3]; - let dy = vals[3] - vals[2]; - - let k0 = (vals[3] - vals[1]) / two; - - #[cfg(not(feature = "fma"))] - let k1 = two * dy - k0; // Natural spline boundary condition - #[cfg(feature = "fma")] - let k1 = two.mul_add(dy, -k0); // Natural spline boundary condition - - // If we are linearizing the interpolant under extrapolation, - // hold the last slope outside the grid - if linearize_extrapolation { - #[cfg(not(feature = "fma"))] - { - y1 + k1 * (t - one) - } - #[cfg(feature = "fma")] - { - k1.mul_add(t - one, y1) - } - } else { - normalized_hermite_spline(t, y0, dy, k0, k1) - } + let t = t - T::one(); + high_weights(t, linearize_extrapolation) } } } +#[inline] +fn low_weights(t: T, linearize_extrapolation: bool) -> [T; 4] { + let one = T::one(); + let two = one + one; + + // If we are linearizing the interpolant under extrapolation, hold the last + // slope outside the grid. Otherwise, continue the natural-boundary spline. + if linearize_extrapolation { + let s = t - one; + [one + s * (one + one / two), -two * s, s / two, T::zero()] + } else { + let [h00, h10, h01, h11] = hermite_basis(t); + [ + h01 + h10 / two + (one + one / two) * h11, + h00 - two * h11, + (h11 - h10) / two, + T::zero(), + ] + } +} + +#[inline] +fn high_weights(t: T, linearize_extrapolation: bool) -> [T; 4] { + let one = T::one(); + let two = one + one; + + // If we are linearizing the interpolant under extrapolation, hold the last + // slope outside the grid. Otherwise, continue the natural-boundary spline. + if linearize_extrapolation { + let s = t - one; + [T::zero(), s / two, -two * s, one + s * (one + one / two)] + } else { + let [h00, h10, h01, h11] = hermite_basis(t); + [ + T::zero(), + (h11 - h10) / two, + h00 - two * h11, + h01 + h10 / two + (one + one / two) * h11, + ] + } +} + #[cfg(test)] mod test { - use super::interpn; + use super::{MulticubicRegular, interpn}; use crate::utils::*; + fn assert_linear_extrapolation(values: [f64; 3]) { + assert!( + (values[2] - 2.0 * values[1] + values[0]).abs() < 1e-12, + "extrapolated values are not linear: {values:?}" + ); + } + /// Iterate from 1 to 6 dimensions, making a minimum-sized grid for each one /// to traverse every combination of interpolating or extrapolating high or low on each dimension. /// Each test evaluates at 5^ndims locations, largely extrapolated in corner regions, so it @@ -629,6 +589,31 @@ mod test { } } + #[test] + fn test_linearized_extrapolation_is_linear_outside_grid() { + let dims = [6_usize]; + let starts = [0.0_f64]; + let steps = [1.0_f64]; + let vals: Vec = (0..dims[0]) + .map(|i| { + let x = i as f64; + x * x * x - 0.5 * x * x + 2.0 * x + }) + .collect(); + let interp = MulticubicRegular::new(dims, starts, steps, &vals, true).unwrap(); + + assert_linear_extrapolation([ + interp.interp_one([0.0]).unwrap(), + interp.interp_one([-1.0]).unwrap(), + interp.interp_one([-2.0]).unwrap(), + ]); + assert_linear_extrapolation([ + interp.interp_one([5.0]).unwrap(), + interp.interp_one([6.0]).unwrap(), + interp.interp_one([7.0]).unwrap(), + ]); + } + /// Under both interpolation and extrapolation, a hermite spline with natural boundary condition /// can reproduce an N-dimensional quadratic function exactly #[test] diff --git a/src/multilinear/rectilinear.rs b/src/multilinear/rectilinear.rs index 0641c96..902caca 100644 --- a/src/multilinear/rectilinear.rs +++ b/src/multilinear/rectilinear.rs @@ -27,7 +27,7 @@ //! //! References //! * https://en.wikipedia.org/wiki/Bilinear_interpolation#Weighted_mean -use crate::index_arr_fixed_dims; +use crate::{index_arr_fixed_dims, mul_add}; use crunchy::unroll; use num_traits::Float; @@ -269,10 +269,7 @@ impl<'a, T: Float, const N: usize> MultilinearRectilinear<'a, T, N> { let y0 = store[ind][0]; let dy = store[ind][1] - y0; - #[cfg(not(feature = "fma"))] - let interped = y0 + t * dy; - #[cfg(feature = "fma")] - let interped = t.mul_add(dy, y0); + let interped = mul_add(t, dy, y0); store[j][p] = interped; } @@ -306,10 +303,7 @@ impl<'a, T: Float, const N: usize> MultilinearRectilinear<'a, T, N> { let y0 = store[ind][0]; let dy = store[ind][1] - y0; - #[cfg(not(feature = "fma"))] - let interped = y0 + t * dy; - #[cfg(feature = "fma")] - let interped = t.mul_add(dy, y0); + let interped = mul_add(t, dy, y0); Ok(interped) } diff --git a/src/multilinear/regular.rs b/src/multilinear/regular.rs index 3695ebb..7d7ef1b 100644 --- a/src/multilinear/regular.rs +++ b/src/multilinear/regular.rs @@ -29,7 +29,7 @@ //! //! References //! * https://en.wikipedia.org/wiki/Bilinear_interpolation#Repeated_linear_interpolation -use crate::index_arr_fixed_dims; +use crate::{index_arr_fixed_dims, mul_add}; use crunchy::unroll; use num_traits::{Float, NumCast}; @@ -268,10 +268,7 @@ impl<'a, T: Float, const N: usize> MultilinearRegular<'a, T, N> { ::from(origin[i]).ok_or("Unrepresentable coordinate value")?; // Calculate normalized delta locations - #[cfg(not(feature = "fma"))] - let index_zero_loc = self.starts[i] + self.steps[i] * origin_f; - #[cfg(feature = "fma")] - let index_zero_loc = self.steps[i].mul_add(origin_f, self.starts[i]); + let index_zero_loc = mul_add(self.steps[i], origin_f, self.starts[i]); dts[i] = (x[i] - index_zero_loc) / self.steps[i]; } @@ -312,10 +309,7 @@ impl<'a, T: Float, const N: usize> MultilinearRegular<'a, T, N> { let dy = store[ind][1] - y0; let t = dts[ind]; - #[cfg(not(feature = "fma"))] - let interped = y0 + t * dy; - #[cfg(feature = "fma")] - let interped = t.mul_add(dy, y0); + let interped = mul_add(t, dy, y0); store[j][p] = interped; } @@ -343,10 +337,7 @@ impl<'a, T: Float, const N: usize> MultilinearRegular<'a, T, N> { let y0 = store[N - 1][0]; let dy = store[N - 1][1] - y0; let t = dts[N - 1]; - #[cfg(not(feature = "fma"))] - let interped = y0 + t * dy; - #[cfg(feature = "fma")] - let interped = t.mul_add(dy, y0); + let interped = mul_add(t, dy, y0); Ok(interped) } diff --git a/src/nearest/regular.rs b/src/nearest/regular.rs index 557dad1..6e07e6a 100644 --- a/src/nearest/regular.rs +++ b/src/nearest/regular.rs @@ -26,7 +26,7 @@ //! // Do interpolation, allocating for the output for convenience //! regular::interpn_alloc(&dims, &starts, &steps, &z, &obs).unwrap(); //! ``` -use crate::index_arr_fixed_dims; +use crate::{index_arr_fixed_dims, mul_add}; use num_traits::{Float, NumCast}; /// Evaluate nearest-neighbor interpolation on a regular grid in up to 8 dimensions. @@ -220,10 +220,7 @@ impl<'a, T: Float, const N: usize> NearestRegular<'a, T, N> { ::from(origin).ok_or("Unrepresentable coordinate value")?; // Calculate normalized delta locations - #[cfg(not(feature = "fma"))] - let index_zero_loc = self.starts[i] + self.steps[i] * origin_f; - #[cfg(feature = "fma")] - let index_zero_loc = self.steps[i].mul_add(origin_f, self.starts[i]); + let index_zero_loc = mul_add(self.steps[i], origin_f, self.starts[i]); let dt = (x[i] - index_zero_loc) / self.steps[i]; diff --git a/src/one_dim/linear.rs b/src/one_dim/linear.rs index 92a3637..a74d054 100644 --- a/src/one_dim/linear.rs +++ b/src/one_dim/linear.rs @@ -3,6 +3,8 @@ use num_traits::Float; +use crate::mul_add; + use super::{Extrap, Grid1D, GridSample, Interp1D}; /// Simple linear interpolation / extrapolation. @@ -28,10 +30,7 @@ where let slope = (y1 - y0) / (x1 - x0); let dx = loc - x0; - #[cfg(not(feature = "fma"))] - let v = y0 + slope * dx; - #[cfg(feature = "fma")] - let v = slope.mul_add(dx, y0); + let v = mul_add(slope, dx, y0); Ok(v) } @@ -70,10 +69,7 @@ where let slope = (y1 - y0) / (x1 - x0); let dx = loc - x0; - #[cfg(not(feature = "fma"))] - let v = y0 + slope * dx; - #[cfg(feature = "fma")] - let v = slope.mul_add(dx, y0); + let v = mul_add(slope, dx, y0); v } diff --git a/src/python.rs b/src/python.rs index 2a3d3c9..19b51fd 100644 --- a/src/python.rs +++ b/src/python.rs @@ -2,6 +2,7 @@ use numpy::borrow::{PyReadonlyArray1, PyReadwriteArray1}; use pyo3::exceptions; use pyo3::prelude::*; +use crate::multibspline; use crate::multicubic; use crate::multilinear; use crate::nearest; @@ -36,6 +37,16 @@ fn interpn<'py>(_py: Python, m: &Bound<'py, PyModule>) -> PyResult<()> { // Multicubic with rectilinear grid m.add_function(wrap_pyfunction!(interpn_cubic_rectilinear_f64, m)?)?; m.add_function(wrap_pyfunction!(interpn_cubic_rectilinear_f32, m)?)?; + // MultiBspline with regular grid + m.add_function(wrap_pyfunction!(coefficients_bspline_regular_f64, m)?)?; + m.add_function(wrap_pyfunction!(coefficients_bspline_regular_f32, m)?)?; + m.add_function(wrap_pyfunction!(_eval_bspline_regular_f64, m)?)?; + m.add_function(wrap_pyfunction!(_eval_bspline_regular_f32, m)?)?; + // MultiBspline with rectilinear grid + m.add_function(wrap_pyfunction!(coefficients_bspline_rectilinear_f64, m)?)?; + m.add_function(wrap_pyfunction!(coefficients_bspline_rectilinear_f32, m)?)?; + m.add_function(wrap_pyfunction!(_eval_bspline_rectilinear_f64, m)?)?; + m.add_function(wrap_pyfunction!(_eval_bspline_rectilinear_f32, m)?)?; // Top-level interpn dispatch m.add_function(wrap_pyfunction!(interpn_f64, m)?)?; m.add_function(wrap_pyfunction!(interpn_f32, m)?)?; @@ -295,6 +306,171 @@ macro_rules! interpn_cubic_rectilinear_impl { interpn_cubic_rectilinear_impl!(interpn_cubic_rectilinear_f64, f64); interpn_cubic_rectilinear_impl!(interpn_cubic_rectilinear_f32, f32); +macro_rules! coefficients_bspline_regular_impl { + ($funcname:ident, $T:ty) => { + #[pyfunction] + fn $funcname( + dims: Vec, + vals: PyReadonlyArray1<$T>, + mut coeffs: PyReadwriteArray1<$T>, + mut scratch: PyReadwriteArray1<$T>, + ) -> PyResult<()> { + let ndims = dims.len(); + + match crate::dispatch_ndims!( + ndims, + "Dimension exceeds maximum (8). Use interpolator struct directly for higher dimensions.", + [1, 2, 3, 4, 5, 6, 7, 8], + |N| { + multibspline::regular::coefficients::<$T, N>( + dims.try_into().unwrap(), + vals.as_slice()?, + coeffs.as_slice_mut()?, + scratch.as_slice_mut()?, + ) + } + ) { + Ok(()) => Ok(()), + Err(msg) => Err(exceptions::PyAssertionError::new_err(msg)), + } + } + }; +} + +coefficients_bspline_regular_impl!(coefficients_bspline_regular_f64, f64); +coefficients_bspline_regular_impl!(coefficients_bspline_regular_f32, f32); + +macro_rules! eval_bspline_regular_impl { + ($funcname:ident, $T:ty) => { + #[pyfunction] + fn $funcname( + dims: Vec, + starts: PyReadonlyArray1<$T>, + steps: PyReadonlyArray1<$T>, + coeffs: PyReadonlyArray1<$T>, + linearize_extrapolation: bool, + obs: Vec>, + mut out: PyReadwriteArray1<$T>, + ) -> PyResult<()> { + unpack_vec_of_arr!(obs, obs, $T); + + let ndims = dims.len(); + let starts = starts.as_slice()?; + let steps = steps.as_slice()?; + let coeffs = coeffs.as_slice()?; + let out = out.as_slice_mut()?; + if starts.len() != ndims || steps.len() != ndims || obs.len() != ndims { + return Err(exceptions::PyAssertionError::new_err("Dimension mismatch")); + } + + match crate::dispatch_ndims!( + ndims, + "Dimension exceeds maximum (8). Use interpolator struct directly for higher dimensions.", + [1, 2, 3, 4, 5, 6, 7, 8], + |N| { + match multibspline::MultiBsplineRegular::<$T, N>::new( + dims.try_into().unwrap(), + starts.try_into().unwrap(), + steps.try_into().unwrap(), + coeffs, + linearize_extrapolation, + ) { + Ok(interpolator) => interpolator.interp(obs.try_into().unwrap(), out), + Err(msg) => Err(msg), + } + } + ) { + Ok(()) => Ok(()), + Err(msg) => Err(exceptions::PyAssertionError::new_err(msg)), + } + } + }; +} + +eval_bspline_regular_impl!(_eval_bspline_regular_f64, f64); +eval_bspline_regular_impl!(_eval_bspline_regular_f32, f32); + +macro_rules! coefficients_bspline_rectilinear_impl { + ($funcname:ident, $T:ty) => { + #[pyfunction] + fn $funcname( + grids: Vec>, + vals: PyReadonlyArray1<$T>, + mut coeffs: PyReadwriteArray1<$T>, + mut scratch: PyReadwriteArray1<$T>, + ) -> PyResult<()> { + unpack_vec_of_arr!(grids, grids, $T); + let ndims = grids.len(); + + match crate::dispatch_ndims!( + ndims, + "Dimension exceeds maximum (8). Use interpolator struct directly for higher dimensions.", + [1, 2, 3, 4, 5, 6, 7, 8], + |N| { + multibspline::rectilinear::coefficients::<$T, N>( + grids.try_into().unwrap(), + vals.as_slice()?, + coeffs.as_slice_mut()?, + scratch.as_slice_mut()?, + ) + } + ) { + Ok(()) => Ok(()), + Err(msg) => Err(exceptions::PyAssertionError::new_err(msg)), + } + } + }; +} + +coefficients_bspline_rectilinear_impl!(coefficients_bspline_rectilinear_f64, f64); +coefficients_bspline_rectilinear_impl!(coefficients_bspline_rectilinear_f32, f32); + +macro_rules! eval_bspline_rectilinear_impl { + ($funcname:ident, $T:ty) => { + #[pyfunction] + fn $funcname( + grids: Vec>, + coeffs: PyReadonlyArray1<$T>, + linearize_extrapolation: bool, + obs: Vec>, + mut out: PyReadwriteArray1<$T>, + ) -> PyResult<()> { + unpack_vec_of_arr!(grids, grids, $T); + unpack_vec_of_arr!(obs, obs, $T); + + let ndims = grids.len(); + if obs.len() != ndims { + return Err(exceptions::PyAssertionError::new_err("Dimension mismatch")); + } + let coeffs = coeffs.as_slice()?; + let out = out.as_slice_mut()?; + + match crate::dispatch_ndims!( + ndims, + "Dimension exceeds maximum (8). Use interpolator struct directly for higher dimensions.", + [1, 2, 3, 4, 5, 6, 7, 8], + |N| { + let grids: &[&[$T]; N] = grids.try_into().unwrap(); + match multibspline::MultiBsplineRectilinear::<$T, N>::new( + grids, + coeffs, + linearize_extrapolation, + ) { + Ok(interpolator) => interpolator.interp(obs.try_into().unwrap(), out), + Err(msg) => Err(msg), + } + } + ) { + Ok(()) => Ok(()), + Err(msg) => Err(exceptions::PyAssertionError::new_err(msg)), + } + } + }; +} + +eval_bspline_rectilinear_impl!(_eval_bspline_rectilinear_f64, f64); +eval_bspline_rectilinear_impl!(_eval_bspline_rectilinear_f32, f32); + fn parse_grid_interp_method(method: &str) -> Result { match method.to_ascii_lowercase().as_str() { "linear" => Ok(GridInterpMethod::Linear), diff --git a/src/testing.rs b/src/testing.rs index f33a9f2..e0b3fb6 100644 --- a/src/testing.rs +++ b/src/testing.rs @@ -1,4 +1,4 @@ -use rand::Rng; +use rand::RngExt; use rand::SeedableRng; use rand::distr::StandardUniform; use rand::rngs::StdRng; diff --git a/test/test_interpn.py b/test/test_interpn.py index 0f185f8..a5f73be 100644 --- a/test/test_interpn.py +++ b/test/test_interpn.py @@ -62,3 +62,13 @@ def test_interpn_check_bounds_rectilinear(dtype, max_threads): check_bounds_with_atol=1e-8, max_threads=max_threads, ) + + +@pytest.mark.parametrize("method", ["bspline", "b-spline"]) +def test_interpn_rejects_bspline_method(method): + grid = np.linspace(0.0, 1.0, 5) + vals = np.linspace(0.0, 1.0, grid.size) + obs = [np.array([0.5])] + + with pytest.raises(ValueError): + interpn(obs=obs, grids=[grid], vals=vals, method=method) diff --git a/test/test_multibspline_rectilinear.py b/test/test_multibspline_rectilinear.py new file mode 100644 index 0000000..ba8ca8b --- /dev/null +++ b/test/test_multibspline_rectilinear.py @@ -0,0 +1,97 @@ +import numpy as np +import pytest +from scipy.interpolate import RegularGridInterpolator + +import interpn + + +@pytest.mark.parametrize("dtype,tol", [(np.float64, 1e-12), (np.float32, 1e-5)]) +def test_multibspline_rectilinear(dtype, tol): + x = np.array([-1.0, -0.35, 0.2, 0.95, 1.8, 3.0], dtype=dtype) + y = np.array([-2.0, -1.25, -0.1, 0.55, 1.7], dtype=dtype) + + xgrid, ygrid = np.meshgrid(x, y, indexing="ij") + zgrid = (xgrid * xgrid + 0.25 * xgrid * ygrid + ygrid).astype(dtype) + vals = zgrid.flatten() + grids = [x, y] + dims = [x.size, y.size] + + coeffs = np.zeros_like(vals) + scratch = np.zeros(2 * max(dims), dtype=dtype) + + if dtype == np.float32: + interpn.raw.coefficients_bspline_rectilinear_f32(grids, vals, coeffs, scratch) + else: + interpn.raw.coefficients_bspline_rectilinear_f64(grids, vals, coeffs, scratch) + + obs = [xgrid.flatten().astype(dtype), ygrid.flatten().astype(dtype)] + assert coeffs.shape == vals.shape + + interpolator = interpn.MultiBsplineRectilinear.new(grids, vals) + out2 = interpolator.eval(obs) + for i in range(out2.size): + assert approx(out2[i], vals[i], dtype(tol)) + + definitely_inside = [ + np.array([0.0]).astype(dtype), + np.array(0.0).astype(dtype), + ] + definitely_outside = [ + np.array([-5.0]).astype(dtype), + np.array(-25.0).astype(dtype), + ] + assert not any(interpolator.check_bounds(definitely_inside, dtype(1e-6))) + assert any(interpolator.check_bounds(definitely_outside, dtype(1e-6))) + + roundtrip_interpolator = interpn.MultiBsplineRectilinear.model_validate_json( + interpolator.model_dump_json() + ) + out3 = roundtrip_interpolator.eval(obs) + for i in range(out3.size): + assert approx(out3[i], vals[i], dtype(tol)) + + +def test_multibspline_rectilinear_quadratic_extrapolation(): + x = np.array([-1.0, -0.35, 0.2, 0.95, 1.8, 3.0]) + y = np.array([-2.0, -1.25, -0.1, 0.55, 1.7]) + xgrid, ygrid = np.meshgrid(x, y, indexing="ij") + vals = 0.5 * xgrid * xgrid + 0.25 * ygrid * ygrid + xgrid * ygrid - 0.3 + interp = interpn.MultiBsplineRectilinear.new( + [x, y], vals.ravel(), linearize_extrapolation=False + ) + + obs = [ + np.array([-1.5, -0.7, 0.0, 1.2, 3.4]), + np.array([-2.4, -0.9, 0.2, 1.2, 2.2]), + ] + out = interp.eval(obs) + expected = 0.5 * obs[0] * obs[0] + 0.25 * obs[1] * obs[1] + obs[0] * obs[1] - 0.3 + + assert np.allclose(out, expected, rtol=1e-12, atol=1e-12) + + +def test_multibspline_rectilinear_cubic_internal_points_vs_scipy(): + x = np.array([-1, -0.8, -0.55, -0.3, 0.05, 0.4, 0.9, 1.4, 2.0, 2.7, 3.5, 4.4]) + y = np.array([-2, -1.5, -0.9, -0.2, 0.4, 1.0, 1.8, 2.7, 3.7]) + xgrid, ygrid = np.meshgrid(x, y, indexing="ij") + vals = 0.2 * xgrid**3 - 0.1 * ygrid**3 + 0.5 * xgrid**2 + xgrid * ygrid - 0.2 + + interp = interpn.MultiBsplineRectilinear.new([x, y], vals.ravel()) + scipy_interp = RegularGridInterpolator( + [x, y], vals, method="cubic", bounds_error=False, fill_value=None + ) + + obs = [ + np.array([0.15, 0.65, 1.1, 1.75, 2.3]), + np.array([-0.5, 0.15, 0.65, 1.2, 2.1]), + ] + out = interp.eval(obs) + scipy_out = scipy_interp(np.array(obs).T) + + assert np.allclose(out, scipy_out, rtol=0.0, atol=1e-2) + + +def approx(value_is, value_should_be, tol) -> bool: + delta = abs(value_is - value_should_be) + norm = max(abs(value_should_be), 1.0) + return delta / norm < tol diff --git a/test/test_multibspline_regular.py b/test/test_multibspline_regular.py new file mode 100644 index 0000000..8146dc7 --- /dev/null +++ b/test/test_multibspline_regular.py @@ -0,0 +1,57 @@ +import numpy as np +import pytest +import interpn + + +@pytest.mark.parametrize("dtype,tol", [(np.float64, 1e-12), (np.float32, 1e-5)]) +def test_multibspline_regular(dtype, tol): + x = np.linspace(0.0, 10.0, 7).astype(dtype) + y = np.linspace(20.0, 30.0, 6).astype(dtype) + + xgrid, ygrid = np.meshgrid(x, y, indexing="ij") + zgrid = (xgrid * xgrid + 0.25 * xgrid * ygrid + ygrid).astype(dtype) + + dims = [x.size, y.size] + starts = np.array([x[0], y[0]]).astype(dtype) + steps = np.array([x[1] - x[0], y[1] - y[0]]).astype(dtype) + vals = zgrid.flatten() + + coeffs = np.zeros_like(vals) + scratch = np.zeros(2 * max(dims), dtype=dtype) + + if dtype == np.float32: + interpn.raw.coefficients_bspline_regular_f32(dims, vals, coeffs, scratch) + else: + interpn.raw.coefficients_bspline_regular_f64(dims, vals, coeffs, scratch) + + obs = [xgrid.flatten().astype(dtype), ygrid.flatten().astype(dtype)] + assert coeffs.shape == vals.shape + + interpolator = interpn.MultiBsplineRegular.new(dims, starts, steps, vals) + out2 = interpolator.eval(obs) + for i in range(out2.size): + assert approx(out2[i], vals[i], dtype(tol)) + + definitely_inside = [ + np.array([5.0]).astype(dtype), + np.array(25.0).astype(dtype), + ] + definitely_outside = [ + np.array([-5.0]).astype(dtype), + np.array(-25.0).astype(dtype), + ] + assert not any(interpolator.check_bounds(definitely_inside, dtype(1e-6))) + assert any(interpolator.check_bounds(definitely_outside, dtype(1e-6))) + + roundtrip_interpolator = interpn.MultiBsplineRegular.model_validate_json( + interpolator.model_dump_json() + ) + out3 = roundtrip_interpolator.eval(obs) + for i in range(out3.size): + assert approx(out3[i], vals[i], dtype(tol)) + + +def approx(value_is, value_should_be, tol) -> bool: + delta = abs(value_is - value_should_be) + norm = max(abs(value_should_be), 1.0) + return delta / norm < tol diff --git a/uv.lock b/uv.lock index b0fe85f..66ccd17 100644 --- a/uv.lock +++ b/uv.lock @@ -261,15 +261,12 @@ wheels = [ ] [[package]] -name = "griffe" -version = "1.14.0" +name = "griffelib" +version = "2.0.2" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "colorama" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ec/d7/6c09dd7ce4c7837e4cdb11dce980cb45ae3cd87677298dc3b781b6bce7d3/griffe-1.14.0.tar.gz", hash = "sha256:9d2a15c1eca966d68e00517de5d69dd1bc5c9f2335ef6c1775362ba5b8651a13", size = 424684, upload-time = "2025-09-05T15:02:29.167Z" } +sdist = { url = "https://files.pythonhosted.org/packages/9d/82/74f4a3310cdabfbb10da554c3a672847f1ed33c6f61dd472681ce7f1fe67/griffelib-2.0.2.tar.gz", hash = "sha256:3cf20b3bc470e83763ffbf236e0076b1211bac1bc67de13daf494640f2de707e", size = 166461, upload-time = "2026-03-27T11:34:51.091Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2a/b1/9ff6578d789a89812ff21e4e0f80ffae20a65d5dd84e7a17873fe3b365be/griffe-1.14.0-py3-none-any.whl", hash = "sha256:0e9d52832cccf0f7188cfe585ba962d2674b241c01916d780925df34873bceb0", size = 144439, upload-time = "2025-09-05T15:02:27.511Z" }, + { url = "https://files.pythonhosted.org/packages/11/8c/c9138d881c79aa0ea9ed83cbd58d5ca75624378b38cee225dcf5c42cc91f/griffelib-2.0.2-py3-none-any.whl", hash = "sha256:925c857658fb1ba40c0772c37acbc2ab650bd794d9c1b9726922e36ea4117ea1", size = 142357, upload-time = "2026-03-27T11:34:46.275Z" }, ] [[package]] @@ -339,18 +336,18 @@ provides-extras = ["pydantic"] bench = [ { name = "kaleido", specifier = "==0.2.1" }, { name = "memory-profiler", specifier = ">=0.61.0" }, - { name = "plotly", specifier = ">=5,<6" }, + { name = "plotly", specifier = ">=6,<7" }, { name = "scipy", specifier = ">=1.11.4" }, ] doc = [ { name = "mkdocs", specifier = ">=1.5.3" }, { name = "mkdocs-material", specifier = ">=9.4.10" }, - { name = "mkdocstrings-python", specifier = ">=1.7.5" }, + { name = "mkdocstrings-python", specifier = ">=2.0.3" }, ] test = [ { name = "kaleido", specifier = "==0.2.1" }, { name = "mktestdocs", specifier = "==0.2.1" }, - { name = "plotly", specifier = ">=5,<6" }, + { name = "plotly", specifier = ">=6,<7" }, { name = "pyright", specifier = "==1.1.407" }, { name = "pytest", specifier = ">=9" }, { name = "pytest-cov", specifier = ">=7.0.0" }, @@ -574,17 +571,17 @@ wheels = [ [[package]] name = "mkdocstrings-python" -version = "1.18.2" +version = "2.0.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "griffe" }, + { name = "griffelib" }, { name = "mkdocs-autorefs" }, { name = "mkdocstrings" }, { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/95/ae/58ab2bfbee2792e92a98b97e872f7c003deb903071f75d8d83aa55db28fa/mkdocstrings_python-1.18.2.tar.gz", hash = "sha256:4ad536920a07b6336f50d4c6d5603316fafb1172c5c882370cbbc954770ad323", size = 207972, upload-time = "2025-08-28T16:11:19.847Z" } +sdist = { url = "https://files.pythonhosted.org/packages/29/33/c225eaf898634bdda489a6766fc35d1683c640bffe0e0acd10646b13536d/mkdocstrings_python-2.0.3.tar.gz", hash = "sha256:c518632751cc869439b31c9d3177678ad2bfa5c21b79b863956ad68fc92c13b8", size = 199083, upload-time = "2026-02-20T10:38:36.368Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d5/8f/ce008599d9adebf33ed144e7736914385e8537f5fc686fdb7cceb8c22431/mkdocstrings_python-1.18.2-py3-none-any.whl", hash = "sha256:944fe6deb8f08f33fa936d538233c4036e9f53e840994f6146e8e94eb71b600d", size = 138215, upload-time = "2025-08-28T16:11:18.176Z" }, + { url = "https://files.pythonhosted.org/packages/32/28/79f0f8de97cce916d5ae88a7bee1ad724855e83e6019c0b4d5b3fabc80f3/mkdocstrings_python-2.0.3-py3-none-any.whl", hash = "sha256:0b83513478bdfd803ff05aa43e9b1fca9dd22bcd9471f09ca6257f009bc5ee12", size = 104779, upload-time = "2026-02-20T10:38:34.517Z" }, ] [[package]] @@ -596,6 +593,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/66/bb/8e781d4545c02034dae5db62ba46ccf1ba319dee47bfc3544a1b3bfc5f09/mktestdocs-0.2.1-py2.py3-none-any.whl", hash = "sha256:55ad757e83227d5ba217eb285b8e44dc490601c4bbef52bc3331fea4510b72ec", size = 7064, upload-time = "2023-04-27T06:01:51.552Z" }, ] +[[package]] +name = "narwhals" +version = "2.21.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cf/a0/6198c56d42ef2f3c6ed0c42ba30dbcefdc86a91262d7d449010770ae085b/narwhals-2.21.2.tar.gz", hash = "sha256:5c5b2d0b47aef7c73ea412cfcbcd467f2f2d5be73e3c2ab19d78f4a97718790a", size = 632176, upload-time = "2026-05-16T08:49:08.314Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1d/77/928ea2e70641ca177a11140062cc5840d421795f2e82749d408d0cce900a/narwhals-2.21.2-py3-none-any.whl", hash = "sha256:7bb57c3700486039215455b9bf2d64261915cc0fd845cc30272d631df696b251", size = 451201, upload-time = "2026-05-16T08:49:05.536Z" }, +] + [[package]] name = "nodeenv" version = "1.9.1" @@ -792,15 +798,15 @@ wheels = [ [[package]] name = "plotly" -version = "5.24.1" +version = "6.7.0" source = { registry = "https://pypi.org/simple" } dependencies = [ + { name = "narwhals" }, { name = "packaging" }, - { name = "tenacity" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/79/4f/428f6d959818d7425a94c190a6b26fbc58035cbef40bf249be0b62a9aedd/plotly-5.24.1.tar.gz", hash = "sha256:dbc8ac8339d248a4bcc36e08a5659bacfe1b079390b8953533f4eb22169b4bae", size = 9479398, upload-time = "2024-09-12T15:36:31.068Z" } +sdist = { url = "https://files.pythonhosted.org/packages/3a/7f/0f100df1172aadf88a929a9dbb902656b0880ba4b960fe5224867159d8f4/plotly-6.7.0.tar.gz", hash = "sha256:45eea0ff27e2a23ccd62776f77eb43aa1ca03df4192b76036e380bb479b892c6", size = 6911286, upload-time = "2026-04-09T20:36:45.738Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e5/ae/580600f441f6fc05218bd6c9d5794f4aef072a7d9093b291f1c50a9db8bc/plotly-5.24.1-py3-none-any.whl", hash = "sha256:f67073a1e637eb0dc3e46324d9d51e2fe76e9727c892dde64ddf1e1b51f29089", size = 19054220, upload-time = "2024-09-12T15:36:24.08Z" }, + { url = "https://files.pythonhosted.org/packages/90/ad/cba91b3bcf04073e4d1655a5c1710ef3f457f56f7d1b79dcc3d72f4dd912/plotly-6.7.0-py3-none-any.whl", hash = "sha256:ac8aca1c25c663a59b5b9140a549264a5badde2e057d79b8c772ae2920e32ff0", size = 9898444, upload-time = "2026-04-09T20:36:39.812Z" }, ] [[package]] @@ -1275,15 +1281,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, ] -[[package]] -name = "tenacity" -version = "9.1.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/0a/d4/2b0cd0fe285e14b36db076e78c93766ff1d529d70408bd1d2a5a84f1d929/tenacity-9.1.2.tar.gz", hash = "sha256:1169d376c297e7de388d18b4481760d478b0e99a777cad3a9c86e556f4b697cb", size = 48036, upload-time = "2025-04-02T08:25:09.966Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e5/30/643397144bfbfec6f6ef821f36f33e57d35946c44a2352d3c9f0ae847619/tenacity-9.1.2-py3-none-any.whl", hash = "sha256:f77bf36710d8b73a50b2dd155c97b870017ad21afe6ab300326b0371b3b05138", size = 28248, upload-time = "2025-04-02T08:25:07.678Z" }, -] - [[package]] name = "tomli" version = "2.2.1"