From e64b27d89a10acadf62d6e8a70544e76a41781f2 Mon Sep 17 00:00:00 2001 From: Xavier Lange Date: Fri, 9 Oct 2026 20:30:04 +0000 Subject: [PATCH 1/8] Make native build discovery explicit and pin stable workspace tooling --- .gitignore | 1 - Cargo.lock | 666 ++++++++++++++++++++++++++++++++++ Cargo.toml | 14 +- benches/molecule_benchmark.rs | 60 ++- rdkit-sys/Cargo.toml | 9 +- rdkit-sys/build.rs | 189 ++++------ rdkit-sys/rustfmt.toml | 69 ---- rust-toolchain.toml | 4 + rustfmt.toml | 69 ---- 9 files changed, 784 insertions(+), 297 deletions(-) create mode 100644 Cargo.lock create mode 100644 rust-toolchain.toml diff --git a/.gitignore b/.gitignore index 5f744ea..143dcbe 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ /target -/Cargo.lock .idea/ tests/fixtures/* *.iml diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..f9e28c3 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,666 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "atty" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" +dependencies = [ + "hermit-abi", + "libc", + "winapi", +] + +[[package]] +name = "bitvec" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "cc" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f74872d07caf508b30a21f6836e7d7016a2eaf7d9ff4f48deaa58cd8a0407630" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + +[[package]] +name = "crc32fast" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "cxx" +version = "1.0.203" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "997704fde49dd562d9f0669d43b1354b3342863d902f6e6a8476c75306a2043f" +dependencies = [ + "cc", + "cxx-build", + "cxxbridge-cmd", + "cxxbridge-flags", + "cxxbridge-macro", + "foldhash", + "link-cplusplus", +] + +[[package]] +name = "cxx-build" +version = "1.0.203" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f19a8878d33dcaa97ff2dd879675a45451cca8c611e0775f6d5111868a7881" +dependencies = [ + "cc", + "codespan-reporting", + "indexmap", + "proc-macro2", + "quote", + "scratch", + "syn 3.0.6", +] + +[[package]] +name = "cxxbridge-cmd" +version = "1.0.203" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b3c0d6bb9bce1e4e07ce4207f4b481ef2fc527ca4fb89956afcb5ee21af922" +dependencies = [ + "clap", + "codespan-reporting", + "indexmap", + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "cxxbridge-flags" +version = "1.0.203" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acef51de43cd46e2bcfae1632a9b295c955814c9d6c67ebde75f6c7facc29979" + +[[package]] +name = "cxxbridge-macro" +version = "1.0.203" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70dc5bc6f6a4338ba4c8174955516f8f56ad3a92b9ee3c87358506bb5e215518" +dependencies = [ + "indexmap", + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "env_logger" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a12e6657c4c97ebab115a42dcee77225f7f482cdd841cf7088c657a42e9e00e7" +dependencies = [ + "atty", + "humantime", + "log", + "regex", + "termcolor", +] + +[[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.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hermit-abi" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" +dependencies = [ + "libc", +] + +[[package]] +name = "humantime" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "link-cplusplus" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f78c730aaa7d0b9336a299029ea49f9ee53b0ed06e9202e8cb7db9bae7b8c82" +dependencies = [ + "cc", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rdkit" +version = "0.4.12" +dependencies = [ + "bitvec", + "byteorder", + "cxx", + "env_logger", + "flate2", + "log", + "rdkit-sys", + "static_assertions", + "thiserror", + "trybuild", +] + +[[package]] +name = "rdkit-sys" +version = "0.4.12" +dependencies = [ + "cxx", + "cxx-build", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "scratch" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d68f2ec51b097e4c1a75b681a8bec621909b5e91f15bb7b840c4f2f7b01148b2" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[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.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "target-tuple" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "876fef147edbcbddc8ac5cbbba92c7b86519e314e86638596c09673b2ed01e7f" + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl", +] + +[[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 2.0.119", +] + +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + +[[package]] +name = "trybuild" +version = "1.0.122" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62db9c92d704393fbf2132041720cc80b689f2d3f28521015c2ac866223c11b8" +dependencies = [ + "glob", + "serde", + "serde_derive", + "serde_json", + "target-tuple", + "termcolor", + "toml", +] + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[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 = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[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.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index 1086859..970f61f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,11 +13,21 @@ members = ["rdkit-sys"] [dependencies] bitvec = "1" byteorder = "1.4.3" -cxx = "1" +cxx = "1.0.203" flate2 = "1" log = "0.4" -rdkit-sys = { path = "rdkit-sys", version = "0.4.9" } +rdkit-sys = { path = "rdkit-sys", version = "=0.4.12" } thiserror = "1" +[features] +default = [] +dynamic-linking-from-conda = ["rdkit-sys/dynamic-linking-from-conda"] + +[[bench]] +name = "molecule_benchmark" +harness = false + [dev-dependencies] +trybuild = "1" +static_assertions = "1" env_logger = "0.9.0" diff --git a/benches/molecule_benchmark.rs b/benches/molecule_benchmark.rs index 24b6d2c..c341562 100644 --- a/benches/molecule_benchmark.rs +++ b/benches/molecule_benchmark.rs @@ -1,38 +1,32 @@ -#![allow(soft_unstable)] -#![feature(test)] -extern crate test; - use rdkit::ROMol; - -#[bench] -fn bench_molecules(bencher: &mut test::bench::Bencher) { - let smiles1 = "c1ccccc1CCCCCCCC"; - - bencher.iter(|| { - ROMol::from_smiles(smiles1).unwrap(); - }) -} - -#[bench] -fn bench_fingerprint(bencher: &mut test::bench::Bencher) { - let smiles1 = "c1ccccc1CCCCCCCC"; - let mol1 = ROMol::from_smiles(smiles1).unwrap(); - - bencher.iter(|| mol1.rdk_fingerprint()) +use std::{hint::black_box, time::Instant}; + +fn measure(name: &str, iterations: u32, mut operation: impl FnMut() -> T) { + let start = Instant::now(); + for _ in 0..iterations { + black_box(operation()); + } + println!( + "{name}: {:.0} ns/iteration ({iterations} iterations)", + start.elapsed().as_nanos() as f64 / iterations as f64 + ); } -#[bench] -fn bench_tanimoto(bencher: &mut test::bench::Bencher) { - let smiles1 = "c1ccccc1CCCCCCCC"; - let mol1 = ROMol::from_smiles(smiles1).unwrap(); - let smiles2 = "c1ccccc1CCCCCC"; - let mol2 = ROMol::from_smiles(smiles2).unwrap(); - - bencher.iter(|| { - let mol1_fingerprint = mol1.rdk_fingerprint(); - - let mol2_fingerprint = mol2.rdk_fingerprint(); - - mol1_fingerprint.tanimoto_distance(&mol2_fingerprint) +fn main() { + let iterations = 1_000; + let smiles = "c1ccccc1CCCCCCCC"; + measure("SMILES parsing", iterations, || { + ROMol::from_smiles(black_box(smiles)).unwrap() + }); + let mol = ROMol::from_smiles(smiles).unwrap(); + measure("RDK fingerprint", iterations, || { + black_box(&mol).rdk_fingerprint() + }); + let first = mol.rdk_fingerprint(); + let second = ROMol::from_smiles("c1ccccc1CCCCCC") + .unwrap() + .rdk_fingerprint(); + measure("Tanimoto similarity", iterations, || { + black_box(&first).tanimoto_similarity(black_box(&second)) }); } diff --git a/rdkit-sys/Cargo.toml b/rdkit-sys/Cargo.toml index 722c75a..c45b752 100644 --- a/rdkit-sys/Cargo.toml +++ b/rdkit-sys/Cargo.toml @@ -4,19 +4,18 @@ authors = ["Xavier Lange (xrlange@gmail.com)", "chrissly31415"] version = "0.4.12" edition = "2021" license = "MIT" -description = "RDKit CFFI library builder and bindings" +description = "CXX bindings to the RDKit C++ library" +links = "rdkit" repository = "https://github.com/rdkit-rs/rdkit/tree/main/rdkit-sys" exclude = ["rdkit-*", "*.tar.gz", "examples/"] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -cxx = "1.0.109" +cxx = "1.0.203" [build-dependencies] -env_logger = "0.10.0" -cxx-build = "1.0.109" -which = "4.4.2" +cxx-build = "1.0.203" [features] default = [] diff --git a/rdkit-sys/build.rs b/rdkit-sys/build.rs index 782861d..9c4c675 100644 --- a/rdkit-sys/build.rs +++ b/rdkit-sys/build.rs @@ -1,146 +1,99 @@ -const CPP_VERSION_FLAG: &str = "-std=c++17"; +use std::env; +use std::path::PathBuf; fn main() { - if std::env::var("DOCS_RS").is_ok() { + for name in [ + "DOCS_RS", + "RDKIT_PREFIX", + "RDKIT_INCLUDE_DIR", + "RDKIT_LIB_DIR", + "CONDA_PREFIX", + ] { + println!("cargo:rerun-if-env-changed={name}"); + } + if env::var_os("DOCS_RS").is_some() { return; } - env_logger::init(); - - let use_conda = std::env::var("CARGO_FEATURE_DYNAMIC_LINKING_FROM_CONDA").is_ok(); - - let mut lib_paths = vec![]; - let mut include_paths = vec![]; - - match (std::env::consts::OS, std::env::consts::ARCH, use_conda) { - (_, _, true) => { - // prefer the prefix env var, if not, fall back to the base from the CLI - match std::env::var("CONDA_PREFIX") { - Ok(prefix) => { - include_paths.push(format!("{prefix}/include")); - include_paths.push(format!("{prefix}/include/rdkit")); - lib_paths.push(format!("{prefix}/lib")); - } - Err(_) => { - let conda = which::which("conda") - .map(|p| p.to_str().unwrap().to_string()) - .unwrap_or_else(|_| panic!("conda not found")); - let mut conda = std::process::Command::new(conda); - conda.args(["info", "--base"]); - - let output = conda.output().unwrap(); - let stdout = String::from_utf8(output.stdout).unwrap(); - let conda_root = stdout.trim().to_string(); - - lib_paths.push(format!("{}/lib", conda_root)); - include_paths.push(format!("{}/include", conda_root)); - include_paths.push(format!("{}/include/rdkit", conda_root)); - } - } - } - ("macos", "x86_64", _) => { - include_paths.push("/usr/local/include".to_string()); - include_paths.push("/usr/local/include/rdkit".to_string()); - } - ("macos", "aarch64", _) => { - include_paths.push("/opt/homebrew/include".to_string()); - include_paths.push("/opt/homebrew/include/rdkit".to_string()); - lib_paths.push("/opt/homebrew/lib".to_string()) - } - ("linux", _, _) => { - include_paths.push("/usr/local/include".to_string()); - include_paths.push("/usr/local/include/rdkit".to_string()); - include_paths.push("/usr/include".to_string()); - include_paths.push("/usr/include/rdkit".to_string()); - } - (unsupported_os, unsupported_arch, use_conda) => panic!( - "sorry, rdkit-sys doesn't support {}/{}/use_conda={} at this time", - unsupported_os, unsupported_arch, use_conda - ), - }; - - let dir = std::fs::read_dir("src/bridge").unwrap(); - let rust_files = dir - .into_iter() - .filter_map(|p| match p { - Ok(p) => { - if p.metadata().unwrap().is_file() { - Some(p.path()) - } else { - None - } - } - Err(_) => None, + let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap(); + let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap(); + if !matches!(target_os.as_str(), "linux" | "macos") { + panic!("rdkit-sys supports Linux and macOS; {target_os}/{target_arch} is not tested"); + } + let prefix = env::var_os("RDKIT_PREFIX") + .or_else(|| { + env::var_os("CARGO_FEATURE_DYNAMIC_LINKING_FROM_CONDA").map(|_| { + env::var_os("CONDA_PREFIX") + .expect("activate a conda environment or set RDKIT_PREFIX") + }) }) - .filter(|p| !p.ends_with("mod.rs")) - .collect::>(); - - let mut wrapper_cc_paths = vec![]; + .map(PathBuf::from) + .unwrap_or_else(|| match (target_os.as_str(), target_arch.as_str()) { + ("macos", "aarch64") => PathBuf::from("/opt/homebrew"), + ("macos", _) => PathBuf::from("/usr/local"), + _ => PathBuf::from("/usr"), + }); + let include_dir = env::var_os("RDKIT_INCLUDE_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| prefix.join("include/rdkit")); + let lib_dir = env::var_os("RDKIT_LIB_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| prefix.join("lib")); + if !include_dir.join("GraphMol/ROMol.h").is_file() { + panic!( + "RDKit headers not found at {}. Install librdkit-dev or set RDKIT_PREFIX / RDKIT_INCLUDE_DIR; see docs/building.md", + include_dir.display() + ); + } - let wrapper_root = std::path::PathBuf::from("wrapper"); + let mut rust_files: Vec<_> = std::fs::read_dir("src/bridge") + .expect("read src/bridge") + .map(|entry| entry.expect("read bridge entry").path()) + .filter(|path| path.extension().is_some_and(|ext| ext == "rs")) + .filter(|path| !path.ends_with("mod.rs")) + .collect(); + rust_files.sort(); + let mut cpp_files = Vec::new(); + println!("cargo:rerun-if-changed=src/bridge"); + println!("cargo:rerun-if-changed=wrapper"); for file in &rust_files { - let file_name = file.file_name().unwrap(); - let file_name = file_name.to_str().unwrap(); - let base_name = &file_name[0..file_name.len() - 3]; - - let cc_path = wrapper_root.join("src").join(format!("{}.cc", base_name)); - let meta = std::fs::metadata(&cc_path).unwrap(); - if !meta.is_file() { - panic!("{} must exist", cc_path.display()) + let stem = file.file_stem().unwrap().to_str().unwrap(); + let source = PathBuf::from(format!("wrapper/src/{stem}.cc")); + let header = PathBuf::from(format!("wrapper/include/{stem}.h")); + assert!(source.is_file(), "{} must exist", source.display()); + assert!(header.is_file(), "{} must exist", header.display()); + for path in [file, &source, &header] { + println!("cargo:rerun-if-changed={}", path.display()); } - println!("cargo:rerun-if-changed={}", cc_path.to_str().unwrap()); - wrapper_cc_paths.push(cc_path); - - let h_path = wrapper_root - .join("include") - .join(format!("{}.h", base_name)); - let meta = std::fs::metadata(&h_path) - .unwrap_or_else(|_| panic!("could not get metadata for {h_path:?}")); - if !meta.is_file() { - panic!("{} must exist", h_path.display()) - } - println!("cargo:rerun-if-changed={}", h_path.to_str().unwrap()); + cpp_files.push(source); } cxx_build::bridges(rust_files) - .files(wrapper_cc_paths) - .includes(include_paths) - .include(std::env::var("CARGO_MANIFEST_DIR").unwrap()) - .flag(CPP_VERSION_FLAG) + .files(cpp_files) + .include(include_dir) + .include(prefix.join("include")) + .include(prefix.join("include/eigen3")) + .include(env::var_os("CARGO_MANIFEST_DIR").unwrap()) + .std("c++20") .warnings(false) - // rdkit has warnings that blow up our build. we could enumerate all those warnings and tell - // the compiler to allow them... .warnings_into_errors(true) - .compile("rdkit"); + .compile("rdkit_cxx_bridge"); - for path in lib_paths { - println!("cargo:rustc-link-search=native={}", path); - } - // println!("cargo:rustc-link-lib=static=c++"); - - for lib in &[ - // "Catalogs", - // "ChemReactions", - // "ChemTransforms", + println!("cargo:rustc-link-search=native={}", lib_dir.display()); + for lib in [ "DataStructs", - // "Depictor", + "Depictor", "Descriptors", "FileParsers", "Fingerprints", - // "GenericGroups", "GraphMol", "MolStandardize", - // "MolTransforms", - // "PartialCharges", "RDGeneral", - // "RDGeometryLib", - // "RingDecomposerLib", + "RDGeometryLib", "ScaffoldNetwork", "SmilesParse", - // "Subgraphs", "SubstructMatch", ] { - println!("cargo:rustc-link-lib=dylib=RDKit{}", lib); + println!("cargo:rustc-link-lib=dylib=RDKit{lib}"); } - println!("cargo:rustc-link-lib=dylib=boost_serialization"); } diff --git a/rdkit-sys/rustfmt.toml b/rdkit-sys/rustfmt.toml index 7de3b73..e61fcbe 100644 --- a/rdkit-sys/rustfmt.toml +++ b/rdkit-sys/rustfmt.toml @@ -1,75 +1,6 @@ max_width = 100 -hard_tabs = false -tab_spaces = 4 -newline_style = "Auto" -indent_style = "Block" use_small_heuristics = "Default" fn_call_width = 60 -attr_fn_like_width = 70 struct_lit_width = 18 -struct_variant_width = 35 -array_width = 60 chain_width = 60 -single_line_if_else_max_width = 50 -format_code_in_doc_comments = false -comment_width = 80 -normalize_comments = false -normalize_doc_attributes = false -format_strings = false -format_macro_matchers = false -format_macro_bodies = true -hex_literal_case = "Preserve" -empty_item_single_line = true -struct_lit_single_line = true -fn_single_line = false -where_single_line = false -imports_indent = "Block" -imports_layout = "Mixed" -reorder_imports = true -reorder_modules = true -type_punctuation_density = "Wide" -space_before_colon = false -space_after_colon = true -spaces_around_ranges = false -binop_separator = "Front" -remove_nested_parens = true -combine_control_expr = true -overflow_delimited_expr = false -struct_field_align_threshold = 0 -enum_discrim_align_threshold = 0 -match_arm_blocks = true -match_arm_leading_pipes = "Never" -force_multiline_blocks = false -fn_params_layout = "Tall" -brace_style = "SameLineWhere" -control_brace_style = "AlwaysSameLine" -trailing_semicolon = true -trailing_comma = "Vertical" -match_block_trailing_comma = false -blank_lines_upper_bound = 1 -blank_lines_lower_bound = 0 edition = "2021" -version = "One" -inline_attribute_width = 0 -format_generated_files = true -merge_derives = true -use_try_shorthand = false -use_field_init_shorthand = false -force_explicit_abi = true -condense_wildcard_suffixes = false -color = "Auto" -unstable_features = false -disable_all_formatting = false -skip_children = false -show_parse_errors = false -error_on_line_overflow = false -error_on_unformatted = false -ignore = [] -emit_mode = "Files" -make_backup = false - - -imports_granularity = "Crate" -group_imports = "StdExternalCrate" -reorder_impl_items = true -wrap_comments = true diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..b432996 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,4 @@ +[toolchain] +channel = "1.99.0" +profile = "minimal" +components = ["rustfmt", "clippy"] diff --git a/rustfmt.toml b/rustfmt.toml index 7de3b73..e61fcbe 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,75 +1,6 @@ max_width = 100 -hard_tabs = false -tab_spaces = 4 -newline_style = "Auto" -indent_style = "Block" use_small_heuristics = "Default" fn_call_width = 60 -attr_fn_like_width = 70 struct_lit_width = 18 -struct_variant_width = 35 -array_width = 60 chain_width = 60 -single_line_if_else_max_width = 50 -format_code_in_doc_comments = false -comment_width = 80 -normalize_comments = false -normalize_doc_attributes = false -format_strings = false -format_macro_matchers = false -format_macro_bodies = true -hex_literal_case = "Preserve" -empty_item_single_line = true -struct_lit_single_line = true -fn_single_line = false -where_single_line = false -imports_indent = "Block" -imports_layout = "Mixed" -reorder_imports = true -reorder_modules = true -type_punctuation_density = "Wide" -space_before_colon = false -space_after_colon = true -spaces_around_ranges = false -binop_separator = "Front" -remove_nested_parens = true -combine_control_expr = true -overflow_delimited_expr = false -struct_field_align_threshold = 0 -enum_discrim_align_threshold = 0 -match_arm_blocks = true -match_arm_leading_pipes = "Never" -force_multiline_blocks = false -fn_params_layout = "Tall" -brace_style = "SameLineWhere" -control_brace_style = "AlwaysSameLine" -trailing_semicolon = true -trailing_comma = "Vertical" -match_block_trailing_comma = false -blank_lines_upper_bound = 1 -blank_lines_lower_bound = 0 edition = "2021" -version = "One" -inline_attribute_width = 0 -format_generated_files = true -merge_derives = true -use_try_shorthand = false -use_field_init_shorthand = false -force_explicit_abi = true -condense_wildcard_suffixes = false -color = "Auto" -unstable_features = false -disable_all_formatting = false -skip_children = false -show_parse_errors = false -error_on_line_overflow = false -error_on_unformatted = false -ignore = [] -emit_mode = "Files" -make_backup = false - - -imports_granularity = "Crate" -group_imports = "StdExternalCrate" -reorder_impl_items = true -wrap_comments = true From f50516c82168b45b10b5b928be1489bdeb27f302 Mon Sep 17 00:00:00 2001 From: Xavier Lange Date: Fri, 9 Oct 2026 20:30:37 +0000 Subject: [PATCH 2/8] Use exclusive CXX ownership and add checked molecule workflows Audit all existing native declarations and shims, translate exceptions, and tie atom, bond and conformer views to their molecule owners. Add graph edits, configurable fingerprints and scaffold networks with regression coverage. Preserve compatible downstream error text and native version semantics. Adapt contributor work from PRs #19, #50, #51, #52, #54 and #56. Co-authored-by: Alexandra Ebberg Co-authored-by: Sharif Haason Co-authored-by: Chris Petersen --- .clang-format | 2 +- .../examples/rdkit_sys_tautomer_enumerator.rs | 24 +- rdkit-sys/src/bridge/bond.rs | 78 +++++ rdkit-sys/src/bridge/conformer.rs | 28 ++ rdkit-sys/src/bridge/descriptors.rs | 12 +- rdkit-sys/src/bridge/fingerprint.rs | 31 +- rdkit-sys/src/bridge/mod.rs | 5 + rdkit-sys/src/bridge/mol_ops.rs | 113 ++++--- rdkit-sys/src/bridge/mol_standardize.rs | 44 +-- rdkit-sys/src/bridge/periodic_table.rs | 72 ++-- rdkit-sys/src/bridge/ro_mol.rs | 75 +++-- rdkit-sys/src/bridge/rw_mol.rs | 26 +- rdkit-sys/src/bridge/scaffold_network.rs | 75 +++-- rdkit-sys/src/bridge/substruct_match.rs | 62 ++-- rdkit-sys/src/lib.rs | 14 - rdkit-sys/tests/test_atoms.rs | 17 +- rdkit-sys/tests/test_descriptors.rs | 13 +- rdkit-sys/tests/test_fingerprint.rs | 8 +- rdkit-sys/tests/test_mol_ops.rs | 19 +- rdkit-sys/tests/test_mol_standardize.rs | 21 +- rdkit-sys/tests/test_periodic_table.rs | 115 +++++-- rdkit-sys/tests/test_ro_mol.rs | 72 ++-- rdkit-sys/tests/test_rw_mol.rs | 24 +- rdkit-sys/tests/test_scaffold_network.rs | 26 +- rdkit-sys/tests/test_substruct_match.rs | 10 +- rdkit-sys/wrapper/include/bond.h | 27 ++ rdkit-sys/wrapper/include/conformer.h | 17 + rdkit-sys/wrapper/include/descriptors.h | 7 +- rdkit-sys/wrapper/include/fingerprint.h | 18 +- rdkit-sys/wrapper/include/mol_ops.h | 76 ++--- rdkit-sys/wrapper/include/mol_standardize.h | 28 +- rdkit-sys/wrapper/include/owned.h | 12 + rdkit-sys/wrapper/include/periodic_table.h | 4 +- rdkit-sys/wrapper/include/ro_mol.h | 31 +- rdkit-sys/wrapper/include/rw_mol.h | 18 +- rdkit-sys/wrapper/include/scaffold_network.h | 40 ++- rdkit-sys/wrapper/include/substruct_match.h | 35 +- rdkit-sys/wrapper/src/bond.cc | 44 +++ rdkit-sys/wrapper/src/conformer.cc | 27 ++ rdkit-sys/wrapper/src/descriptors.cc | 15 +- rdkit-sys/wrapper/src/fingerprint.cc | 49 ++- rdkit-sys/wrapper/src/mol_ops.cc | 121 +++---- rdkit-sys/wrapper/src/mol_standardize.cc | 62 ++-- rdkit-sys/wrapper/src/periodic_table.cc | 32 +- rdkit-sys/wrapper/src/ro_mol.cc | 78 +++-- rdkit-sys/wrapper/src/rw_mol.cc | 66 +++- rdkit-sys/wrapper/src/scaffold_network.cc | 117 +++++-- rdkit-sys/wrapper/src/substruct_match.cc | 66 ++-- src/descriptors.rs | 41 ++- src/file_parsers.rs | 115 ++++--- src/fingerprint.rs | 43 ++- src/graphmol/atom.rs | 151 +++++++-- src/graphmol/atom_ref.rs | 119 +++++++ src/graphmol/bond.rs | 67 ++++ src/graphmol/conformer.rs | 45 +++ src/graphmol/mod.rs | 7 + src/graphmol/mol_ops.rs | 168 +++++---- src/graphmol/ro_mol.rs | 217 +++++++++--- src/graphmol/rw_mol.rs | 186 ++++++++-- src/lib.rs | 3 + src/mol_standardize.rs | 156 +++++---- src/periodic_table.rs | 187 +++++----- src/scaffold_network.rs | 231 +++++++++++++ src/substruct_match/mod.rs | 23 +- src/substruct_match/substruct_match_item.rs | 6 +- .../substruct_match_parameters.rs | 35 +- src/verbose_file_parsers.rs | 69 ++-- tests/test_atom.rs | 8 +- tests/test_borrowing.rs | 5 + tests/test_graphmol.rs | 20 +- tests/test_periodic_table.rs | 2 +- tests/test_safety.rs | 318 ++++++++++++++++++ tests/test_scaffold_network.rs | 170 ++++++++++ tests/ui/atom_outlives_molecule.rs | 8 + tests/ui/atom_outlives_molecule.stderr | 11 + tests/ui/bond_blocks_graph_edit.rs | 7 + tests/ui/bond_blocks_graph_edit.stderr | 9 + tests/ui/conformer_blocks_coordinates.rs | 8 + tests/ui/conformer_blocks_coordinates.stderr | 9 + tests/ui/low_level_mutable_alias.rs | 9 + tests/ui/low_level_mutable_alias.stderr | 9 + tests/ui/low_level_ownership_cannot_clone.rs | 7 + .../low_level_ownership_cannot_clone.stderr | 5 + tests/ui/shared_atom_blocks_mutation.rs | 7 + tests/ui/shared_atom_blocks_mutation.stderr | 9 + 85 files changed, 3279 insertions(+), 1187 deletions(-) create mode 100644 rdkit-sys/src/bridge/bond.rs create mode 100644 rdkit-sys/src/bridge/conformer.rs create mode 100644 rdkit-sys/wrapper/include/bond.h create mode 100644 rdkit-sys/wrapper/include/conformer.h create mode 100644 rdkit-sys/wrapper/include/owned.h create mode 100644 rdkit-sys/wrapper/src/bond.cc create mode 100644 rdkit-sys/wrapper/src/conformer.cc create mode 100644 src/graphmol/atom_ref.rs create mode 100644 src/graphmol/bond.rs create mode 100644 src/graphmol/conformer.rs create mode 100644 src/scaffold_network.rs create mode 100644 tests/test_borrowing.rs create mode 100644 tests/test_safety.rs create mode 100644 tests/test_scaffold_network.rs create mode 100644 tests/ui/atom_outlives_molecule.rs create mode 100644 tests/ui/atom_outlives_molecule.stderr create mode 100644 tests/ui/bond_blocks_graph_edit.rs create mode 100644 tests/ui/bond_blocks_graph_edit.stderr create mode 100644 tests/ui/conformer_blocks_coordinates.rs create mode 100644 tests/ui/conformer_blocks_coordinates.stderr create mode 100644 tests/ui/low_level_mutable_alias.rs create mode 100644 tests/ui/low_level_mutable_alias.stderr create mode 100644 tests/ui/low_level_ownership_cannot_clone.rs create mode 100644 tests/ui/low_level_ownership_cannot_clone.stderr create mode 100644 tests/ui/shared_atom_blocks_mutation.rs create mode 100644 tests/ui/shared_atom_blocks_mutation.stderr diff --git a/.clang-format b/.clang-format index 108110c..f562bb3 100644 --- a/.clang-format +++ b/.clang-format @@ -69,7 +69,7 @@ DerivePointerAlignment: false DisableFormat: false EmptyLineBeforeAccessModifier: LogicalBlock ExperimentalAutoDetectBinPacking: false -FixNamespaceComments: true +FixNamespaceComments: false ForEachMacros: - foreach - Q_FOREACH diff --git a/rdkit-sys/examples/rdkit_sys_tautomer_enumerator.rs b/rdkit-sys/examples/rdkit_sys_tautomer_enumerator.rs index 07df88b..bd03925 100644 --- a/rdkit-sys/examples/rdkit_sys_tautomer_enumerator.rs +++ b/rdkit-sys/examples/rdkit_sys_tautomer_enumerator.rs @@ -3,26 +3,33 @@ use cxx::let_cxx_string; fn main() { let_cxx_string!(smiles = "c1ccccc1C(=O)NC"); let mol = rdkit_sys::ro_mol_ffi::smiles_to_mol(&smiles).unwrap(); - let tautomer_enumerator = rdkit_sys::mol_standardize_ffi::tautomer_enumerator(); + let tautomer_enumerator = + rdkit_sys::mol_standardize_ffi::tautomer_enumerator().expect("RDKit operation failed"); let tautomer_enumerator_result = - rdkit_sys::mol_standardize_ffi::tautomer_enumerate(&tautomer_enumerator, &mol); + rdkit_sys::mol_standardize_ffi::tautomer_enumerate(&tautomer_enumerator, &mol) + .expect("RDKit operation failed"); let size = rdkit_sys::mol_standardize_ffi::tautomer_enumerator_result_tautomers_size( &tautomer_enumerator_result, - ); + ) + .expect("RDKit operation failed"); println!("size: {}", size); let first = rdkit_sys::mol_standardize_ffi::tautomer_enumerator_result_tautomers_at( &tautomer_enumerator_result, 0, - ); - let first_smiles = rdkit_sys::ro_mol_ffi::mol_to_smiles(&first); + ) + .expect("RDKit operation failed"); + let first_smiles = + rdkit_sys::ro_mol_ffi::mol_to_smiles(&first).expect("RDKit operation failed"); println!("first smiles: {}", first_smiles); let second = rdkit_sys::mol_standardize_ffi::tautomer_enumerator_result_tautomers_at( &tautomer_enumerator_result, 1, - ); - let second_smiles = rdkit_sys::ro_mol_ffi::mol_to_smiles(&second); + ) + .expect("RDKit operation failed"); + let second_smiles = + rdkit_sys::ro_mol_ffi::mol_to_smiles(&second).expect("RDKit operation failed"); println!("second smiles: {}", second_smiles); let canonical_mol = rdkit_sys::mol_standardize_ffi::tautomer_enumerator_canonicalize( @@ -30,6 +37,7 @@ fn main() { &mol, ) .unwrap(); - let canonical_smiles = rdkit_sys::ro_mol_ffi::mol_to_smiles(&canonical_mol); + let canonical_smiles = + rdkit_sys::ro_mol_ffi::mol_to_smiles(&canonical_mol).expect("RDKit operation failed"); println!("canonical: {}", canonical_smiles); } diff --git a/rdkit-sys/src/bridge/bond.rs b/rdkit-sys/src/bridge/bond.rs new file mode 100644 index 0000000..2093575 --- /dev/null +++ b/rdkit-sys/src/bridge/bond.rs @@ -0,0 +1,78 @@ +#[cxx::bridge(namespace = "RDKit")] +pub mod ffi { + #[repr(i32)] + #[derive(Debug, PartialEq)] + pub enum BondType { + UNSPECIFIED, + SINGLE, + DOUBLE, + TRIPLE, + QUADRUPLE, + QUINTUPLE, + HEXTUPLE, + ONEANDAHALF, + TWOANDAHALF, + THREEANDAHALF, + FOURANDAHALF, + FIVEANDAHALF, + AROMATIC, + IONIC, + HYDROGEN, + THREECENTER, + DATIVEONE, + DATIVE, + DATIVEL, + DATIVER, + OTHER, + ZERO, + } + + #[repr(i32)] + #[derive(Debug, PartialEq)] + pub enum BondStereo { + STEREONONE, + STEREOANY, + STEREOZ, + STEREOE, + STEREOCIS, + STEREOTRANS, + } + + #[repr(i32)] + #[derive(Debug, PartialEq)] + pub enum BondDir { + NONE, + BEGINWEDGE, + BEGINDASH, + ENDDOWNRIGHT, + ENDUPRIGHT, + EITHERDOUBLE, + UNKNOWN, + } + + unsafe extern "C++" { + include!("wrapper/include/bond.h"); + + pub type ROMol = crate::ro_mol_ffi::ROMol; + pub type Bond; + pub type BondType; + pub type BondStereo; + pub type BondDir; + + pub fn get_num_bonds(mol: &ROMol, only_heavy: bool) -> Result; + pub fn get_bond_with_idx(mol: &ROMol, idx: u32) -> Result<&Bond>; + pub fn get_bond_idx_between_atoms(mol: &ROMol, begin_idx: u32, end_idx: u32) + -> Result; + + pub fn bond_get_bond_type(bond: &Bond) -> Result; + pub fn bond_get_bond_type_as_double(bond: &Bond) -> Result; + pub fn bond_get_begin_atom_idx(bond: &Bond) -> Result; + pub fn bond_get_end_atom_idx(bond: &Bond) -> Result; + pub fn bond_get_other_atom_idx(bond: &Bond, this_idx: u32) -> Result; + pub fn bond_get_is_aromatic(bond: &Bond) -> Result; + pub fn bond_get_is_conjugated(bond: &Bond) -> Result; + pub fn bond_get_stereo(bond: &Bond) -> Result; + pub fn bond_get_bond_dir(bond: &Bond) -> Result; + pub fn bond_get_idx(bond: &Bond) -> Result; + } +} diff --git a/rdkit-sys/src/bridge/conformer.rs b/rdkit-sys/src/bridge/conformer.rs new file mode 100644 index 0000000..1ed5e55 --- /dev/null +++ b/rdkit-sys/src/bridge/conformer.rs @@ -0,0 +1,28 @@ +#[cxx::bridge(namespace = "RDKit")] +pub mod ffi { + #[derive(Debug, Clone, Copy, PartialEq)] + pub struct Point3D { + pub x: f64, + pub y: f64, + pub z: f64, + } + + unsafe extern "C++" { + include!("wrapper/include/conformer.h"); + pub type ROMol = crate::ro_mol_ffi::ROMol; + pub type Conformer; + pub fn compute_2d_coords(mol: Pin<&mut ROMol>) -> Result; + pub fn get_num_conformers(mol: &ROMol) -> Result; + pub fn get_conformer(mol: &ROMol, id: i32) -> Result<&Conformer>; + pub fn get_conformer_mut(mol: Pin<&mut ROMol>, id: i32) -> Result>; + pub fn conformer_id(conf: &Conformer) -> Result; + pub fn conformer_is_3d(conf: &Conformer) -> Result; + pub fn conformer_num_atoms(conf: &Conformer) -> Result; + pub fn conformer_position(conf: &Conformer, idx: u32) -> Result; + pub fn conformer_set_position( + conf: Pin<&mut Conformer>, + idx: u32, + pos: Point3D, + ) -> Result<()>; + } +} diff --git a/rdkit-sys/src/bridge/descriptors.rs b/rdkit-sys/src/bridge/descriptors.rs index ec0b2c1..5a36ed1 100644 --- a/rdkit-sys/src/bridge/descriptors.rs +++ b/rdkit-sys/src/bridge/descriptors.rs @@ -7,13 +7,13 @@ pub mod ffi { pub type ROMol = crate::ro_mol_ffi::ROMol; pub type Properties; - pub fn new_properties() -> SharedPtr; + pub fn new_properties() -> Result>; pub fn get_property_names( - properties: &SharedPtr, - ) -> UniquePtr>; + properties: &Properties, + ) -> Result>>; pub fn compute_properties( - properties: &SharedPtr, - mol: &SharedPtr, - ) -> UniquePtr>; + properties: &Properties, + mol: &ROMol, + ) -> Result>>; } } diff --git a/rdkit-sys/src/bridge/fingerprint.rs b/rdkit-sys/src/bridge/fingerprint.rs index 44eb48c..e622f23 100644 --- a/rdkit-sys/src/bridge/fingerprint.rs +++ b/rdkit-sys/src/bridge/fingerprint.rs @@ -6,16 +6,33 @@ pub mod ffi { pub type ROMol = crate::ro_mol_ffi::ROMol; pub type ExplicitBitVect; - pub fn rdk_fingerprint_mol(mol: &SharedPtr) -> SharedPtr; - pub fn pattern_fingerprint_mol(mol: &SharedPtr) -> SharedPtr; - pub fn morgan_fingerprint_mol(mol: &SharedPtr) -> SharedPtr; + pub fn rdk_fingerprint_mol(mol: &ROMol) -> Result>; + pub fn pattern_fingerprint_mol(mol: &ROMol) -> Result>; + pub fn morgan_fingerprint_mol(mol: &ROMol) -> Result>; pub fn copy_explicit_bit_vect( - fingerprint: &SharedPtr, - ) -> SharedPtr; + fingerprint: &ExplicitBitVect, + ) -> Result>; pub fn explicit_bit_vect_to_u64_vec( - bitvect: &SharedPtr, - ) -> UniquePtr>; + bitvect: &ExplicitBitVect, + ) -> Result>>; + pub fn explicit_bit_vect_num_bits(bits: &ExplicitBitVect) -> Result; + pub fn morgan_fingerprint_mol_with_params( + mol: &ROMol, + radius: u32, + n_bits: u32, + ) -> Result>; + pub fn rdk_fingerprint_mol_with_params( + mol: &ROMol, + min_path: u32, + max_path: u32, + n_bits: u32, + ) -> Result>; + pub fn pattern_fingerprint_mol_with_params( + mol: &ROMol, + n_bits: u32, + ) -> Result>; + pub fn maccs_fingerprint_mol(mol: &ROMol) -> Result>; } } diff --git a/rdkit-sys/src/bridge/mod.rs b/rdkit-sys/src/bridge/mod.rs index 1593316..adc5e72 100644 --- a/rdkit-sys/src/bridge/mod.rs +++ b/rdkit-sys/src/bridge/mod.rs @@ -24,3 +24,8 @@ pub use scaffold_network::ffi as scaffold_network_ffi; mod substruct_match; pub use substruct_match::ffi as substruct_match_ffi; + +mod bond; +pub use bond::ffi as bond_ffi; +mod conformer; +pub use conformer::ffi as conformer_ffi; diff --git a/rdkit-sys/src/bridge/mol_ops.rs b/rdkit-sys/src/bridge/mol_ops.rs index e7e89ce..2581aa3 100644 --- a/rdkit-sys/src/bridge/mol_ops.rs +++ b/rdkit-sys/src/bridge/mol_ops.rs @@ -8,80 +8,107 @@ pub mod ffi { pub type RWMol = crate::rw_mol_ffi::RWMol; pub type RemoveHsParameters; - pub fn new_remove_hs_parameters() -> SharedPtr; + pub fn new_remove_hs_parameters() -> Result>; - pub fn get_remove_degree_zero(params: &SharedPtr) -> bool; - pub fn set_remove_degree_zero(params: &mut SharedPtr, what: bool); + pub fn get_remove_degree_zero(params: &RemoveHsParameters) -> Result; + pub fn set_remove_degree_zero( + params: Pin<&mut RemoveHsParameters>, + what: bool, + ) -> Result<()>; - pub fn get_remove_higher_degrees(params: &SharedPtr) -> bool; - pub fn set_remove_higher_degrees(params: &mut SharedPtr, what: bool); + pub fn get_remove_higher_degrees(params: &RemoveHsParameters) -> Result; + pub fn set_remove_higher_degrees( + params: Pin<&mut RemoveHsParameters>, + what: bool, + ) -> Result<()>; - pub fn get_remove_only_h_neighbors(params: &SharedPtr) -> bool; - pub fn set_remove_only_h_neighbors(params: &mut SharedPtr, what: bool); + pub fn get_remove_only_h_neighbors(params: &RemoveHsParameters) -> Result; + pub fn set_remove_only_h_neighbors( + params: Pin<&mut RemoveHsParameters>, + what: bool, + ) -> Result<()>; - pub fn get_remove_isotopes(params: &SharedPtr) -> bool; - pub fn set_remove_isotopes(params: &mut SharedPtr, what: bool); + pub fn get_remove_isotopes(params: &RemoveHsParameters) -> Result; + pub fn set_remove_isotopes(params: Pin<&mut RemoveHsParameters>, what: bool) -> Result<()>; - pub fn get_remove_and_track_isotopes(params: &SharedPtr) -> bool; + pub fn get_remove_and_track_isotopes(params: &RemoveHsParameters) -> Result; pub fn set_remove_and_track_isotopes( - params: &mut SharedPtr, + params: Pin<&mut RemoveHsParameters>, what: bool, - ); + ) -> Result<()>; - pub fn get_remove_dummy_neighbors(params: &SharedPtr) -> bool; - pub fn set_remove_dummy_neighbors(params: &mut SharedPtr, what: bool); + pub fn get_remove_dummy_neighbors(params: &RemoveHsParameters) -> Result; + pub fn set_remove_dummy_neighbors( + params: Pin<&mut RemoveHsParameters>, + what: bool, + ) -> Result<()>; - pub fn get_remove_defining_bond_stereo(params: &SharedPtr) -> bool; + pub fn get_remove_defining_bond_stereo(params: &RemoveHsParameters) -> Result; pub fn set_remove_defining_bond_stereo( - params: &mut SharedPtr, + params: Pin<&mut RemoveHsParameters>, what: bool, - ); + ) -> Result<()>; - pub fn get_remove_with_wedged_bond(params: &SharedPtr) -> bool; - pub fn set_remove_with_wedged_bond(params: &mut SharedPtr, what: bool); + pub fn get_remove_with_wedged_bond(params: &RemoveHsParameters) -> Result; + pub fn set_remove_with_wedged_bond( + params: Pin<&mut RemoveHsParameters>, + what: bool, + ) -> Result<()>; - pub fn get_remove_with_query(params: &SharedPtr) -> bool; - pub fn set_remove_with_query(params: &mut SharedPtr, what: bool); + pub fn get_remove_with_query(params: &RemoveHsParameters) -> Result; + pub fn set_remove_with_query( + params: Pin<&mut RemoveHsParameters>, + what: bool, + ) -> Result<()>; - pub fn get_remove_mapped(params: &SharedPtr) -> bool; - pub fn set_remove_mapped(params: &mut SharedPtr, what: bool); + pub fn get_remove_mapped(params: &RemoveHsParameters) -> Result; + pub fn set_remove_mapped(params: Pin<&mut RemoveHsParameters>, what: bool) -> Result<()>; - pub fn get_remove_in_s_groups(params: &SharedPtr) -> bool; - pub fn set_remove_in_s_groups(params: &mut SharedPtr, what: bool); + pub fn get_remove_in_s_groups(params: &RemoveHsParameters) -> Result; + pub fn set_remove_in_s_groups( + params: Pin<&mut RemoveHsParameters>, + what: bool, + ) -> Result<()>; - pub fn get_show_warnings(params: &SharedPtr) -> bool; - pub fn set_show_warnings(params: &mut SharedPtr, what: bool); + pub fn get_show_warnings(params: &RemoveHsParameters) -> Result; + pub fn set_show_warnings(params: Pin<&mut RemoveHsParameters>, what: bool) -> Result<()>; - pub fn get_remove_nonimplicit(params: &SharedPtr) -> bool; - pub fn set_remove_nonimplicit(params: &mut SharedPtr, what: bool); + pub fn get_remove_nonimplicit(params: &RemoveHsParameters) -> Result; + pub fn set_remove_nonimplicit( + params: Pin<&mut RemoveHsParameters>, + what: bool, + ) -> Result<()>; - pub fn get_update_explicit_count(params: &SharedPtr) -> bool; - pub fn set_update_explicit_count(params: &mut SharedPtr, what: bool); + pub fn get_update_explicit_count(params: &RemoveHsParameters) -> Result; + pub fn set_update_explicit_count( + params: Pin<&mut RemoveHsParameters>, + what: bool, + ) -> Result<()>; - pub fn get_remove_hydrides(params: &SharedPtr) -> bool; - pub fn set_remove_hydrides(params: &mut SharedPtr, what: bool); + pub fn get_remove_hydrides(params: &RemoveHsParameters) -> Result; + pub fn set_remove_hydrides(params: Pin<&mut RemoveHsParameters>, what: bool) -> Result<()>; - pub fn get_remove_nontetrahedral_neighbors(params: &SharedPtr) -> bool; + pub fn get_remove_nontetrahedral_neighbors(params: &RemoveHsParameters) -> Result; pub fn set_remove_nontetrahedral_neighbors( - params: &mut SharedPtr, + params: Pin<&mut RemoveHsParameters>, what: bool, - ); + ) -> Result<()>; pub fn remove_hs_parameters( - mol: &SharedPtr, - params: &SharedPtr, + mol: &ROMol, + params: &RemoveHsParameters, sanitize: bool, - ) -> SharedPtr; + ) -> Result>; pub fn add_hs( - mol: &SharedPtr, + mol: &ROMol, explicit_only: bool, add_coords: bool, add_residue_info: bool, - ) -> SharedPtr; + ) -> Result>; - pub fn romol_set_hybridization(mol: &mut SharedPtr); + pub fn romol_set_hybridization(mol: Pin<&mut ROMol>) -> Result<()>; - pub fn clean_up(rw_mol: &mut SharedPtr); + pub fn clean_up(rw_mol: Pin<&mut RWMol>) -> Result<()>; } } diff --git a/rdkit-sys/src/bridge/mol_standardize.rs b/rdkit-sys/src/bridge/mol_standardize.rs index b425a52..5d75c6f 100644 --- a/rdkit-sys/src/bridge/mol_standardize.rs +++ b/rdkit-sys/src/bridge/mol_standardize.rs @@ -12,41 +12,41 @@ pub mod ffi { pub type CleanupParameters; pub type Uncharger; - pub fn tautomer_enumerator() -> SharedPtr; + pub fn tautomer_enumerator() -> Result>; pub fn tautomer_enumerate( - tautomer_enumerator: &SharedPtr, - mol: &SharedPtr, - ) -> SharedPtr; + tautomer_enumerator: &TautomerEnumerator, + mol: &ROMol, + ) -> Result>; pub fn tautomer_enumerator_result_tautomers_size( - enumerator_result: &SharedPtr, - ) -> i32; + enumerator_result: &TautomerEnumeratorResult, + ) -> Result; pub fn tautomer_enumerator_result_tautomers_at( - enumerator_result: &SharedPtr, + enumerator_result: &TautomerEnumeratorResult, at: usize, - ) -> SharedPtr; + ) -> Result>; pub fn tautomer_enumerator_canonicalize( - tautomer_enumerator: &SharedPtr, - mol: &SharedPtr, - ) -> Result>; + tautomer_enumerator: &TautomerEnumerator, + mol: &ROMol, + ) -> Result>; - pub fn default_cleanup_parameters() -> SharedPtr; + pub fn default_cleanup_parameters() -> Result>; - pub fn new_uncharger(canonical: bool) -> SharedPtr; + pub fn new_uncharger(canonical: bool) -> Result>; pub fn uncharger_uncharge( - uncharger: &SharedPtr, - mol: &SharedPtr, - ) -> SharedPtr; + uncharger: Pin<&mut Uncharger>, + mol: &ROMol, + ) -> Result>; pub fn fragment_parent( - rw_mol: &SharedPtr, - cleanup_params: &SharedPtr, + rw_mol: &RWMol, + cleanup_params: &CleanupParameters, skip_standardize: bool, - ) -> SharedPtr; + ) -> Result>; pub fn normalize( - rw_mol: &SharedPtr, - cleanup_params: &SharedPtr, - ) -> SharedPtr; + rw_mol: &RWMol, + cleanup_params: &CleanupParameters, + ) -> Result>; } } diff --git a/rdkit-sys/src/bridge/periodic_table.rs b/rdkit-sys/src/bridge/periodic_table.rs index b08b1fb..56ccab7 100644 --- a/rdkit-sys/src/bridge/periodic_table.rs +++ b/rdkit-sys/src/bridge/periodic_table.rs @@ -9,50 +9,68 @@ pub mod ffi { unsafe extern "C++" { type PeriodicTable; include!("wrapper/include/periodic_table.h"); - pub fn get_periodic_table() -> UniquePtr; - pub fn getAtomicWeight(self: &PeriodicTable, atomic_number: u32) -> f64; - pub fn getAtomicNumber(self: &PeriodicTable, atom: &CxxString) -> i32; - pub fn getElementSymbol(atomic_number: u32) -> String; - pub fn getElementName(atomic_number: u32) -> String; - pub fn getRvdw(self: &PeriodicTable, atomic_number: u32) -> f64; - pub fn getRcovalent(self: &PeriodicTable, atomic_number: u32) -> f64; - pub fn getRb0(self: &PeriodicTable, atomic_number: u32) -> f64; - pub fn getDefaultValence(self: &PeriodicTable, atomic_number: u32) -> i32; - fn getValenceList(atomic_number: u32) -> &'static CxxVector; - pub fn getNouterElecs(self: &PeriodicTable, atomic_number: u32) -> i32; - pub fn getMostCommonIsotope(self: &PeriodicTable, atomic_number: u32) -> i32; - pub fn getMostCommonIsotopeMass(self: &PeriodicTable, atom: &CxxString) -> f64; - pub fn getMassForIsotope(self: &PeriodicTable, atomic_number: u32, isotope: u32) -> f64; - pub fn getMaxAtomicNumber(self: &PeriodicTable) -> u32; + pub fn get_periodic_table() -> Result>; + pub fn getAtomicWeight(self: &PeriodicTable, atomic_number: u32) -> Result; + pub fn getAtomicNumber(self: &PeriodicTable, atom: &CxxString) -> Result; + pub fn getElementSymbol(atomic_number: u32) -> Result; + pub fn getElementName(atomic_number: u32) -> Result; + pub fn getRvdw(self: &PeriodicTable, atomic_number: u32) -> Result; + pub fn getRcovalent(self: &PeriodicTable, atomic_number: u32) -> Result; + pub fn getRb0(self: &PeriodicTable, atomic_number: u32) -> Result; + pub fn getDefaultValence(self: &PeriodicTable, atomic_number: u32) -> Result; + fn getValenceList(atomic_number: u32) -> Result>>; + pub fn getNouterElecs(self: &PeriodicTable, atomic_number: u32) -> Result; + pub fn getMostCommonIsotope(self: &PeriodicTable, atomic_number: u32) -> Result; + pub fn getMostCommonIsotopeMass(self: &PeriodicTable, atom: &CxxString) -> Result; + pub fn getMassForIsotope( + self: &PeriodicTable, + atomic_number: u32, + isotope: u32, + ) -> Result; + pub fn periodic_table_max_atomic_number(table: &PeriodicTable) -> Result; pub fn getAbundanceForIsotope( self: &PeriodicTable, atomic_number: u32, isotope: u32, - ) -> f64; + ) -> Result; pub fn moreElectroNegative( self: &PeriodicTable, atomic_number1: u32, atomic_number2: u32, - ) -> bool; - pub fn getRow(self: &PeriodicTable, atomic_number: u32) -> u32; + ) -> Result; + pub fn periodic_table_row(table: &PeriodicTable, atomic_number: u32) -> Result; } } pub trait PeriodicTableOps { - fn getElementSymbol(self, atomic_number: u32) -> String; - fn getElementName(self, atomic_number: u32) -> String; - fn getValenceList(self, atomic_number: u32) -> &'static CxxVector; + fn getElementSymbol(&self, atomic_number: u32) -> Result; + fn getElementName(&self, atomic_number: u32) -> Result; + fn getValenceList( + &self, + atomic_number: u32, + ) -> Result>, cxx::Exception>; } -impl<'a> PeriodicTableOps for UniquePtr { - fn getElementSymbol(self, atomic_number: u32) -> String { +impl PeriodicTableOps for UniquePtr { + fn getElementSymbol(&self, atomic_number: u32) -> Result { ffi::getElementSymbol(atomic_number) } - - fn getElementName(self, atomic_number: u32) -> String { + fn getElementName(&self, atomic_number: u32) -> Result { ffi::getElementName(atomic_number) } - - fn getValenceList(self, atomic_number: u32) -> &'static CxxVector { + fn getValenceList( + &self, + atomic_number: u32, + ) -> Result>, cxx::Exception> { ffi::getValenceList(atomic_number) } } + +impl PeriodicTable { + pub fn getMaxAtomicNumber(&self) -> Result { + ffi::periodic_table_max_atomic_number(self) + } + + pub fn getRow(&self, atomic_number: u32) -> Result { + ffi::periodic_table_row(self, atomic_number) + } +} diff --git a/rdkit-sys/src/bridge/ro_mol.rs b/rdkit-sys/src/bridge/ro_mol.rs index fffa0e7..51e796d 100644 --- a/rdkit-sys/src/bridge/ro_mol.rs +++ b/rdkit-sys/src/bridge/ro_mol.rs @@ -26,64 +26,65 @@ pub mod ffi { pub type MolSanitizeException; pub type MolSanitizeExceptionUniquePtr; // = UniquePtr; - pub fn copy_mol(mol: &SharedPtr) -> SharedPtr; + pub fn copy_mol(mol: &ROMol) -> Result>; - pub fn smiles_to_mol(smi: &CxxString) -> Result>; + pub fn smiles_to_mol(smi: &CxxString) -> Result>; pub fn smiles_to_mol_with_params( smi: &CxxString, - params: &SharedPtr, - ) -> Result>; - pub fn new_smiles_parser_params() -> SharedPtr; + params: &SmilesParserParams, + ) -> Result>; + pub fn new_smiles_parser_params() -> Result>; pub fn smiles_parser_params_set_sanitize( - ptr: &SharedPtr, + ptr: Pin<&mut SmilesParserParams>, sanitize: bool, - ); - pub fn smiles_parser_params_get_sanitize(ptr: &SharedPtr) -> bool; + ) -> Result<()>; + pub fn smiles_parser_params_get_sanitize(ptr: &SmilesParserParams) -> Result; - pub fn mol_to_smiles(mol: &SharedPtr) -> String; + pub fn mol_to_smiles(mol: &ROMol) -> Result; - pub fn mol_to_molblock(mol: &SharedPtr) -> String; + pub fn mol_to_molblock(mol: &ROMol) -> Result; pub fn detect_chemistry_problems( - mol: &SharedPtr, - ) -> UniquePtr>; + mol: &ROMol, + ) -> Result>>; pub fn mol_sanitize_exception_type( mol_sanitize_exception: &MolSanitizeExceptionUniquePtr, - ) -> String; + ) -> Result; pub fn atom_sanitize_exception_get_atom_idx( mol_sanitize_exception: &MolSanitizeExceptionUniquePtr, - ) -> u32; + ) -> Result; - pub fn get_num_atoms(mol: &SharedPtr, onlyExplicit: bool) -> u32; - pub fn get_atom_with_idx(mol: &mut SharedPtr, idx: u32) -> Pin<&mut Atom>; - pub fn get_symbol(atom: Pin<&Atom>) -> String; - pub fn get_is_aromatic(atom: Pin<&Atom>) -> bool; - pub fn get_atomic_num(atom: Pin<&Atom>) -> i32; - pub fn get_formal_charge(atom: Pin<&Atom>) -> i32; - pub fn get_total_num_hs(atom: Pin<&Atom>) -> u32; - pub fn get_total_valence(atom: Pin<&Atom>) -> u32; - pub fn set_formal_charge(atom: Pin<&mut Atom>, what: i32); - pub fn set_num_explicit_hs(atom: Pin<&mut Atom>, what: i32); + pub fn get_num_atoms(mol: &ROMol, onlyExplicit: bool) -> Result; + pub fn get_atom_ref(mol: &ROMol, idx: u32) -> Result<&Atom>; + pub fn get_atom_with_idx(mol: Pin<&mut ROMol>, idx: u32) -> Result>; + pub fn get_symbol(atom: &Atom) -> Result; + pub fn get_is_aromatic(atom: &Atom) -> Result; + pub fn get_atomic_num(atom: &Atom) -> Result; + pub fn get_formal_charge(atom: &Atom) -> Result; + pub fn get_total_num_hs(atom: &Atom) -> Result; + pub fn get_total_valence(atom: &Atom) -> Result; + pub fn set_formal_charge(atom: Pin<&mut Atom>, what: i32) -> Result<()>; + pub fn set_num_explicit_hs(atom: Pin<&mut Atom>, what: i32) -> Result<()>; pub fn atom_update_property_cache(atom: Pin<&mut Atom>, strict: bool) -> Result<()>; - pub fn atom_set_hybridization(atom: Pin<&mut Atom>, what: HybridizationType); - pub fn atom_get_hybridization(atom: Pin<&Atom>) -> HybridizationType; + pub fn atom_set_hybridization(atom: Pin<&mut Atom>, what: i32) -> Result<()>; + pub fn atom_get_hybridization(atom: &Atom) -> Result; - pub fn ro_mol_update_property_cache(atom: &mut SharedPtr, strict: bool); + pub fn ro_mol_update_property_cache(atom: Pin<&mut ROMol>, strict: bool) -> Result<()>; - pub fn set_int_prop(atom: Pin<&mut Atom>, key: &CxxString, value: i32); - pub fn get_int_prop(atom: Pin<&Atom>, key: &CxxString) -> Result; - pub fn set_float_prop(atom: Pin<&mut Atom>, key: &CxxString, value: f64); - pub fn get_float_prop(atom: Pin<&Atom>, key: &CxxString) -> Result; - pub fn set_bool_prop(atom: Pin<&mut Atom>, key: &CxxString, value: bool); - pub fn get_bool_prop(atom: Pin<&Atom>, key: &CxxString) -> Result; - pub fn set_prop(atom: Pin<&mut Atom>, key: &CxxString, value: &CxxString); - pub fn get_prop(atom: Pin<&Atom>, key: &CxxString) -> Result; - pub fn get_num_radical_electrons(atom: Pin<&Atom>) -> u32; + pub fn set_int_prop(atom: Pin<&mut Atom>, key: &CxxString, value: i32) -> Result<()>; + pub fn get_int_prop(atom: &Atom, key: &CxxString) -> Result; + pub fn set_float_prop(atom: Pin<&mut Atom>, key: &CxxString, value: f64) -> Result<()>; + pub fn get_float_prop(atom: &Atom, key: &CxxString) -> Result; + pub fn set_bool_prop(atom: Pin<&mut Atom>, key: &CxxString, value: bool) -> Result<()>; + pub fn get_bool_prop(atom: &Atom, key: &CxxString) -> Result; + pub fn set_prop(atom: Pin<&mut Atom>, key: &CxxString, value: &CxxString) -> Result<()>; + pub fn get_prop(atom: &Atom, key: &CxxString) -> Result; + pub fn get_num_radical_electrons(atom: &Atom) -> Result; //Returns the degree of the atom in the molecule. - pub fn get_degree(atom: Pin<&Atom>) -> u32; + pub fn get_degree(atom: &Atom) -> Result; } } diff --git a/rdkit-sys/src/bridge/rw_mol.rs b/rdkit-sys/src/bridge/rw_mol.rs index 72e4d75..852e896 100644 --- a/rdkit-sys/src/bridge/rw_mol.rs +++ b/rdkit-sys/src/bridge/rw_mol.rs @@ -12,18 +12,32 @@ pub mod ffi { sanitize: bool, remove_hs: bool, strict_parsing: bool, - ) -> SharedPtr; + ) -> Result>; pub fn rw_mol_from_ro_mol( - mol: &SharedPtr, + mol: &ROMol, quick_copy: bool, conf_id: i32, - ) -> SharedPtr; + ) -> Result>; - pub fn rw_mol_from_rw_mol(mol: &SharedPtr) -> SharedPtr; + pub fn rw_mol_from_rw_mol(mol: &RWMol) -> Result>; - pub fn rw_mol_to_ro_mol(mol: SharedPtr) -> SharedPtr; + pub fn rw_mol_to_ro_mol(mol: UniquePtr) -> Result>; - pub fn smarts_to_mol(smarts: &CxxString) -> Result>; + pub fn rw_mol_as_ro_mol(mol: &RWMol) -> &ROMol; + + pub fn smarts_to_mol(smarts: &CxxString) -> Result>; + pub fn new_rw_mol() -> Result>; + pub fn rw_mol_as_ro_mol_mut(mol: Pin<&mut RWMol>) -> Pin<&mut ROMol>; + pub fn rw_mol_add_atom(mol: Pin<&mut RWMol>, atomic_num: u32) -> Result; + pub fn rw_mol_add_bond( + mol: Pin<&mut RWMol>, + begin: u32, + end: u32, + order: i32, + ) -> Result; + pub fn rw_mol_remove_atom(mol: Pin<&mut RWMol>, idx: u32) -> Result<()>; + pub fn rw_mol_remove_bond(mol: Pin<&mut RWMol>, begin: u32, end: u32) -> Result<()>; + pub fn rw_mol_sanitize(mol: Pin<&mut RWMol>) -> Result<()>; } } diff --git a/rdkit-sys/src/bridge/scaffold_network.rs b/rdkit-sys/src/bridge/scaffold_network.rs index 5ba705e..8951ecd 100644 --- a/rdkit-sys/src/bridge/scaffold_network.rs +++ b/rdkit-sys/src/bridge/scaffold_network.rs @@ -1,43 +1,80 @@ #[cxx::bridge(namespace = "RDKit")] pub mod ffi { unsafe extern "C++" { + include!("wrapper/include/ro_mol.h"); include!("wrapper/include/scaffold_network.h"); + pub type ROMol = crate::ro_mol_ffi::ROMol; pub type ScaffoldNetworkParams; - // - // pub fn default_scaffold_network_params() -> SharedPtr; - pub fn default_scaffold_network_params() -> SharedPtr; + pub fn default_scaffold_network_params() -> Result>; pub fn new_scaffold_network_params( bond_breaker_smarts: &Vec, - ) -> SharedPtr; + ) -> Result>; pub fn set_include_generic_scaffolds( - params: &mut SharedPtr, + params: Pin<&mut ScaffoldNetworkParams>, input: bool, - ); + ) -> Result<()>; pub fn include_generic_bond_scaffolds( - params: &mut SharedPtr, + params: Pin<&mut ScaffoldNetworkParams>, input: bool, - ); + ) -> Result<()>; pub fn include_scaffolds_without_attachments( - params: &mut SharedPtr, + params: Pin<&mut ScaffoldNetworkParams>, input: bool, - ); + ) -> Result<()>; pub fn include_scaffolds_with_attachments( - params: &mut SharedPtr, + params: Pin<&mut ScaffoldNetworkParams>, input: bool, - ); - pub fn keep_only_first_fragment(params: &mut SharedPtr, input: bool); - pub fn prune_before_fragmenting(params: &mut SharedPtr, input: bool); - pub fn flatten_isotopes(params: &mut SharedPtr, input: bool); - pub fn flatten_chirality(params: &mut SharedPtr, input: bool); - pub fn flatten_keep_largest(params: &mut SharedPtr, input: bool); - pub fn collect_mol_counts(params: &mut SharedPtr, input: bool); + ) -> Result<()>; + pub fn keep_only_first_fragment( + params: Pin<&mut ScaffoldNetworkParams>, + input: bool, + ) -> Result<()>; + pub fn prune_before_fragmenting( + params: Pin<&mut ScaffoldNetworkParams>, + input: bool, + ) -> Result<()>; + pub fn flatten_isotopes(params: Pin<&mut ScaffoldNetworkParams>, input: bool) + -> Result<()>; + pub fn flatten_chirality( + params: Pin<&mut ScaffoldNetworkParams>, + input: bool, + ) -> Result<()>; + pub fn flatten_keep_largest( + params: Pin<&mut ScaffoldNetworkParams>, + input: bool, + ) -> Result<()>; + pub fn collect_mol_counts( + params: Pin<&mut ScaffoldNetworkParams>, + input: bool, + ) -> Result<()>; pub type ScaffoldNetworkClass; - pub fn default_scaffold_network() -> SharedPtr; + pub fn default_scaffold_network() -> Result>; + + pub fn create_scaffold_network( + mol: &ROMol, + params: &ScaffoldNetworkParams, + ) -> Result>; + + pub fn update_scaffold_network( + network: Pin<&mut ScaffoldNetworkClass>, + mol: &ROMol, + params: &ScaffoldNetworkParams, + ) -> Result<()>; + pub fn scaffold_network_nodes(network: &ScaffoldNetworkClass) -> Result>; + pub fn scaffold_network_counts(network: &ScaffoldNetworkClass) -> Result>; + pub fn scaffold_network_mol_counts(network: &ScaffoldNetworkClass) -> Result>; + pub fn scaffold_network_edge_begin_indices( + network: &ScaffoldNetworkClass, + ) -> Result>; + pub fn scaffold_network_edge_end_indices( + network: &ScaffoldNetworkClass, + ) -> Result>; + pub fn scaffold_network_edge_types(network: &ScaffoldNetworkClass) -> Result>; } } diff --git a/rdkit-sys/src/bridge/substruct_match.rs b/rdkit-sys/src/bridge/substruct_match.rs index f5b801a..dd91b9a 100644 --- a/rdkit-sys/src/bridge/substruct_match.rs +++ b/rdkit-sys/src/bridge/substruct_match.rs @@ -10,49 +10,55 @@ pub mod ffi { pub type MatchVectType; pub fn substruct_match( - mol: &SharedPtr, - mol_query: &SharedPtr, - params: &SharedPtr, - ) -> UniquePtr>; + mol: &ROMol, + mol_query: &ROMol, + params: &SubstructMatchParameters, + ) -> Result>>; - pub fn new_substruct_match_parameters() -> SharedPtr; - pub fn get_use_chirality(params: &SharedPtr) -> bool; - pub fn get_use_enhanced_stereo(params: &SharedPtr) -> bool; - pub fn get_aromatic_matches_conjugated( - params: &SharedPtr, - ) -> bool; - pub fn get_use_query_query_matches(params: &SharedPtr) -> bool; - pub fn get_use_generic_matchers(params: &SharedPtr) -> bool; - pub fn get_recursion_possible(params: &SharedPtr) -> bool; - pub fn get_uniquify(params: &SharedPtr) -> bool; + pub fn new_substruct_match_parameters() -> Result>; + pub fn get_use_chirality(params: &SubstructMatchParameters) -> Result; + pub fn get_use_enhanced_stereo(params: &SubstructMatchParameters) -> Result; + pub fn get_aromatic_matches_conjugated(params: &SubstructMatchParameters) -> Result; + pub fn get_use_query_query_matches(params: &SubstructMatchParameters) -> Result; + pub fn get_use_generic_matchers(params: &SubstructMatchParameters) -> Result; + pub fn get_recursion_possible(params: &SubstructMatchParameters) -> Result; + pub fn get_uniquify(params: &SubstructMatchParameters) -> Result; - pub fn set_use_chirality(params: &mut SharedPtr, what: bool); + pub fn set_use_chirality( + params: Pin<&mut SubstructMatchParameters>, + what: bool, + ) -> Result<()>; pub fn set_use_enhanced_stereo( - params: &mut SharedPtr, + params: Pin<&mut SubstructMatchParameters>, what: bool, - ); + ) -> Result<()>; pub fn set_aromatic_matches_conjugated( - params: &mut SharedPtr, + params: Pin<&mut SubstructMatchParameters>, what: bool, - ); + ) -> Result<()>; pub fn set_use_query_query_matches( - params: &mut SharedPtr, + params: Pin<&mut SubstructMatchParameters>, what: bool, - ); + ) -> Result<()>; pub fn set_use_generic_matchers( - params: &mut SharedPtr, + params: Pin<&mut SubstructMatchParameters>, + what: bool, + ) -> Result<()>; + pub fn set_recursion_possible( + params: Pin<&mut SubstructMatchParameters>, what: bool, - ); - pub fn set_recursion_possible(params: &mut SharedPtr, what: bool); - pub fn set_uniquify(params: &mut SharedPtr, what: bool); + ) -> Result<()>; + pub fn set_uniquify(params: Pin<&mut SubstructMatchParameters>, what: bool) -> Result<()>; pub fn substruct_matchvect_type_to_vec_substruct_match_item( matchvect: &MatchVectType, - ) -> UniquePtr>; + ) -> Result>>; pub fn substruct_match_item_query_atom_idx( substruct_match_item: &SubstructMatchItem, - ) -> i32; - pub fn substruct_match_item_mol_atom_idx(substruct_match_item: &SubstructMatchItem) -> i32; + ) -> Result; + pub fn substruct_match_item_mol_atom_idx( + substruct_match_item: &SubstructMatchItem, + ) -> Result; } } diff --git a/rdkit-sys/src/lib.rs b/rdkit-sys/src/lib.rs index e31b98d..57a455c 100644 --- a/rdkit-sys/src/lib.rs +++ b/rdkit-sys/src/lib.rs @@ -1,16 +1,2 @@ -//! rdkit-sys is a direct, one-to-one Rust binding against the RDKit C++ API -//! -//! Rust cannot represent C++ concepts like classes, subclasses, and structs, -//! nor can Rust perform moves or copies. Hence, all data from the RDKit C++ API -//! must be moved behind a "smart pointer" which will take care of freeing -//! memory after being dropped, you will see this is pervasive as -//! a `SharedPtr` on the Rust side or `std::shared_ptr` on the C++ side. -//! -//! It is highly recommend you read through the [RDKit C++ API documentation](https://www.rdkit.org/docs/cppapi/index.html) to learn more -//! about what exactly is possible with RDKit. -//! -//! If you just want high level access to SMILES parsing and various clean up -//! operations, please refer to the high level accompanying crate [rdkit](https://www.crates.io/crate/rdkit). - mod bridge; pub use bridge::*; diff --git a/rdkit-sys/tests/test_atoms.rs b/rdkit-sys/tests/test_atoms.rs index f5d9d5c..6030de7 100644 --- a/rdkit-sys/tests/test_atoms.rs +++ b/rdkit-sys/tests/test_atoms.rs @@ -3,15 +3,18 @@ fn test_atoms() { cxx::let_cxx_string!(smiles = "c1ccccc1CCCCCCCC"); let mut romol = rdkit_sys::ro_mol_ffi::smiles_to_mol(&smiles).unwrap(); - let num_atoms = rdkit_sys::ro_mol_ffi::get_num_atoms(&romol, true); + let num_atoms = + rdkit_sys::ro_mol_ffi::get_num_atoms(&romol, true).expect("RDKit operation failed"); assert_eq!(num_atoms, 14); let atoms = (0..num_atoms) .into_iter() .map(|idx| { - let atom = rdkit_sys::ro_mol_ffi::get_atom_with_idx(&mut romol, idx); - rdkit_sys::ro_mol_ffi::get_symbol(atom.as_ref()) + let atom = rdkit_sys::ro_mol_ffi::get_atom_with_idx(romol.pin_mut(), idx) + .expect("RDKit operation failed"); + rdkit_sys::ro_mol_ffi::get_symbol(atom.as_ref().get_ref()) + .expect("RDKit operation failed") }) .collect::>(); @@ -20,9 +23,11 @@ fn test_atoms() { &["C", "C", "C", "C", "C", "C", "C", "C", "C", "C", "C", "C", "C", "C"] ); - let mut atom = rdkit_sys::ro_mol_ffi::get_atom_with_idx(&mut romol, 2); + let mut atom = rdkit_sys::ro_mol_ffi::get_atom_with_idx(romol.pin_mut(), 2) + .expect("RDKit operation failed"); rdkit_sys::ro_mol_ffi::atom_set_hybridization( atom.as_mut(), - rdkit_sys::ro_mol_ffi::HybridizationType::SP3, - ); + rdkit_sys::ro_mol_ffi::HybridizationType::SP3.repr, + ) + .expect("RDKit operation failed"); } diff --git a/rdkit-sys/tests/test_descriptors.rs b/rdkit-sys/tests/test_descriptors.rs index 14fe8e8..1106be8 100644 --- a/rdkit-sys/tests/test_descriptors.rs +++ b/rdkit-sys/tests/test_descriptors.rs @@ -5,18 +5,17 @@ fn test_descriptors() { let_cxx_string!(smiles = "c1ccccc1C(=O)NC"); let mol = rdkit_sys::ro_mol_ffi::smiles_to_mol(&smiles).unwrap(); - let properties = rdkit_sys::descriptors_ffi::new_properties(); + let properties = rdkit_sys::descriptors_ffi::new_properties().expect("RDKit operation failed"); - let names = rdkit_sys::descriptors_ffi::get_property_names(&properties); + let names = rdkit_sys::descriptors_ffi::get_property_names(&properties) + .expect("RDKit operation failed"); let names = names .into_iter() .map(|stringy| stringy.to_string()) .collect::>(); - let computed = rdkit_sys::descriptors_ffi::compute_properties(&properties, &mol); - let computed = computed - .into_iter() - .map(|floaty| *floaty) - .collect::>(); + let computed = rdkit_sys::descriptors_ffi::compute_properties(&properties, &mol) + .expect("RDKit operation failed"); + let computed = computed.into_iter().copied().collect::>(); let expected_names = vec![ "exactmw", diff --git a/rdkit-sys/tests/test_fingerprint.rs b/rdkit-sys/tests/test_fingerprint.rs index 2f07d90..56fa704 100644 --- a/rdkit-sys/tests/test_fingerprint.rs +++ b/rdkit-sys/tests/test_fingerprint.rs @@ -3,8 +3,10 @@ fn test_fingerprint_to_vec() { cxx::let_cxx_string!(smiles = "c1ccccc1CCCCCCCC"); let mol = rdkit_sys::ro_mol_ffi::smiles_to_mol(&smiles).unwrap(); - let fingerprint = rdkit_sys::fingerprint_ffi::rdk_fingerprint_mol(&mol); - let bytes = rdkit_sys::fingerprint_ffi::explicit_bit_vect_to_u64_vec(&fingerprint); - let bytes: Vec = bytes.into_iter().map(|x| *x).collect(); + let fingerprint = + rdkit_sys::fingerprint_ffi::rdk_fingerprint_mol(&mol).expect("RDKit operation failed"); + let bytes = rdkit_sys::fingerprint_ffi::explicit_bit_vect_to_u64_vec(&fingerprint) + .expect("RDKit operation failed"); + let bytes: Vec = bytes.into_iter().copied().collect(); assert_eq!(bytes.len(), 32); } diff --git a/rdkit-sys/tests/test_mol_ops.rs b/rdkit-sys/tests/test_mol_ops.rs index 8b2b4df..37cde03 100644 --- a/rdkit-sys/tests/test_mol_ops.rs +++ b/rdkit-sys/tests/test_mol_ops.rs @@ -5,12 +5,13 @@ fn test_mol_ops_substruct_match_as_bool() { cxx::let_cxx_string!(smiles = "c1ccccc1CCCCCCCC"); let mol = rdkit_sys::ro_mol_ffi::smiles_to_mol(&smiles).unwrap(); - let params = new_remove_hs_parameters(); + let params = new_remove_hs_parameters().expect("RDKit operation failed"); - let mut new_mol = remove_hs_parameters(&mol, ¶ms, true); - let new_smiles = rdkit_sys::ro_mol_ffi::mol_to_smiles(&new_mol); + let mut new_mol = remove_hs_parameters(&mol, ¶ms, true).expect("RDKit operation failed"); + let new_smiles = + rdkit_sys::ro_mol_ffi::mol_to_smiles(&new_mol).expect("RDKit operation failed"); - romol_set_hybridization(&mut new_mol); + romol_set_hybridization(new_mol.pin_mut()).expect("RDKit operation failed"); assert_eq!(new_smiles, "CCCCCCCCc1ccccc1"); } @@ -19,9 +20,11 @@ fn test_mol_ops_substruct_match_as_bool() { fn test_mol_ops_cleanup() { cxx::let_cxx_string!(smiles = "[H]C([H])([H])([H])"); let ro_mol = rdkit_sys::ro_mol_ffi::smiles_to_mol(&smiles).unwrap(); - let mut rw_mol = rdkit_sys::rw_mol_ffi::rw_mol_from_ro_mol(&ro_mol, true, 0); - clean_up(&mut rw_mol); - let new_ro_mol = rdkit_sys::rw_mol_ffi::rw_mol_to_ro_mol(rw_mol); // low-cost pointer swap - let smiles = rdkit_sys::ro_mol_ffi::mol_to_smiles(&new_ro_mol); + let mut rw_mol = rdkit_sys::rw_mol_ffi::rw_mol_from_ro_mol(&ro_mol, true, 0) + .expect("RDKit operation failed"); + clean_up(rw_mol.pin_mut()).expect("RDKit operation failed"); + let new_ro_mol = + rdkit_sys::rw_mol_ffi::rw_mol_to_ro_mol(rw_mol).expect("RDKit operation failed"); + let smiles = rdkit_sys::ro_mol_ffi::mol_to_smiles(&new_ro_mol).expect("RDKit operation failed"); assert_eq!(smiles, "C"); } diff --git a/rdkit-sys/tests/test_mol_standardize.rs b/rdkit-sys/tests/test_mol_standardize.rs index cd02201..a5ccfe3 100644 --- a/rdkit-sys/tests/test_mol_standardize.rs +++ b/rdkit-sys/tests/test_mol_standardize.rs @@ -4,25 +4,32 @@ use cxx::let_cxx_string; fn test_tautomer_enumerator() { let_cxx_string!(smiles = "c1ccccc1C(=O)NC"); let mol = rdkit_sys::ro_mol_ffi::smiles_to_mol(&smiles).unwrap(); - let tautomer_enumerator = rdkit_sys::mol_standardize_ffi::tautomer_enumerator(); + let tautomer_enumerator = + rdkit_sys::mol_standardize_ffi::tautomer_enumerator().expect("RDKit operation failed"); let tautomer_enumerator_result = - rdkit_sys::mol_standardize_ffi::tautomer_enumerate(&tautomer_enumerator, &mol); + rdkit_sys::mol_standardize_ffi::tautomer_enumerate(&tautomer_enumerator, &mol) + .expect("RDKit operation failed"); let size = rdkit_sys::mol_standardize_ffi::tautomer_enumerator_result_tautomers_size( &tautomer_enumerator_result, - ); + ) + .expect("RDKit operation failed"); assert_eq!(size, 2); let first = rdkit_sys::mol_standardize_ffi::tautomer_enumerator_result_tautomers_at( &tautomer_enumerator_result, 0, - ); - let first_smiles = rdkit_sys::ro_mol_ffi::mol_to_smiles(&first); + ) + .expect("RDKit operation failed"); + let first_smiles = + rdkit_sys::ro_mol_ffi::mol_to_smiles(&first).expect("RDKit operation failed"); assert_eq!("CN=C(O)c1ccccc1", first_smiles); let second = rdkit_sys::mol_standardize_ffi::tautomer_enumerator_result_tautomers_at( &tautomer_enumerator_result, 1, - ); - let second_smiles = rdkit_sys::ro_mol_ffi::mol_to_smiles(&second); + ) + .expect("RDKit operation failed"); + let second_smiles = + rdkit_sys::ro_mol_ffi::mol_to_smiles(&second).expect("RDKit operation failed"); assert_eq!("CNC(=O)c1ccccc1", second_smiles); } diff --git a/rdkit-sys/tests/test_periodic_table.rs b/rdkit-sys/tests/test_periodic_table.rs index 22c4378..eb6edcb 100644 --- a/rdkit-sys/tests/test_periodic_table.rs +++ b/rdkit-sys/tests/test_periodic_table.rs @@ -6,121 +6,166 @@ use rdkit_sys::PeriodicTableOps; #[test] fn test_get_valence_list() { - let periodic_table = rdkit_sys::periodic_table_ffi::get_periodic_table(); - let list = periodic_table.getValenceList(6); + let periodic_table = + rdkit_sys::periodic_table_ffi::get_periodic_table().expect("RDKit operation failed"); + let list = periodic_table + .getValenceList(6) + .expect("RDKit operation failed"); assert_eq!(list.as_slice(), &[4]); } #[test] fn test_get_monoisotopic_mass() { let_cxx_string!(atom = "C"); - let periodic_table = rdkit_sys::periodic_table_ffi::get_periodic_table(); - let mass = periodic_table.getMostCommonIsotopeMass(&atom); + let periodic_table = + rdkit_sys::periodic_table_ffi::get_periodic_table().expect("RDKit operation failed"); + let mass = periodic_table + .getMostCommonIsotopeMass(&atom) + .expect("RDKit operation failed"); assert_eq!(mass, 12.00); } #[test] fn test_getAtomicWeight() { - let periodic_table = rdkit_sys::periodic_table_ffi::get_periodic_table(); - let weight = periodic_table.getAtomicWeight(6); + let periodic_table = + rdkit_sys::periodic_table_ffi::get_periodic_table().expect("RDKit operation failed"); + let weight = periodic_table + .getAtomicWeight(6) + .expect("RDKit operation failed"); assert_eq!(weight, 12.011); } #[test] fn test_getAtomicNumber() { let_cxx_string!(atom = "C"); - let periodic_table = rdkit_sys::periodic_table_ffi::get_periodic_table(); - let number = periodic_table.getAtomicNumber(&atom); + let periodic_table = + rdkit_sys::periodic_table_ffi::get_periodic_table().expect("RDKit operation failed"); + let number = periodic_table + .getAtomicNumber(&atom) + .expect("RDKit operation failed"); assert_eq!(number, 6); } #[test] fn test_getElementSymbol() { - let periodic_table = rdkit_sys::periodic_table_ffi::get_periodic_table(); - let symbol = periodic_table.getElementSymbol(6); + let periodic_table = + rdkit_sys::periodic_table_ffi::get_periodic_table().expect("RDKit operation failed"); + let symbol = periodic_table + .getElementSymbol(6) + .expect("RDKit operation failed"); assert_eq!(symbol, "C"); } #[test] fn test_getElementName() { - let periodic_table = rdkit_sys::periodic_table_ffi::get_periodic_table(); - let name = periodic_table.getElementName(6); + let periodic_table = + rdkit_sys::periodic_table_ffi::get_periodic_table().expect("RDKit operation failed"); + let name = periodic_table + .getElementName(6) + .expect("RDKit operation failed"); assert_eq!(name, "Carbon"); } #[test] fn test_getRvdw() { - let periodic_table = rdkit_sys::periodic_table_ffi::get_periodic_table(); - let rvdw = periodic_table.getRvdw(6); + let periodic_table = + rdkit_sys::periodic_table_ffi::get_periodic_table().expect("RDKit operation failed"); + let rvdw = periodic_table.getRvdw(6).expect("RDKit operation failed"); assert_eq!(rvdw, 1.7); } #[test] fn test_getRcovalent() { - let periodic_table = rdkit_sys::periodic_table_ffi::get_periodic_table(); - let rcovalent = periodic_table.getRcovalent(6); + let periodic_table = + rdkit_sys::periodic_table_ffi::get_periodic_table().expect("RDKit operation failed"); + let rcovalent = periodic_table + .getRcovalent(6) + .expect("RDKit operation failed"); assert_eq!(rcovalent, 0.76); } #[test] fn test_getRb0() { - let periodic_table = rdkit_sys::periodic_table_ffi::get_periodic_table(); - let rb0 = periodic_table.getRb0(6); + let periodic_table = + rdkit_sys::periodic_table_ffi::get_periodic_table().expect("RDKit operation failed"); + let rb0 = periodic_table.getRb0(6).expect("RDKit operation failed"); assert_eq!(rb0, 0.77); } #[test] fn test_getDefaultValence() { - let periodic_table = rdkit_sys::periodic_table_ffi::get_periodic_table(); - let valence = periodic_table.getDefaultValence(6); + let periodic_table = + rdkit_sys::periodic_table_ffi::get_periodic_table().expect("RDKit operation failed"); + let valence = periodic_table + .getDefaultValence(6) + .expect("RDKit operation failed"); assert_eq!(valence, 4); } #[test] fn test_getNouterElecs() { - let periodic_table = rdkit_sys::periodic_table_ffi::get_periodic_table(); - let nouter = periodic_table.getNouterElecs(6); + let periodic_table = + rdkit_sys::periodic_table_ffi::get_periodic_table().expect("RDKit operation failed"); + let nouter = periodic_table + .getNouterElecs(6) + .expect("RDKit operation failed"); assert_eq!(nouter, 4); } #[test] fn test_getMostCommonIsotope() { - let periodic_table = rdkit_sys::periodic_table_ffi::get_periodic_table(); - let isotope = periodic_table.getMostCommonIsotope(6); + let periodic_table = + rdkit_sys::periodic_table_ffi::get_periodic_table().expect("RDKit operation failed"); + let isotope = periodic_table + .getMostCommonIsotope(6) + .expect("RDKit operation failed"); assert_eq!(isotope, 12); } #[test] fn test_getRow() { - let periodic_table = rdkit_sys::periodic_table_ffi::get_periodic_table(); - let row = periodic_table.getRow(6); + let periodic_table = + rdkit_sys::periodic_table_ffi::get_periodic_table().expect("RDKit operation failed"); + let row = periodic_table.getRow(6).expect("RDKit operation failed"); assert_eq!(row, 2); } #[test] fn test_getMassForIsotope() { - let periodic_table = rdkit_sys::periodic_table_ffi::get_periodic_table(); - let mass = periodic_table.getMassForIsotope(6, 13); + let periodic_table = + rdkit_sys::periodic_table_ffi::get_periodic_table().expect("RDKit operation failed"); + let mass = periodic_table + .getMassForIsotope(6, 13) + .expect("RDKit operation failed"); assert_eq!(mass, 13.00335484); } #[test] fn test_getMaxAtomicNumber() { - let periodic_table = rdkit_sys::periodic_table_ffi::get_periodic_table(); - let max = periodic_table.getMaxAtomicNumber(); + let periodic_table = + rdkit_sys::periodic_table_ffi::get_periodic_table().expect("RDKit operation failed"); + let max = periodic_table + .getMaxAtomicNumber() + .expect("RDKit operation failed"); assert_eq!(max, 118); } #[test] fn test_getAbundanceForIsotope() { - let periodic_table = rdkit_sys::periodic_table_ffi::get_periodic_table(); - let abundance = periodic_table.getAbundanceForIsotope(6, 13); + let periodic_table = + rdkit_sys::periodic_table_ffi::get_periodic_table().expect("RDKit operation failed"); + let abundance = periodic_table + .getAbundanceForIsotope(6, 13) + .expect("RDKit operation failed"); assert_eq!(abundance, 1.07); } #[test] fn test_moreElectroNegative() { - let periodic_table = rdkit_sys::periodic_table_ffi::get_periodic_table(); - let more_electro = periodic_table.moreElectroNegative(6, 7); - assert_eq!(more_electro, false); + let periodic_table = + rdkit_sys::periodic_table_ffi::get_periodic_table().expect("RDKit operation failed"); + let more_electro = periodic_table + .moreElectroNegative(6, 7) + .expect("RDKit operation failed"); + assert!(!more_electro); } diff --git a/rdkit-sys/tests/test_ro_mol.rs b/rdkit-sys/tests/test_ro_mol.rs index 50b6bc8..f8b6c1d 100644 --- a/rdkit-sys/tests/test_ro_mol.rs +++ b/rdkit-sys/tests/test_ro_mol.rs @@ -4,7 +4,8 @@ fn test_ro_mol() { let mut romol = rdkit_sys::ro_mol_ffi::smiles_to_mol(&smiles).unwrap(); assert!(!romol.is_null()); - rdkit_sys::ro_mol_ffi::ro_mol_update_property_cache(&mut romol, true); + rdkit_sys::ro_mol_ffi::ro_mol_update_property_cache(romol.pin_mut(), true) + .expect("RDKit operation failed"); } #[test] @@ -26,39 +27,50 @@ fn bad_mol_test() { fn parse_without_sanitize_test() { cxx::let_cxx_string!(smiles = "N#[N]c1ccc(cc1)N(C)CN(C)(C)(C)"); - let params = rdkit_sys::ro_mol_ffi::new_smiles_parser_params(); + let mut params = + rdkit_sys::ro_mol_ffi::new_smiles_parser_params().expect("RDKit operation failed"); - rdkit_sys::ro_mol_ffi::smiles_parser_params_set_sanitize(¶ms, true); + rdkit_sys::ro_mol_ffi::smiles_parser_params_set_sanitize(params.pin_mut(), true) + .expect("RDKit operation failed"); let romol = rdkit_sys::ro_mol_ffi::smiles_to_mol_with_params(&smiles, ¶ms); assert!(romol.is_err()); - rdkit_sys::ro_mol_ffi::smiles_parser_params_set_sanitize(¶ms, false); + rdkit_sys::ro_mol_ffi::smiles_parser_params_set_sanitize(params.pin_mut(), false) + .expect("RDKit operation failed"); let romol = rdkit_sys::ro_mol_ffi::smiles_to_mol_with_params(&smiles, ¶ms); assert!(romol.is_ok()); let mut romol = romol.unwrap(); - let problems = rdkit_sys::ro_mol_ffi::detect_chemistry_problems(&romol); + let problems = + rdkit_sys::ro_mol_ffi::detect_chemistry_problems(&romol).expect("RDKit operation failed"); assert_eq!(problems.len(), 2); let types = problems .iter() - .map(|p| rdkit_sys::ro_mol_ffi::mol_sanitize_exception_type(p)) + .map(|p| { + rdkit_sys::ro_mol_ffi::mol_sanitize_exception_type(p).expect("RDKit operation failed") + }) .collect::>(); assert_eq!(&types, &["AtomValenceException", "AtomValenceException"]); let atom_idxs = problems .iter() - .map(|p| rdkit_sys::ro_mol_ffi::atom_sanitize_exception_get_atom_idx(p)) + .map(|p| { + rdkit_sys::ro_mol_ffi::atom_sanitize_exception_get_atom_idx(p) + .expect("RDKit operation failed") + }) .collect::>(); assert_eq!(&atom_idxs, &[1, 11]); let atoms = atom_idxs .into_iter() .map(|idx| { - let atom = rdkit_sys::ro_mol_ffi::get_atom_with_idx(&mut romol, idx); - rdkit_sys::ro_mol_ffi::get_symbol(atom.as_ref()) + let atom = rdkit_sys::ro_mol_ffi::get_atom_with_idx(romol.pin_mut(), idx) + .expect("RDKit operation failed"); + rdkit_sys::ro_mol_ffi::get_symbol(atom.as_ref().get_ref()) + .expect("RDKit operation failed") }) .collect::>(); assert_eq!(atoms, &["N", "N"]); @@ -68,7 +80,7 @@ fn parse_without_sanitize_test() { fn mol_to_molblock_test() { cxx::let_cxx_string!(smiles = "CC"); let romol = rdkit_sys::ro_mol_ffi::smiles_to_mol(&smiles).unwrap(); - let molblock = rdkit_sys::ro_mol_ffi::mol_to_molblock(&romol); + let molblock = rdkit_sys::ro_mol_ffi::mol_to_molblock(&romol).expect("RDKit operation failed"); assert_eq!(molblock, "\n RDKit 2D\n\n 2 1 0 0 0 0 0 0 0 0999 V2000\n 0.0000 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n 1.2990 0.7500 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n 1 2 1 0\nM END\n"); } @@ -77,15 +89,17 @@ fn set_and_get_bool_property_test() { cxx::let_cxx_string!(smiles = "CC"); cxx::let_cxx_string!(key = "foo"); let mut romol = rdkit_sys::ro_mol_ffi::smiles_to_mol(&smiles).unwrap(); - let atom = rdkit_sys::ro_mol_ffi::get_atom_with_idx(&mut romol, 0); - rdkit_sys::ro_mol_ffi::set_bool_prop(atom, &key, true); + let atom = rdkit_sys::ro_mol_ffi::get_atom_with_idx(romol.pin_mut(), 0) + .expect("RDKit operation failed"); + rdkit_sys::ro_mol_ffi::set_bool_prop(atom, &key, true).expect("RDKit operation failed"); // now we create an other variable that is the same atom. // if it works, it should - let atom_2 = rdkit_sys::ro_mol_ffi::get_atom_with_idx(&mut romol, 0); - let value = rdkit_sys::ro_mol_ffi::get_bool_prop(atom_2.as_ref(), &key); + let atom_2 = rdkit_sys::ro_mol_ffi::get_atom_with_idx(romol.pin_mut(), 0) + .expect("RDKit operation failed"); + let value = rdkit_sys::ro_mol_ffi::get_bool_prop(atom_2.as_ref().get_ref(), &key); assert!(value.is_ok()); - assert_eq!(value.unwrap(), true); + assert!(value.unwrap()); } #[test] @@ -93,20 +107,23 @@ fn set_and_get_int_property_test() { cxx::let_cxx_string!(smiles = "CC"); cxx::let_cxx_string!(key = "foo"); let mut romol = rdkit_sys::ro_mol_ffi::smiles_to_mol(&smiles).unwrap(); - let atom = rdkit_sys::ro_mol_ffi::get_atom_with_idx(&mut romol, 0); - rdkit_sys::ro_mol_ffi::set_int_prop(atom, &key, 42); + let atom = rdkit_sys::ro_mol_ffi::get_atom_with_idx(romol.pin_mut(), 0) + .expect("RDKit operation failed"); + rdkit_sys::ro_mol_ffi::set_int_prop(atom, &key, 42).expect("RDKit operation failed"); // now we create an other variable that is the same atom. // if it works, it should - let atom_2 = rdkit_sys::ro_mol_ffi::get_atom_with_idx(&mut romol, 0); - let value = rdkit_sys::ro_mol_ffi::get_int_prop(atom_2.as_ref(), &key); + let atom_2 = rdkit_sys::ro_mol_ffi::get_atom_with_idx(romol.pin_mut(), 0) + .expect("RDKit operation failed"); + let value = rdkit_sys::ro_mol_ffi::get_int_prop(atom_2.as_ref().get_ref(), &key); assert!(value.is_ok()); assert_eq!(value.unwrap(), 42); // get the "bar" property that does not exist, should return an error cxx::let_cxx_string!(error_key = "bar"); - let atom_2 = rdkit_sys::ro_mol_ffi::get_atom_with_idx(&mut romol, 0); - let error_value = rdkit_sys::ro_mol_ffi::get_int_prop(atom_2.as_ref(), &error_key); + let atom_2 = rdkit_sys::ro_mol_ffi::get_atom_with_idx(romol.pin_mut(), 0) + .expect("RDKit operation failed"); + let error_value = rdkit_sys::ro_mol_ffi::get_int_prop(atom_2.as_ref().get_ref(), &error_key); assert!(error_value.is_err()); } @@ -114,8 +131,11 @@ fn set_and_get_int_property_test() { fn get_num_radical_electrons_test() { cxx::let_cxx_string!(smiles = "CC"); let mut romol = rdkit_sys::ro_mol_ffi::smiles_to_mol(&smiles).unwrap(); - let atom = rdkit_sys::ro_mol_ffi::get_atom_with_idx(&mut romol, 0); - let num_radical_electrons = rdkit_sys::ro_mol_ffi::get_num_radical_electrons(atom.as_ref()); + let atom = rdkit_sys::ro_mol_ffi::get_atom_with_idx(romol.pin_mut(), 0) + .expect("RDKit operation failed"); + let num_radical_electrons = + rdkit_sys::ro_mol_ffi::get_num_radical_electrons(atom.as_ref().get_ref()) + .expect("RDKit operation failed"); assert_eq!(num_radical_electrons, 0); } @@ -123,7 +143,9 @@ fn get_num_radical_electrons_test() { fn get_degree_test() { cxx::let_cxx_string!(smiles = "CC"); let mut romol = rdkit_sys::ro_mol_ffi::smiles_to_mol(&smiles).unwrap(); - let atom = rdkit_sys::ro_mol_ffi::get_atom_with_idx(&mut romol, 0); - let degree = rdkit_sys::ro_mol_ffi::get_degree(atom.as_ref()); + let atom = rdkit_sys::ro_mol_ffi::get_atom_with_idx(romol.pin_mut(), 0) + .expect("RDKit operation failed"); + let degree = + rdkit_sys::ro_mol_ffi::get_degree(atom.as_ref().get_ref()).expect("RDKit operation failed"); assert_eq!(degree, 1); } diff --git a/rdkit-sys/tests/test_rw_mol.rs b/rdkit-sys/tests/test_rw_mol.rs index f31ee43..9577690 100644 --- a/rdkit-sys/tests/test_rw_mol.rs +++ b/rdkit-sys/tests/test_rw_mol.rs @@ -1,13 +1,12 @@ -use cxx::{let_cxx_string, SharedPtr}; -use rdkit_sys::{ro_mol_ffi::ROMol, rw_mol_ffi::RWMol}; +use cxx::let_cxx_string; #[test] fn test_rw_mol_from_smarts() { cxx::let_cxx_string!(smarts = "[+1!h0!$([*]~[-1,-2,-3,-4]),-1!$([*]~[+1,+2,+3,+4])]"); let rwmol = rdkit_sys::rw_mol_ffi::smarts_to_mol(&smarts).unwrap(); - let romol = rdkit_sys::rw_mol_ffi::rw_mol_to_ro_mol(rwmol); + let romol = rdkit_sys::rw_mol_ffi::rw_mol_to_ro_mol(rwmol).expect("RDKit operation failed"); - let smiles = rdkit_sys::ro_mol_ffi::mol_to_smiles(&romol); + let smiles = rdkit_sys::ro_mol_ffi::mol_to_smiles(&romol).expect("RDKit operation failed"); assert_eq!(smiles, "*".to_string()); } @@ -187,10 +186,11 @@ CC(=O)OC(CC(=O)[O-])C[N+](C)(C)C let_cxx_string!(mol_block = mol_block); - let rw_mol = rdkit_sys::rw_mol_ffi::rw_mol_from_mol_block(&mol_block, false, false, false); - let ro_mol = unsafe { std::mem::transmute::, SharedPtr>(rw_mol) }; + let rw_mol = rdkit_sys::rw_mol_ffi::rw_mol_from_mol_block(&mol_block, false, false, false) + .expect("RDKit operation failed"); + let ro_mol = rdkit_sys::rw_mol_ffi::rw_mol_to_ro_mol(rw_mol).unwrap(); - let smiles = rdkit_sys::ro_mol_ffi::mol_to_smiles(&ro_mol); + let smiles = rdkit_sys::ro_mol_ffi::mol_to_smiles(&ro_mol).expect("RDKit operation failed"); assert_eq!("[H]C([H])([H])C(=O)OC([H])(C([H])([H])C(=O)[O-])C([H])([H])[N+](C([H])([H])[H])(C([H])([H])[H])C([H])([H])[H]", &smiles); } @@ -314,13 +314,7 @@ O=Cl(=O)(=O)F $"#; let_cxx_string!(bad = bad); - let mol = { - let mut mol = rdkit_sys::rw_mol_ffi::rw_mol_from_mol_block(&bad, true, false, false); - if mol.is_null() { - mol = rdkit_sys::rw_mol_ffi::rw_mol_from_mol_block(&bad, false, false, false); - } - mol - }; + assert!(rdkit_sys::rw_mol_ffi::rw_mol_from_mol_block(&bad, true, false, false).is_err()); + let mol = rdkit_sys::rw_mol_ffi::rw_mol_from_mol_block(&bad, false, false, false).unwrap(); assert!(!mol.is_null()); - // println!("{}", mol.as_smile()); } diff --git a/rdkit-sys/tests/test_scaffold_network.rs b/rdkit-sys/tests/test_scaffold_network.rs index 9819a4d..f93cc1c 100644 --- a/rdkit-sys/tests/test_scaffold_network.rs +++ b/rdkit-sys/tests/test_scaffold_network.rs @@ -2,19 +2,19 @@ use rdkit_sys::scaffold_network_ffi::*; #[test] fn test_scaffold_network() { - default_scaffold_network_params(); - let mut params = new_scaffold_network_params(&vec![]); + default_scaffold_network_params().expect("RDKit operation failed"); + let mut params = new_scaffold_network_params(&vec![]).expect("RDKit operation failed"); - set_include_generic_scaffolds(&mut params, true); - include_generic_bond_scaffolds(&mut params, true); - include_scaffolds_without_attachments(&mut params, true); - include_scaffolds_with_attachments(&mut params, true); - keep_only_first_fragment(&mut params, true); - prune_before_fragmenting(&mut params, true); - flatten_isotopes(&mut params, true); - flatten_chirality(&mut params, true); - flatten_keep_largest(&mut params, true); - collect_mol_counts(&mut params, true); + set_include_generic_scaffolds(params.pin_mut(), true).expect("RDKit operation failed"); + include_generic_bond_scaffolds(params.pin_mut(), true).expect("RDKit operation failed"); + include_scaffolds_without_attachments(params.pin_mut(), true).expect("RDKit operation failed"); + include_scaffolds_with_attachments(params.pin_mut(), true).expect("RDKit operation failed"); + keep_only_first_fragment(params.pin_mut(), true).expect("RDKit operation failed"); + prune_before_fragmenting(params.pin_mut(), true).expect("RDKit operation failed"); + flatten_isotopes(params.pin_mut(), true).expect("RDKit operation failed"); + flatten_chirality(params.pin_mut(), true).expect("RDKit operation failed"); + flatten_keep_largest(params.pin_mut(), true).expect("RDKit operation failed"); + collect_mol_counts(params.pin_mut(), true).expect("RDKit operation failed"); - let _scaffold_network = default_scaffold_network(); + let _scaffold_network = default_scaffold_network().expect("RDKit operation failed"); } diff --git a/rdkit-sys/tests/test_substruct_match.rs b/rdkit-sys/tests/test_substruct_match.rs index 9890b2e..c291e12 100644 --- a/rdkit-sys/tests/test_substruct_match.rs +++ b/rdkit-sys/tests/test_substruct_match.rs @@ -8,19 +8,19 @@ fn test_substruct_match_as_bool() { cxx::let_cxx_string!(smiles = "C"); let query = rdkit_sys::ro_mol_ffi::smiles_to_mol(&smiles).unwrap(); - let match_params = new_substruct_match_parameters(); + let match_params = new_substruct_match_parameters().expect("RDKit operation failed"); - let hits = substruct_match(&mol, &query, &match_params); + let hits = substruct_match(&mol, &query, &match_params).expect("RDKit operation failed"); // Note that idx are not stable between test runs, we would need to pull out // atoms but that's too much work for me. let testable_hits: Vec> = hits .into_iter() .map(|x| { - let substruct_match_items = rdkit_sys::substruct_match_ffi::substruct_matchvect_type_to_vec_substruct_match_item(x); + let substruct_match_items = rdkit_sys::substruct_match_ffi::substruct_matchvect_type_to_vec_substruct_match_item(x).expect("RDKit operation failed"); substruct_match_items.iter().map(|smi| { ( - substruct_match_item_query_atom_idx(smi), - substruct_match_item_mol_atom_idx(smi), + substruct_match_item_query_atom_idx(smi).expect("RDKit operation failed"), + substruct_match_item_mol_atom_idx(smi).expect("RDKit operation failed"), ) }).collect::>() diff --git a/rdkit-sys/wrapper/include/bond.h b/rdkit-sys/wrapper/include/bond.h new file mode 100644 index 0000000..9b22aee --- /dev/null +++ b/rdkit-sys/wrapper/include/bond.h @@ -0,0 +1,27 @@ +#pragma once + +#include "rust/cxx.h" +#include + +namespace RDKit { + +using BondType = Bond::BondType; +using BondStereo = Bond::BondStereo; +using BondDir = Bond::BondDir; + +unsigned int get_num_bonds(const ROMol &mol, bool only_heavy); +const Bond &get_bond_with_idx(const ROMol &mol, unsigned int idx); +int get_bond_idx_between_atoms(const ROMol &mol, unsigned int begin_idx, unsigned int end_idx); + +BondType bond_get_bond_type(const Bond &bond); +double bond_get_bond_type_as_double(const Bond &bond); +unsigned int bond_get_begin_atom_idx(const Bond &bond); +unsigned int bond_get_end_atom_idx(const Bond &bond); +unsigned int bond_get_other_atom_idx(const Bond &bond, unsigned int this_idx); +bool bond_get_is_aromatic(const Bond &bond); +bool bond_get_is_conjugated(const Bond &bond); +BondStereo bond_get_stereo(const Bond &bond); +BondDir bond_get_bond_dir(const Bond &bond); +unsigned int bond_get_idx(const Bond &bond); + +} diff --git a/rdkit-sys/wrapper/include/conformer.h b/rdkit-sys/wrapper/include/conformer.h new file mode 100644 index 0000000..707aa97 --- /dev/null +++ b/rdkit-sys/wrapper/include/conformer.h @@ -0,0 +1,17 @@ +#pragma once +#include "rust/cxx.h" +#include +#include + +namespace RDKit { +struct Point3D; +unsigned int compute_2d_coords(ROMol &mol); +unsigned int get_num_conformers(const ROMol &mol); +const Conformer &get_conformer(const ROMol &mol, int id); +Conformer &get_conformer_mut(ROMol &mol, int id); +unsigned int conformer_id(const Conformer &conf); +bool conformer_is_3d(const Conformer &conf); +unsigned int conformer_num_atoms(const Conformer &conf); +Point3D conformer_position(const Conformer &conf, unsigned int idx); +void conformer_set_position(Conformer &conf, unsigned int idx, Point3D pos); +} diff --git a/rdkit-sys/wrapper/include/descriptors.h b/rdkit-sys/wrapper/include/descriptors.h index c7a87e1..0e3bdd0 100644 --- a/rdkit-sys/wrapper/include/descriptors.h +++ b/rdkit-sys/wrapper/include/descriptors.h @@ -6,8 +6,7 @@ namespace RDKit { using Descriptors::Properties; -std::shared_ptr new_properties(); -std::unique_ptr> get_property_names(const std::shared_ptr &props); -std::unique_ptr> compute_properties(const std::shared_ptr &props, - const std::shared_ptr &mol); +std::unique_ptr new_properties(); +std::unique_ptr> get_property_names(const Properties &props); +std::unique_ptr> compute_properties(const Properties &props, const ROMol &mol); } // namespace RDKit \ No newline at end of file diff --git a/rdkit-sys/wrapper/include/fingerprint.h b/rdkit-sys/wrapper/include/fingerprint.h index f1fe3e7..b496d78 100644 --- a/rdkit-sys/wrapper/include/fingerprint.h +++ b/rdkit-sys/wrapper/include/fingerprint.h @@ -4,11 +4,17 @@ namespace RDKit { using ExplicitBitVect = ::ExplicitBitVect; -std::shared_ptr rdk_fingerprint_mol(const std::shared_ptr &mol); -std::shared_ptr pattern_fingerprint_mol(const std::shared_ptr &mol); -std::shared_ptr morgan_fingerprint_mol(const std::shared_ptr &mol); -std::shared_ptr copy_explicit_bit_vect(const std::shared_ptr &orig); -unsigned int get_num_on_bits(const std::shared_ptr &bitvect); +std::unique_ptr rdk_fingerprint_mol(const ROMol &mol); +std::unique_ptr pattern_fingerprint_mol(const ROMol &mol); +std::unique_ptr morgan_fingerprint_mol(const ROMol &mol); +std::unique_ptr copy_explicit_bit_vect(const ExplicitBitVect &orig); -std::unique_ptr> explicit_bit_vect_to_u64_vec(const std::shared_ptr &bitvect); +std::unique_ptr> explicit_bit_vect_to_u64_vec(const ExplicitBitVect &bitvect); +unsigned int explicit_bit_vect_num_bits(const ExplicitBitVect &bits); +std::unique_ptr morgan_fingerprint_mol_with_params(const ROMol &mol, unsigned int radius, + unsigned int n_bits); +std::unique_ptr rdk_fingerprint_mol_with_params(const ROMol &mol, unsigned int min_path, + unsigned int max_path, unsigned int n_bits); +std::unique_ptr pattern_fingerprint_mol_with_params(const ROMol &mol, unsigned int n_bits); +std::unique_ptr maccs_fingerprint_mol(const ROMol &mol); } // namespace RDKit \ No newline at end of file diff --git a/rdkit-sys/wrapper/include/mol_ops.h b/rdkit-sys/wrapper/include/mol_ops.h index 654bce2..039fdca 100644 --- a/rdkit-sys/wrapper/include/mol_ops.h +++ b/rdkit-sys/wrapper/include/mol_ops.h @@ -7,64 +7,62 @@ namespace RDKit { // pub fn new_remove_hs_parameters() -> SharedPtr; using RemoveHsParameters = RDKit::MolOps::RemoveHsParameters; -std::shared_ptr new_remove_hs_parameters(); +std::unique_ptr new_remove_hs_parameters(); -bool get_remove_degree_zero(const std::shared_ptr ¶ms); -void set_remove_degree_zero(std::shared_ptr ¶ms, bool what); +bool get_remove_degree_zero(const RemoveHsParameters ¶ms); +void set_remove_degree_zero(RemoveHsParameters ¶ms, bool what); -bool get_remove_higher_degrees(const std::shared_ptr ¶ms); -void set_remove_higher_degrees(std::shared_ptr ¶ms, bool what); +bool get_remove_higher_degrees(const RemoveHsParameters ¶ms); +void set_remove_higher_degrees(RemoveHsParameters ¶ms, bool what); -bool get_remove_only_h_neighbors(const std::shared_ptr ¶ms); -void set_remove_only_h_neighbors(std::shared_ptr ¶ms, bool what); +bool get_remove_only_h_neighbors(const RemoveHsParameters ¶ms); +void set_remove_only_h_neighbors(RemoveHsParameters ¶ms, bool what); -bool get_remove_isotopes(const std::shared_ptr ¶ms); -void set_remove_isotopes(std::shared_ptr ¶ms, bool what); +bool get_remove_isotopes(const RemoveHsParameters ¶ms); +void set_remove_isotopes(RemoveHsParameters ¶ms, bool what); -bool get_remove_and_track_isotopes(const std::shared_ptr ¶ms); -void set_remove_and_track_isotopes(std::shared_ptr ¶ms, bool what); +bool get_remove_and_track_isotopes(const RemoveHsParameters ¶ms); +void set_remove_and_track_isotopes(RemoveHsParameters ¶ms, bool what); -bool get_remove_dummy_neighbors(const std::shared_ptr ¶ms); -void set_remove_dummy_neighbors(std::shared_ptr ¶ms, bool what); +bool get_remove_dummy_neighbors(const RemoveHsParameters ¶ms); +void set_remove_dummy_neighbors(RemoveHsParameters ¶ms, bool what); -bool get_remove_defining_bond_stereo(const std::shared_ptr ¶ms); -void set_remove_defining_bond_stereo(std::shared_ptr ¶ms, bool what); +bool get_remove_defining_bond_stereo(const RemoveHsParameters ¶ms); +void set_remove_defining_bond_stereo(RemoveHsParameters ¶ms, bool what); -bool get_remove_with_wedged_bond(const std::shared_ptr ¶ms); -void set_remove_with_wedged_bond(std::shared_ptr ¶ms, bool what); +bool get_remove_with_wedged_bond(const RemoveHsParameters ¶ms); +void set_remove_with_wedged_bond(RemoveHsParameters ¶ms, bool what); -bool get_remove_with_query(const std::shared_ptr ¶ms); -void set_remove_with_query(std::shared_ptr ¶ms, bool what); +bool get_remove_with_query(const RemoveHsParameters ¶ms); +void set_remove_with_query(RemoveHsParameters ¶ms, bool what); -bool get_remove_mapped(const std::shared_ptr ¶ms); -void set_remove_mapped(std::shared_ptr ¶ms, bool what); +bool get_remove_mapped(const RemoveHsParameters ¶ms); +void set_remove_mapped(RemoveHsParameters ¶ms, bool what); -bool get_remove_in_s_groups(const std::shared_ptr ¶ms); -void set_remove_in_s_groups(std::shared_ptr ¶ms, bool what); +bool get_remove_in_s_groups(const RemoveHsParameters ¶ms); +void set_remove_in_s_groups(RemoveHsParameters ¶ms, bool what); -bool get_show_warnings(const std::shared_ptr ¶ms); -void set_show_warnings(std::shared_ptr ¶ms, bool what); +bool get_show_warnings(const RemoveHsParameters ¶ms); +void set_show_warnings(RemoveHsParameters ¶ms, bool what); -bool get_remove_nonimplicit(const std::shared_ptr ¶ms); -void set_remove_nonimplicit(std::shared_ptr ¶ms, bool what); +bool get_remove_nonimplicit(const RemoveHsParameters ¶ms); +void set_remove_nonimplicit(RemoveHsParameters ¶ms, bool what); -bool get_update_explicit_count(const std::shared_ptr ¶ms); -void set_update_explicit_count(std::shared_ptr ¶ms, bool what); +bool get_update_explicit_count(const RemoveHsParameters ¶ms); +void set_update_explicit_count(RemoveHsParameters ¶ms, bool what); -bool get_remove_hydrides(const std::shared_ptr ¶ms); -void set_remove_hydrides(std::shared_ptr ¶ms, bool what); +bool get_remove_hydrides(const RemoveHsParameters ¶ms); +void set_remove_hydrides(RemoveHsParameters ¶ms, bool what); -bool get_remove_nontetrahedral_neighbors(const std::shared_ptr ¶ms); -void set_remove_nontetrahedral_neighbors(std::shared_ptr ¶ms, bool what); +bool get_remove_nontetrahedral_neighbors(const RemoveHsParameters ¶ms); +void set_remove_nontetrahedral_neighbors(RemoveHsParameters ¶ms, bool what); -std::shared_ptr remove_hs_parameters(const std::shared_ptr &mol, - const std::shared_ptr ¶ms, bool sanitize); +std::unique_ptr remove_hs_parameters(const ROMol &mol, const RemoveHsParameters ¶ms, bool sanitize); -std::shared_ptr add_hs(const std::shared_ptr &mol, bool explicit_only, bool add_coords, - bool add_residue_info); +std::unique_ptr add_hs(const ROMol &mol, bool explicit_only, bool add_coords, bool add_residue_info); -void romol_set_hybridization(std::shared_ptr &mol); +void romol_set_hybridization(ROMol &mol); // pub fn clean_up(rw_mol: &mut SharedPtr) -void clean_up(std::shared_ptr &rw_mol); +void clean_up(RWMol &rw_mol); } // namespace RDKit diff --git a/rdkit-sys/wrapper/include/mol_standardize.h b/rdkit-sys/wrapper/include/mol_standardize.h index d9ea8c1..57f2530 100644 --- a/rdkit-sys/wrapper/include/mol_standardize.h +++ b/rdkit-sys/wrapper/include/mol_standardize.h @@ -11,27 +11,23 @@ using TautomerEnumeratorResult = RDKit::MolStandardize::TautomerEnumeratorResult using CleanupParameters = MolStandardize::CleanupParameters; using Uncharger = MolStandardize::Uncharger; -std::shared_ptr tautomer_enumerator(); -std::shared_ptr tautomer_enumerate(const std::shared_ptr &enumerator, - const std::shared_ptr &mol); -std::shared_ptr tautomer_enumerator_canonicalize(const std::shared_ptr &enumerator, - const std::shared_ptr &mol); +std::unique_ptr tautomer_enumerator(); +std::unique_ptr tautomer_enumerate(const TautomerEnumerator &enumerator, const ROMol &mol); +std::unique_ptr tautomer_enumerator_canonicalize(const TautomerEnumerator &enumerator, const ROMol &mol); // I couldn't figure out a better way to return a vec of rolmols, check the backlog.md for more info -int tautomer_enumerator_result_tautomers_size(const std::shared_ptr &enumerator_result); -std::shared_ptr -tautomer_enumerator_result_tautomers_at(const std::shared_ptr &enumerator_result, size_t at); +size_t tautomer_enumerator_result_tautomers_size(const TautomerEnumeratorResult &enumerator_result); +std::unique_ptr tautomer_enumerator_result_tautomers_at(const TautomerEnumeratorResult &enumerator_result, + size_t at); // rdkit-Release_2022_03_1/Code/MinimalLib/common.h -std::shared_ptr default_cleanup_parameters(); +std::unique_ptr default_cleanup_parameters(); -std::shared_ptr new_uncharger(bool canonical); -std::shared_ptr uncharger_uncharge(const std::shared_ptr &uncharger, - const std::shared_ptr &mol); +std::unique_ptr new_uncharger(bool canonical); +std::unique_ptr uncharger_uncharge(Uncharger &uncharger, const ROMol &mol); -std::shared_ptr fragment_parent(const std::shared_ptr &rw_mol, - const std::shared_ptr &cleanup_params, bool skip_standardize); +std::unique_ptr fragment_parent(const RWMol &rw_mol, const CleanupParameters &cleanup_params, + bool skip_standardize); -std::shared_ptr normalize(const std::shared_ptr &mol, - const std::shared_ptr &cleanup_params); +std::unique_ptr normalize(const RWMol &mol, const CleanupParameters &cleanup_params); } // namespace RDKit \ No newline at end of file diff --git a/rdkit-sys/wrapper/include/owned.h b/rdkit-sys/wrapper/include/owned.h new file mode 100644 index 0000000..79088d2 --- /dev/null +++ b/rdkit-sys/wrapper/include/owned.h @@ -0,0 +1,12 @@ +#pragma once +#include +#include +#include + +namespace RDKit { +template std::unique_ptr checked_owned(U &&value) { + std::unique_ptr result(std::forward(value)); + if (!result) { throw std::invalid_argument("RDKit returned no object"); } + return result; +} +} diff --git a/rdkit-sys/wrapper/include/periodic_table.h b/rdkit-sys/wrapper/include/periodic_table.h index be54cd5..bd616e8 100644 --- a/rdkit-sys/wrapper/include/periodic_table.h +++ b/rdkit-sys/wrapper/include/periodic_table.h @@ -4,8 +4,10 @@ #include namespace RDKit { +unsigned int periodic_table_max_atomic_number(const PeriodicTable &table); +unsigned int periodic_table_row(const PeriodicTable &table, unsigned int atomic_number); std::unique_ptr get_periodic_table(); rust::String getElementSymbol(unsigned int atomic_number); rust::String getElementName(unsigned int atomic_number); -const std::vector &getValenceList(unsigned int atomic_number); +std::unique_ptr> getValenceList(unsigned int atomic_number); } // namespace RDKit diff --git a/rdkit-sys/wrapper/include/ro_mol.h b/rdkit-sys/wrapper/include/ro_mol.h index 6cbe18d..d9b79c6 100644 --- a/rdkit-sys/wrapper/include/ro_mol.h +++ b/rdkit-sys/wrapper/include/ro_mol.h @@ -2,7 +2,7 @@ #include "rust/cxx.h" #include -#include +#include #include #include #include @@ -10,25 +10,24 @@ #include namespace RDKit { -std::shared_ptr copy_mol(const std::shared_ptr &mol); -std::shared_ptr smiles_to_mol(const std::string &smiles); -rust::String mol_to_smiles(const std::shared_ptr &mol); -rust::String mol_to_molblock(const std::shared_ptr &mol); +std::unique_ptr copy_mol(const ROMol &mol); +std::unique_ptr smiles_to_mol(const std::string &smiles); +rust::String mol_to_smiles(const ROMol &mol); +rust::String mol_to_molblock(const ROMol &mol); -std::shared_ptr smiles_to_mol_with_params(const std::string &smiles, - const std::shared_ptr ¶ms); -std::shared_ptr new_smiles_parser_params(); -void smiles_parser_params_set_sanitize(const std::shared_ptr ¶ms, bool sanitize); -bool smiles_parser_params_get_sanitize(const std::shared_ptr ¶ms); +std::unique_ptr smiles_to_mol_with_params(const std::string &smiles, const SmilesParserParams ¶ms); +std::unique_ptr new_smiles_parser_params(); +void smiles_parser_params_set_sanitize(SmilesParserParams ¶ms, bool sanitize); +bool smiles_parser_params_get_sanitize(const SmilesParserParams ¶ms); using MolSanitizeExceptionUniquePtr = std::unique_ptr; -std::unique_ptr> -detect_chemistry_problems(const std::shared_ptr &mol); +std::unique_ptr> detect_chemistry_problems(const ROMol &mol); rust::String mol_sanitize_exception_type(const MolSanitizeExceptionUniquePtr &mol_except); unsigned int atom_sanitize_exception_get_atom_idx(const MolSanitizeExceptionUniquePtr &mol_except); -unsigned int get_num_atoms(const std::shared_ptr &mol, bool only_explicit); -Atom &get_atom_with_idx(std::shared_ptr &mol, unsigned int idx); +unsigned int get_num_atoms(const ROMol &mol, bool only_explicit); +const Atom &get_atom_ref(const ROMol &mol, unsigned int idx); +Atom &get_atom_with_idx(ROMol &mol, unsigned int idx); rust::String get_symbol(const Atom &atom); bool get_is_aromatic(const Atom &atom); int get_atomic_num(const Atom &atom); @@ -40,10 +39,10 @@ void set_num_explicit_hs(Atom &atom, int what); void atom_update_property_cache(Atom &atom, bool strict); using HybridizationType = Atom::HybridizationType; -void atom_set_hybridization(Atom &atom, HybridizationType what); +void atom_set_hybridization(Atom &atom, int what); HybridizationType atom_get_hybridization(const Atom &atom); -void ro_mol_update_property_cache(std::shared_ptr &mol, bool strict); +void ro_mol_update_property_cache(ROMol &mol, bool strict); void set_int_prop(Atom &atom, const std::string &key, int val); int get_int_prop(const Atom &atom, const std::string &key); diff --git a/rdkit-sys/wrapper/include/rw_mol.h b/rdkit-sys/wrapper/include/rw_mol.h index a368e8e..913f173 100644 --- a/rdkit-sys/wrapper/include/rw_mol.h +++ b/rdkit-sys/wrapper/include/rw_mol.h @@ -3,14 +3,22 @@ #include "rust/cxx.h" namespace RDKit { -std::shared_ptr rw_mol_from_mol_block(const std::string &mol_block, bool sanitize, bool remove_hs, +const ROMol &rw_mol_as_ro_mol(const RWMol &mol); +std::unique_ptr rw_mol_from_mol_block(const std::string &mol_block, bool sanitize, bool remove_hs, bool strict_parsing); -std::shared_ptr rw_mol_from_ro_mol(const std::shared_ptr &mol, bool quick_copy, int conf_id); +std::unique_ptr rw_mol_from_ro_mol(const ROMol &mol, bool quick_copy, int conf_id); -std::shared_ptr rw_mol_from_rw_mol(const std::shared_ptr &mol); +std::unique_ptr rw_mol_from_rw_mol(const RWMol &mol); -std::shared_ptr rw_mol_to_ro_mol(std::shared_ptr mol); +std::unique_ptr rw_mol_to_ro_mol(std::unique_ptr mol); -std::shared_ptr smarts_to_mol(const std::string &smarts); +std::unique_ptr smarts_to_mol(const std::string &smarts); +std::unique_ptr new_rw_mol(); +ROMol &rw_mol_as_ro_mol_mut(RWMol &mol); +unsigned int rw_mol_add_atom(RWMol &mol, unsigned int atomic_num); +unsigned int rw_mol_add_bond(RWMol &mol, unsigned int begin, unsigned int end, int order); +void rw_mol_remove_atom(RWMol &mol, unsigned int idx); +void rw_mol_remove_bond(RWMol &mol, unsigned int begin, unsigned int end); +void rw_mol_sanitize(RWMol &mol); } // namespace RDKit \ No newline at end of file diff --git a/rdkit-sys/wrapper/include/scaffold_network.h b/rdkit-sys/wrapper/include/scaffold_network.h index 72e9a99..4f353ad 100644 --- a/rdkit-sys/wrapper/include/scaffold_network.h +++ b/rdkit-sys/wrapper/include/scaffold_network.h @@ -7,21 +7,31 @@ namespace RDKit { using ScaffoldNetworkParams = ScaffoldNetwork::ScaffoldNetworkParams; -std::shared_ptr default_scaffold_network_params(); -std::shared_ptr new_scaffold_network_params(const rust::Vec &bondBreakersSmarts); - -void set_include_generic_scaffolds(std::shared_ptr ¶ms, bool input); -void include_generic_bond_scaffolds(std::shared_ptr ¶ms, bool input); -void include_scaffolds_without_attachments(std::shared_ptr ¶ms, bool input); -void include_scaffolds_with_attachments(std::shared_ptr ¶ms, bool input); -void keep_only_first_fragment(std::shared_ptr ¶ms, bool input); -void prune_before_fragmenting(std::shared_ptr ¶ms, bool input); -void flatten_isotopes(std::shared_ptr ¶ms, bool input); -void flatten_chirality(std::shared_ptr ¶ms, bool input); -void flatten_keep_largest(std::shared_ptr ¶ms, bool input); -void collect_mol_counts(std::shared_ptr ¶ms, bool input); +std::unique_ptr default_scaffold_network_params(); +std::unique_ptr new_scaffold_network_params(const rust::Vec &bondBreakersSmarts); + +void set_include_generic_scaffolds(ScaffoldNetworkParams ¶ms, bool input); +void include_generic_bond_scaffolds(ScaffoldNetworkParams ¶ms, bool input); +void include_scaffolds_without_attachments(ScaffoldNetworkParams ¶ms, bool input); +void include_scaffolds_with_attachments(ScaffoldNetworkParams ¶ms, bool input); +void keep_only_first_fragment(ScaffoldNetworkParams ¶ms, bool input); +void prune_before_fragmenting(ScaffoldNetworkParams ¶ms, bool input); +void flatten_isotopes(ScaffoldNetworkParams ¶ms, bool input); +void flatten_chirality(ScaffoldNetworkParams ¶ms, bool input); +void flatten_keep_largest(ScaffoldNetworkParams ¶ms, bool input); +void collect_mol_counts(ScaffoldNetworkParams ¶ms, bool input); using ScaffoldNetworkClass = ScaffoldNetwork::ScaffoldNetwork; -std::shared_ptr default_scaffold_network(); -} // namespace RDKit \ No newline at end of file +std::unique_ptr default_scaffold_network(); + +std::unique_ptr create_scaffold_network(const ROMol &mol, const ScaffoldNetworkParams ¶ms); +void update_scaffold_network(ScaffoldNetworkClass &network, const ROMol &mol, const ScaffoldNetworkParams ¶ms); + +rust::Vec scaffold_network_nodes(const ScaffoldNetworkClass &network); +rust::Vec scaffold_network_counts(const ScaffoldNetworkClass &network); +rust::Vec scaffold_network_mol_counts(const ScaffoldNetworkClass &network); +rust::Vec scaffold_network_edge_begin_indices(const ScaffoldNetworkClass &network); +rust::Vec scaffold_network_edge_end_indices(const ScaffoldNetworkClass &network); +rust::Vec scaffold_network_edge_types(const ScaffoldNetworkClass &network); +} diff --git a/rdkit-sys/wrapper/include/substruct_match.h b/rdkit-sys/wrapper/include/substruct_match.h index 1488af0..5d52012 100644 --- a/rdkit-sys/wrapper/include/substruct_match.h +++ b/rdkit-sys/wrapper/include/substruct_match.h @@ -8,25 +8,24 @@ namespace RDKit { using SubstructMatchItem = std::pair; using MatchVectType = MatchVectType; -std::unique_ptr> substruct_match(const std::shared_ptr &mol, - const std::shared_ptr &other_mol, - const std::shared_ptr ¶ms); +std::unique_ptr> substruct_match(const ROMol &mol, const ROMol &other_mol, + const SubstructMatchParameters ¶ms); -std::shared_ptr new_substruct_match_parameters(); -bool get_use_chirality(const std::shared_ptr ¶ms); -bool get_use_enhanced_stereo(const std::shared_ptr ¶ms); -bool get_aromatic_matches_conjugated(const std::shared_ptr ¶ms); -bool get_use_query_query_matches(const std::shared_ptr ¶ms); -bool get_use_generic_matchers(const std::shared_ptr ¶ms); -bool get_recursion_possible(const std::shared_ptr ¶ms); -bool get_uniquify(const std::shared_ptr ¶ms); -void set_use_chirality(std::shared_ptr ¶ms, bool what); -void set_use_enhanced_stereo(std::shared_ptr ¶ms, bool what); -void set_aromatic_matches_conjugated(std::shared_ptr ¶ms, bool what); -void set_use_query_query_matches(std::shared_ptr ¶ms, bool what); -void set_use_generic_matchers(std::shared_ptr ¶ms, bool what); -void set_recursion_possible(std::shared_ptr ¶ms, bool what); -void set_uniquify(std::shared_ptr ¶ms, bool what); +std::unique_ptr new_substruct_match_parameters(); +bool get_use_chirality(const SubstructMatchParameters ¶ms); +bool get_use_enhanced_stereo(const SubstructMatchParameters ¶ms); +bool get_aromatic_matches_conjugated(const SubstructMatchParameters ¶ms); +bool get_use_query_query_matches(const SubstructMatchParameters ¶ms); +bool get_use_generic_matchers(const SubstructMatchParameters ¶ms); +bool get_recursion_possible(const SubstructMatchParameters ¶ms); +bool get_uniquify(const SubstructMatchParameters ¶ms); +void set_use_chirality(SubstructMatchParameters ¶ms, bool what); +void set_use_enhanced_stereo(SubstructMatchParameters ¶ms, bool what); +void set_aromatic_matches_conjugated(SubstructMatchParameters ¶ms, bool what); +void set_use_query_query_matches(SubstructMatchParameters ¶ms, bool what); +void set_use_generic_matchers(SubstructMatchParameters ¶ms, bool what); +void set_recursion_possible(SubstructMatchParameters ¶ms, bool what); +void set_uniquify(SubstructMatchParameters ¶ms, bool what); std::unique_ptr> substruct_matchvect_type_to_vec_substruct_match_item(const MatchVectType &match_vect); diff --git a/rdkit-sys/wrapper/src/bond.cc b/rdkit-sys/wrapper/src/bond.cc new file mode 100644 index 0000000..e9c5cc7 --- /dev/null +++ b/rdkit-sys/wrapper/src/bond.cc @@ -0,0 +1,44 @@ +#include "rust/cxx.h" +#include + +namespace RDKit { + +using BondType = Bond::BondType; +using BondStereo = Bond::BondStereo; +using BondDir = Bond::BondDir; + +unsigned int get_num_bonds(const ROMol &mol, bool only_heavy) { return mol.getNumBonds(only_heavy); } + +const Bond &get_bond_with_idx(const ROMol &mol, unsigned int idx) { + if (idx >= mol.getNumBonds()) { throw std::out_of_range("bond index"); } + return *mol.getBondWithIdx(idx); +} + +int get_bond_idx_between_atoms(const ROMol &mol, unsigned int begin_idx, unsigned int end_idx) { + if (begin_idx >= mol.getNumAtoms() || end_idx >= mol.getNumAtoms()) { throw std::out_of_range("bond atom index"); } + const Bond *bond = mol.getBondBetweenAtoms(begin_idx, end_idx); + if (bond == nullptr) { return -1; } + return static_cast(bond->getIdx()); +} + +BondType bond_get_bond_type(const Bond &bond) { return bond.getBondType(); } + +double bond_get_bond_type_as_double(const Bond &bond) { return bond.getBondTypeAsDouble(); } + +unsigned int bond_get_begin_atom_idx(const Bond &bond) { return bond.getBeginAtomIdx(); } + +unsigned int bond_get_end_atom_idx(const Bond &bond) { return bond.getEndAtomIdx(); } + +unsigned int bond_get_other_atom_idx(const Bond &bond, unsigned int this_idx) { return bond.getOtherAtomIdx(this_idx); } + +bool bond_get_is_aromatic(const Bond &bond) { return bond.getIsAromatic(); } + +bool bond_get_is_conjugated(const Bond &bond) { return bond.getIsConjugated(); } + +BondStereo bond_get_stereo(const Bond &bond) { return bond.getStereo(); } + +BondDir bond_get_bond_dir(const Bond &bond) { return bond.getBondDir(); } + +unsigned int bond_get_idx(const Bond &bond) { return bond.getIdx(); } + +} diff --git a/rdkit-sys/wrapper/src/conformer.cc b/rdkit-sys/wrapper/src/conformer.cc new file mode 100644 index 0000000..987b7f3 --- /dev/null +++ b/rdkit-sys/wrapper/src/conformer.cc @@ -0,0 +1,27 @@ +#include "wrapper/include/conformer.h" +#include "rdkit-sys/src/bridge/conformer.rs.h" +#include +#include +#include + +namespace RDKit { +unsigned int compute_2d_coords(ROMol &mol) { return RDDepict::compute2DCoords(mol); } +unsigned int get_num_conformers(const ROMol &mol) { return mol.getNumConformers(); } +const Conformer &get_conformer(const ROMol &mol, int id) { return mol.getConformer(id); } +Conformer &get_conformer_mut(ROMol &mol, int id) { return mol.getConformer(id); } +unsigned int conformer_id(const Conformer &conf) { return conf.getId(); } +bool conformer_is_3d(const Conformer &conf) { return conf.is3D(); } +unsigned int conformer_num_atoms(const Conformer &conf) { return conf.getNumAtoms(); } +Point3D conformer_position(const Conformer &conf, unsigned int idx) { + if (idx >= conf.getNumAtoms()) { throw std::out_of_range("conformer atom index"); } + const auto &pos = conf.getAtomPos(idx); + return {pos.x, pos.y, pos.z}; +} +void conformer_set_position(Conformer &conf, unsigned int idx, Point3D pos) { + if (idx >= conf.getNumAtoms()) { throw std::out_of_range("conformer atom index"); } + if (!std::isfinite(pos.x) || !std::isfinite(pos.y) || !std::isfinite(pos.z)) { + throw std::invalid_argument("coordinates must be finite"); + } + conf.setAtomPos(idx, RDGeom::Point3D(pos.x, pos.y, pos.z)); +} +} diff --git a/rdkit-sys/wrapper/src/descriptors.cc b/rdkit-sys/wrapper/src/descriptors.cc index 2e5b2fa..bbf48ef 100644 --- a/rdkit-sys/wrapper/src/descriptors.cc +++ b/rdkit-sys/wrapper/src/descriptors.cc @@ -5,18 +5,13 @@ namespace RDKit { using Descriptors::Properties; -std::shared_ptr new_properties() { return std::shared_ptr(new Properties()); } +std::unique_ptr new_properties() { return std::unique_ptr(new Properties()); } -std::unique_ptr> get_property_names(const std::shared_ptr &props) { - std::vector names = props->getPropertyNames(); - std::vector *names_heap = new std::vector(names); - return std::unique_ptr>(names_heap); +std::unique_ptr> get_property_names(const Properties &props) { + return std::make_unique>(props.getPropertyNames()); } -std::unique_ptr> compute_properties(const std::shared_ptr &props, - const std::shared_ptr &mol) { - std::vector computed = props->computeProperties(*mol); - auto computed_heap = new std::vector(computed); - return std::unique_ptr>(computed_heap); +std::unique_ptr> compute_properties(const Properties &props, const ROMol &mol) { + return std::make_unique>(props.computeProperties(mol)); } } // namespace RDKit \ No newline at end of file diff --git a/rdkit-sys/wrapper/src/fingerprint.cc b/rdkit-sys/wrapper/src/fingerprint.cc index 83c939f..edf9a47 100644 --- a/rdkit-sys/wrapper/src/fingerprint.cc +++ b/rdkit-sys/wrapper/src/fingerprint.cc @@ -1,31 +1,52 @@ #include "rust/cxx.h" +#include "wrapper/include/owned.h" #include #include +#include #include +#include namespace RDKit { -std::shared_ptr rdk_fingerprint_mol(const std::shared_ptr &mol) { - return std::shared_ptr(RDKFingerprintMol(*mol)); +std::unique_ptr rdk_fingerprint_mol(const ROMol &mol) { + return checked_owned(RDKFingerprintMol(mol)); } -std::shared_ptr pattern_fingerprint_mol(const std::shared_ptr &mol) { - return std::shared_ptr(PatternFingerprintMol(*mol)); +std::unique_ptr pattern_fingerprint_mol(const ROMol &mol) { + return checked_owned(PatternFingerprintMol(mol)); } -std::shared_ptr morgan_fingerprint_mol(const std::shared_ptr &mol) { - return std::shared_ptr(MorganFingerprints::getFingerprintAsBitVect(*mol, 3, 2048)); +std::unique_ptr morgan_fingerprint_mol(const ROMol &mol) { + return checked_owned(MorganFingerprints::getFingerprintAsBitVect(mol, 3, 2048)); } -std::shared_ptr copy_explicit_bit_vect(const std::shared_ptr &orig) { - std::shared_ptr fingerprint(new ExplicitBitVect(*orig)); +std::unique_ptr copy_explicit_bit_vect(const ExplicitBitVect &orig) { + std::unique_ptr fingerprint(new ExplicitBitVect(orig)); return fingerprint; } -std::unique_ptr> explicit_bit_vect_to_u64_vec(const std::shared_ptr &bitvect) { - std::vector bytes; - bytes.reserve(bitvect->dp_bits->num_blocks()); - boost::to_block_range(*bitvect->dp_bits, (std::back_inserter(bytes))); - std::vector *bytes_heap = new std::vector(bytes); - return std::unique_ptr>(bytes_heap); +std::unique_ptr> explicit_bit_vect_to_u64_vec(const ExplicitBitVect &bitvect) { + auto words = std::make_unique>((static_cast(bitvect.getNumBits()) + 63u) / 64u, 0); + for (unsigned int i = 0; i < bitvect.getNumBits(); ++i) { + if (bitvect.getBit(i)) { (*words)[i / 64u] |= uint64_t{1} << (i % 64u); } + } + return words; +} +unsigned int explicit_bit_vect_num_bits(const ExplicitBitVect &bits) { return bits.getNumBits(); } +std::unique_ptr morgan_fingerprint_mol_with_params(const ROMol &mol, unsigned int radius, + unsigned int n_bits) { + if (!n_bits) { throw std::invalid_argument("fingerprint size must be positive"); } + return checked_owned(MorganFingerprints::getFingerprintAsBitVect(mol, radius, n_bits)); +} +std::unique_ptr rdk_fingerprint_mol_with_params(const ROMol &mol, unsigned int min_path, + unsigned int max_path, unsigned int n_bits) { + if (!n_bits || !min_path || min_path > max_path) { throw std::invalid_argument("invalid fingerprint parameters"); } + return checked_owned(RDKFingerprintMol(mol, min_path, max_path, n_bits)); +} +std::unique_ptr pattern_fingerprint_mol_with_params(const ROMol &mol, unsigned int n_bits) { + if (!n_bits) { throw std::invalid_argument("fingerprint size must be positive"); } + return checked_owned(PatternFingerprintMol(mol, n_bits)); +} +std::unique_ptr maccs_fingerprint_mol(const ROMol &mol) { + return checked_owned(MACCSFingerprints::getFingerprintAsBitVect(mol)); } } // namespace RDKit \ No newline at end of file diff --git a/rdkit-sys/wrapper/src/mol_ops.cc b/rdkit-sys/wrapper/src/mol_ops.cc index 66b11f5..5dbecfb 100644 --- a/rdkit-sys/wrapper/src/mol_ops.cc +++ b/rdkit-sys/wrapper/src/mol_ops.cc @@ -1,109 +1,78 @@ #include "rust/cxx.h" +#include "wrapper/include/owned.h" #include #include namespace RDKit { using RemoveHsParameters = RDKit::MolOps::RemoveHsParameters; -std::shared_ptr new_remove_hs_parameters() { - return std::shared_ptr(new RemoveHsParameters); +std::unique_ptr new_remove_hs_parameters() { + return std::unique_ptr(new RemoveHsParameters); } -bool get_remove_degree_zero(const std::shared_ptr ¶ms) { return params->removeDegreeZero; } -void set_remove_degree_zero(std::shared_ptr ¶ms, bool what) { params->removeDegreeZero = what; } +bool get_remove_degree_zero(const RemoveHsParameters ¶ms) { return params.removeDegreeZero; } +void set_remove_degree_zero(RemoveHsParameters ¶ms, bool what) { params.removeDegreeZero = what; } -bool get_remove_higher_degrees(const std::shared_ptr ¶ms) { - return params->removeHigherDegrees; -} -void set_remove_higher_degrees(std::shared_ptr ¶ms, bool what) { - params->removeHigherDegrees = what; -} +bool get_remove_higher_degrees(const RemoveHsParameters ¶ms) { return params.removeHigherDegrees; } +void set_remove_higher_degrees(RemoveHsParameters ¶ms, bool what) { params.removeHigherDegrees = what; } -bool get_remove_only_h_neighbors(const std::shared_ptr ¶ms) { - return params->removeOnlyHNeighbors; -} -void set_remove_only_h_neighbors(std::shared_ptr ¶ms, bool what) { - params->removeOnlyHNeighbors = what; -} +bool get_remove_only_h_neighbors(const RemoveHsParameters ¶ms) { return params.removeOnlyHNeighbors; } +void set_remove_only_h_neighbors(RemoveHsParameters ¶ms, bool what) { params.removeOnlyHNeighbors = what; } -bool get_remove_isotopes(const std::shared_ptr ¶ms) { return params->removeIsotopes; } -void set_remove_isotopes(std::shared_ptr ¶ms, bool what) { params->removeIsotopes = what; } +bool get_remove_isotopes(const RemoveHsParameters ¶ms) { return params.removeIsotopes; } +void set_remove_isotopes(RemoveHsParameters ¶ms, bool what) { params.removeIsotopes = what; } -bool get_remove_and_track_isotopes(const std::shared_ptr ¶ms) { - return params->removeAndTrackIsotopes; -} -void set_remove_and_track_isotopes(std::shared_ptr ¶ms, bool what) { - params->removeAndTrackIsotopes = what; -} +bool get_remove_and_track_isotopes(const RemoveHsParameters ¶ms) { return params.removeAndTrackIsotopes; } +void set_remove_and_track_isotopes(RemoveHsParameters ¶ms, bool what) { params.removeAndTrackIsotopes = what; } -bool get_remove_dummy_neighbors(const std::shared_ptr ¶ms) { - return params->removeDummyNeighbors; -} -void set_remove_dummy_neighbors(std::shared_ptr ¶ms, bool what) { - params->removeDummyNeighbors = what; -} +bool get_remove_dummy_neighbors(const RemoveHsParameters ¶ms) { return params.removeDummyNeighbors; } +void set_remove_dummy_neighbors(RemoveHsParameters ¶ms, bool what) { params.removeDummyNeighbors = what; } -bool get_remove_defining_bond_stereo(const std::shared_ptr ¶ms) { - return params->removeDefiningBondStereo; -} -void set_remove_defining_bond_stereo(std::shared_ptr ¶ms, bool what) { - params->removeDefiningBondStereo = what; -} +bool get_remove_defining_bond_stereo(const RemoveHsParameters ¶ms) { return params.removeDefiningBondStereo; } +void set_remove_defining_bond_stereo(RemoveHsParameters ¶ms, bool what) { params.removeDefiningBondStereo = what; } -bool get_remove_with_wedged_bond(const std::shared_ptr ¶ms) { - return params->removeWithWedgedBond; -} -void set_remove_with_wedged_bond(std::shared_ptr ¶ms, bool what) { - params->removeWithWedgedBond = what; -} +bool get_remove_with_wedged_bond(const RemoveHsParameters ¶ms) { return params.removeWithWedgedBond; } +void set_remove_with_wedged_bond(RemoveHsParameters ¶ms, bool what) { params.removeWithWedgedBond = what; } -bool get_remove_with_query(const std::shared_ptr ¶ms) { return params->removeWithQuery; } -void set_remove_with_query(std::shared_ptr ¶ms, bool what) { params->removeWithQuery = what; } +bool get_remove_with_query(const RemoveHsParameters ¶ms) { return params.removeWithQuery; } +void set_remove_with_query(RemoveHsParameters ¶ms, bool what) { params.removeWithQuery = what; } -bool get_remove_mapped(const std::shared_ptr ¶ms) { return params->removeMapped; } -void set_remove_mapped(std::shared_ptr ¶ms, bool what) { params->removeMapped = what; } +bool get_remove_mapped(const RemoveHsParameters ¶ms) { return params.removeMapped; } +void set_remove_mapped(RemoveHsParameters ¶ms, bool what) { params.removeMapped = what; } -bool get_remove_in_s_groups(const std::shared_ptr ¶ms) { return params->removeInSGroups; } -void set_remove_in_s_groups(std::shared_ptr ¶ms, bool what) { params->removeInSGroups = what; } +bool get_remove_in_s_groups(const RemoveHsParameters ¶ms) { return params.removeInSGroups; } +void set_remove_in_s_groups(RemoveHsParameters ¶ms, bool what) { params.removeInSGroups = what; } -bool get_show_warnings(const std::shared_ptr ¶ms) { return params->showWarnings; } -void set_show_warnings(std::shared_ptr ¶ms, bool what) { params->showWarnings = what; } +bool get_show_warnings(const RemoveHsParameters ¶ms) { return params.showWarnings; } +void set_show_warnings(RemoveHsParameters ¶ms, bool what) { params.showWarnings = what; } -bool get_remove_nonimplicit(const std::shared_ptr ¶ms) { return params->removeNonimplicit; } -void set_remove_nonimplicit(std::shared_ptr ¶ms, bool what) { - params->removeNonimplicit = what; -} +bool get_remove_nonimplicit(const RemoveHsParameters ¶ms) { return params.removeNonimplicit; } +void set_remove_nonimplicit(RemoveHsParameters ¶ms, bool what) { params.removeNonimplicit = what; } -bool get_update_explicit_count(const std::shared_ptr ¶ms) { - return params->updateExplicitCount; -} -void set_update_explicit_count(std::shared_ptr ¶ms, bool what) { - params->updateExplicitCount = what; -} +bool get_update_explicit_count(const RemoveHsParameters ¶ms) { return params.updateExplicitCount; } +void set_update_explicit_count(RemoveHsParameters ¶ms, bool what) { params.updateExplicitCount = what; } -bool get_remove_hydrides(const std::shared_ptr ¶ms) { return params->removeHydrides; } -void set_remove_hydrides(std::shared_ptr ¶ms, bool what) { params->removeHydrides = what; } +bool get_remove_hydrides(const RemoveHsParameters ¶ms) { return params.removeHydrides; } +void set_remove_hydrides(RemoveHsParameters ¶ms, bool what) { params.removeHydrides = what; } -bool get_remove_nontetrahedral_neighbors(const std::shared_ptr ¶ms) { - return params->removeNontetrahedralNeighbors; +bool get_remove_nontetrahedral_neighbors(const RemoveHsParameters ¶ms) { + return params.removeNontetrahedralNeighbors; } -void set_remove_nontetrahedral_neighbors(std::shared_ptr ¶ms, bool what) { - params->removeNontetrahedralNeighbors = what; +void set_remove_nontetrahedral_neighbors(RemoveHsParameters ¶ms, bool what) { + params.removeNontetrahedralNeighbors = what; } -std::shared_ptr remove_hs_parameters(const std::shared_ptr &mol, - const std::shared_ptr ¶ms, bool sanitize) { - ROMol *new_mol = MolOps::removeHs(*mol, *params, sanitize); - return std::shared_ptr(new_mol); +std::unique_ptr remove_hs_parameters(const ROMol &mol, const RemoveHsParameters ¶ms, bool sanitize) { + ROMol *new_mol = MolOps::removeHs(mol, params, sanitize); + return checked_owned(new_mol); } // TODO: do we care about the onlyOnAtoms when adding Hs? -std::shared_ptr add_hs(const std::shared_ptr &mol, bool explicit_only, bool add_coords, - bool add_residue_info) { - ROMol *new_mol = MolOps::addHs(*mol, explicit_only, add_coords, nullptr, add_residue_info); - return std::shared_ptr(new_mol); +std::unique_ptr add_hs(const ROMol &mol, bool explicit_only, bool add_coords, bool add_residue_info) { + ROMol *new_mol = MolOps::addHs(mol, explicit_only, add_coords, nullptr, add_residue_info); + return checked_owned(new_mol); } -void romol_set_hybridization(std::shared_ptr &mol) { MolOps::setHybridization(*mol); } +void romol_set_hybridization(ROMol &mol) { MolOps::setHybridization(mol); } -void clean_up(std::shared_ptr &rw_mol) { MolOps::cleanUp(*rw_mol); } +void clean_up(RWMol &rw_mol) { MolOps::cleanUp(rw_mol); } } // namespace RDKit \ No newline at end of file diff --git a/rdkit-sys/wrapper/src/mol_standardize.cc b/rdkit-sys/wrapper/src/mol_standardize.cc index 082e655..af68be3 100644 --- a/rdkit-sys/wrapper/src/mol_standardize.cc +++ b/rdkit-sys/wrapper/src/mol_standardize.cc @@ -1,3 +1,4 @@ +#include "wrapper/include/owned.h" #include #include "rust/cxx.h" @@ -14,59 +15,56 @@ using TautomerEnumeratorResult = MolStandardize::TautomerEnumeratorResult; using CleanupParameters = MolStandardize::CleanupParameters; using Uncharger = MolStandardize::Uncharger; -std::shared_ptr tautomer_enumerator() { +std::unique_ptr tautomer_enumerator() { TautomerEnumerator *enumerator = new MolStandardize::TautomerEnumerator(); - return std::shared_ptr(enumerator); + return std::unique_ptr(enumerator); } -std::shared_ptr tautomer_enumerate(const std::shared_ptr &enumerator, - const std::shared_ptr &mol) { - TautomerEnumeratorResult stacked_enumerator = enumerator->enumerate(*mol); +std::unique_ptr tautomer_enumerate(const TautomerEnumerator &enumerator, const ROMol &mol) { + TautomerEnumeratorResult stacked_enumerator = enumerator.enumerate(mol); TautomerEnumeratorResult *heaped_enumerator = new TautomerEnumeratorResult(stacked_enumerator); - return std::shared_ptr(heaped_enumerator); + return std::unique_ptr(heaped_enumerator); } -std::shared_ptr tautomer_enumerator_canonicalize(const std::shared_ptr &enumerator, - const std::shared_ptr &mol) { - ROMol *canonical_mol = enumerator->canonicalize(*mol); - return std::shared_ptr(canonical_mol); +std::unique_ptr tautomer_enumerator_canonicalize(const TautomerEnumerator &enumerator, const ROMol &mol) { + ROMol *canonical_mol = enumerator.canonicalize(mol); + return checked_owned(canonical_mol); } -int tautomer_enumerator_result_tautomers_size(const std::shared_ptr &enumerator_result) { - return enumerator_result->size(); +size_t tautomer_enumerator_result_tautomers_size(const TautomerEnumeratorResult &enumerator_result) { + return enumerator_result.size(); } -std::shared_ptr -tautomer_enumerator_result_tautomers_at(const std::shared_ptr &enumerator_result, size_t at) { - RDKit::ROMOL_SPTR sptr = enumerator_result->at(at); - return std::shared_ptr(new ROMol(*sptr)); +std::unique_ptr tautomer_enumerator_result_tautomers_at(const TautomerEnumeratorResult &enumerator_result, + size_t at) { + if (at >= enumerator_result.size()) { throw std::out_of_range("tautomer index"); } + RDKit::ROMOL_SPTR sptr = enumerator_result.at(at); + if (!sptr) { throw std::runtime_error("missing tautomer"); } + return checked_owned(new ROMol(*sptr)); } -std::shared_ptr default_cleanup_parameters() { +std::unique_ptr default_cleanup_parameters() { CleanupParameters *heap_cp = new CleanupParameters(MolStandardize::defaultCleanupParameters); - return std::shared_ptr(heap_cp); + return std::unique_ptr(heap_cp); } -std::shared_ptr new_uncharger(bool canonical) { - return std::shared_ptr(new Uncharger(canonical)); +std::unique_ptr new_uncharger(bool canonical) { + return std::unique_ptr(new Uncharger(canonical)); } -std::shared_ptr uncharger_uncharge(const std::shared_ptr &uncharger, - const std::shared_ptr &mol) { - ROMol *return_mol = uncharger->uncharge(*mol); - return std::shared_ptr(return_mol); +std::unique_ptr uncharger_uncharge(Uncharger &uncharger, const ROMol &mol) { + ROMol *return_mol = uncharger.uncharge(mol); + return checked_owned(return_mol); } -std::shared_ptr fragment_parent(const std::shared_ptr &rw_mol, - const std::shared_ptr &cleanup_params, +std::unique_ptr fragment_parent(const RWMol &rw_mol, const CleanupParameters &cleanup_params, bool skip_standardize) { - RWMol *parent = RDKit::MolStandardize::fragmentParent(*rw_mol, *cleanup_params, skip_standardize); - return std::shared_ptr(parent); + RWMol *parent = RDKit::MolStandardize::fragmentParent(rw_mol, cleanup_params, skip_standardize); + return checked_owned(parent); } -std::shared_ptr normalize(const std::shared_ptr &mol, - const std::shared_ptr &cleanup_params) { - RWMol *normalized = RDKit::MolStandardize::normalize(&*mol, *cleanup_params); - return std::shared_ptr(normalized); +std::unique_ptr normalize(const RWMol &mol, const CleanupParameters &cleanup_params) { + RWMol *normalized = RDKit::MolStandardize::normalize(&mol, cleanup_params); + return checked_owned(normalized); } } // namespace RDKit \ No newline at end of file diff --git a/rdkit-sys/wrapper/src/periodic_table.cc b/rdkit-sys/wrapper/src/periodic_table.cc index dc68723..d64660d 100644 --- a/rdkit-sys/wrapper/src/periodic_table.cc +++ b/rdkit-sys/wrapper/src/periodic_table.cc @@ -1,7 +1,33 @@ #include "rust/cxx.h" -#include +#include +#include +#include +#include namespace RDKit { +template unsigned int table_max_atomic_number(const Table &table) { + if constexpr (requires { table.getMaxAtomicNumber(); }) { + return table.getMaxAtomicNumber(); + } else { + return 118; + } +} + +template unsigned int table_row(const Table &table, unsigned int atomic_number) { + if constexpr (requires { table.getRow(atomic_number); }) { + return table.getRow(atomic_number); + } else { + constexpr std::array row_ends{0, 2, 10, 18, 36, 54, 86, 118}; + if (atomic_number > row_ends.back()) { throw std::out_of_range("atomic number"); } + return std::lower_bound(row_ends.begin(), row_ends.end(), atomic_number) - row_ends.begin(); + } +} + +unsigned int periodic_table_max_atomic_number(const PeriodicTable &table) { return table_max_atomic_number(table); } +unsigned int periodic_table_row(const PeriodicTable &table, unsigned int atomic_number) { + return table_row(table, atomic_number); +} + std::unique_ptr get_periodic_table() { // in rdkit we have the following: // PeriodicTable::getTable() return : const PeriodicTable* @@ -18,9 +44,9 @@ rust::String getElementName(unsigned int atomic_number) { return pt->getElementName(atomic_number); } -const std::vector &getValenceList(unsigned int atomic_number) { +std::unique_ptr> getValenceList(unsigned int atomic_number) { PeriodicTable *pt = RDKit::PeriodicTable::getTable(); - return pt->getValenceList(atomic_number); + return std::make_unique>(pt->getValenceList(atomic_number)); } } // namespace RDKit \ No newline at end of file diff --git a/rdkit-sys/wrapper/src/ro_mol.cc b/rdkit-sys/wrapper/src/ro_mol.cc index 2442a0b..79a532e 100644 --- a/rdkit-sys/wrapper/src/ro_mol.cc +++ b/rdkit-sys/wrapper/src/ro_mol.cc @@ -1,6 +1,7 @@ #include "rust/cxx.h" +#include "wrapper/include/owned.h" #include -#include +#include #include #include #include @@ -13,61 +14,53 @@ namespace RDKit { using ExplicitBitVect = ::ExplicitBitVect; -std::shared_ptr copy_mol(const std::shared_ptr &mol) { return std::shared_ptr(new ROMol(*mol)); } +std::unique_ptr copy_mol(const ROMol &mol) { return checked_owned(new ROMol(mol)); } -std::shared_ptr smiles_to_mol(const std::string &smiles) { +std::unique_ptr smiles_to_mol(const std::string &smiles) { ROMol *mol = SmilesToMol(smiles); - return std::shared_ptr(mol); + return std::unique_ptr(mol); } -rust::String mol_to_smiles(const std::shared_ptr &mol) { return MolToSmiles(*mol); } +rust::String mol_to_smiles(const ROMol &mol) { return MolToSmiles(mol); } -rust::String mol_to_molblock(const std::shared_ptr &mol) { return MolToMolBlock(*mol); } +rust::String mol_to_molblock(const ROMol &mol) { return MolToMolBlock(mol); } -std::shared_ptr smiles_to_mol_with_params(const std::string &smiles, - const std::shared_ptr ¶ms) { - ROMol *mol = SmilesToMol(smiles, *params); +std::unique_ptr smiles_to_mol_with_params(const std::string &smiles, const SmilesParserParams ¶ms) { + ROMol *mol = SmilesToMol(smiles, params); - return std::shared_ptr(mol); + return std::unique_ptr(mol); } -std::shared_ptr new_smiles_parser_params() { - return std::shared_ptr(new SmilesParserParams()); +std::unique_ptr new_smiles_parser_params() { + return std::unique_ptr(new SmilesParserParams()); } -void smiles_parser_params_set_sanitize(const std::shared_ptr ¶ms, bool sanitize) { - params->sanitize = sanitize; -} -bool smiles_parser_params_get_sanitize(const std::shared_ptr ¶ms) { return params->sanitize; } +void smiles_parser_params_set_sanitize(SmilesParserParams ¶ms, bool sanitize) { params.sanitize = sanitize; } +bool smiles_parser_params_get_sanitize(const SmilesParserParams ¶ms) { return params.sanitize; } using MolSanitizeExceptionUniquePtr = std::unique_ptr; -std::unique_ptr> -detect_chemistry_problems(const std::shared_ptr &mol) { - std::vector exceptions = RDKit::MolOps::detectChemistryProblems(*mol); - std::vector *heaped_exceptions = new std::vector(); - - auto s = exceptions.size(); - heaped_exceptions->reserve(s); - for (int i = 0; i < s; i++) { heaped_exceptions->push_back(std::move(exceptions[i])); } - - return std::unique_ptr>(heaped_exceptions); +std::unique_ptr> detect_chemistry_problems(const ROMol &mol) { + return std::make_unique>(RDKit::MolOps::detectChemistryProblems(mol)); } rust::String mol_sanitize_exception_type(const MolSanitizeExceptionUniquePtr &mol_except) { + if (!mol_except) { throw std::invalid_argument("missing sanitize exception"); } return mol_except->getType(); } unsigned int atom_sanitize_exception_get_atom_idx(const MolSanitizeExceptionUniquePtr &mol_except) { - MolSanitizeException *mol_except_ptr = mol_except.get(); - AtomSanitizeException *atom_sanitize_except_ptr = (AtomSanitizeException *)mol_except_ptr; + MolSanitizeException *mol_except_ptr = mol_except.get(); + auto *atom_sanitize_except_ptr = dynamic_cast(mol_except_ptr); + if (!atom_sanitize_except_ptr) { throw std::invalid_argument("not an atom sanitize exception"); } return atom_sanitize_except_ptr->getAtomIdx(); } -unsigned int get_num_atoms(const std::shared_ptr &mol, bool only_explicit) { - return mol->getNumAtoms(only_explicit); -} +unsigned int get_num_atoms(const ROMol &mol, bool only_explicit) { return mol.getNumAtoms(only_explicit); } -Atom &get_atom_with_idx(std::shared_ptr &mol, unsigned int idx) { return *mol->getAtomWithIdx(idx); } +Atom &get_atom_with_idx(ROMol &mol, unsigned int idx) { + if (idx >= mol.getNumAtoms()) { throw std::out_of_range("atom index"); } + return *mol.getAtomWithIdx(idx); +} rust::String get_symbol(const Atom &atom) { return atom.getSymbol(); } @@ -76,15 +69,24 @@ int get_atomic_num(const Atom &atom) { return atom.getAtomicNum(); } int get_formal_charge(const Atom &atom) { return atom.getFormalCharge(); } unsigned int get_total_num_hs(const Atom &atom) { return atom.getTotalNumHs(); } unsigned int get_total_valence(const Atom &atom) { return atom.getTotalValence(); } -void set_formal_charge(Atom &atom, int what) { atom.setFormalCharge(what); } -void set_num_explicit_hs(Atom &atom, int what) { atom.setNumExplicitHs(what); } +void set_formal_charge(Atom &atom, int what) { + if (what < -128 || what > 127) { throw std::invalid_argument("formal charge out of range"); } + atom.setFormalCharge(what); +} +void set_num_explicit_hs(Atom &atom, int what) { + if (what < 0 || what > 255) { throw std::invalid_argument("negative hydrogen count"); } + atom.setNumExplicitHs(what); +} void atom_update_property_cache(Atom &atom, bool strict) { atom.updatePropertyCache(strict); } using HybridizationType = Atom::HybridizationType; -void atom_set_hybridization(Atom &atom, HybridizationType what) { atom.setHybridization(what); } +void atom_set_hybridization(Atom &atom, int what) { + if (what < Atom::UNSPECIFIED || what > Atom::OTHER) { throw std::invalid_argument("invalid hybridization"); } + atom.setHybridization(static_cast(what)); +} HybridizationType atom_get_hybridization(const Atom &atom) { return atom.getHybridization(); } -void ro_mol_update_property_cache(std::shared_ptr &mol, bool strict) { mol->updatePropertyCache(strict); } +void ro_mol_update_property_cache(ROMol &mol, bool strict) { mol.updatePropertyCache(strict); } // We add the different properties of and an atom to the Atom struct void set_int_prop(Atom &atom, const std::string &key, int value) { atom.setProp(key, value); } @@ -98,4 +100,8 @@ rust::String get_prop(const Atom &atom, const std::string &key) { return atom.ge unsigned int get_num_radical_electrons(const Atom &atom) { return atom.getNumRadicalElectrons(); } unsigned int get_degree(const Atom &atom) { return atom.getDegree(); } +const Atom &get_atom_ref(const ROMol &mol, unsigned int idx) { + if (idx >= mol.getNumAtoms()) { throw std::out_of_range("atom index"); } + return *mol.getAtomWithIdx(idx); +} } // namespace RDKit \ No newline at end of file diff --git a/rdkit-sys/wrapper/src/rw_mol.cc b/rdkit-sys/wrapper/src/rw_mol.cc index faf0165..2d1abda 100644 --- a/rdkit-sys/wrapper/src/rw_mol.cc +++ b/rdkit-sys/wrapper/src/rw_mol.cc @@ -1,32 +1,66 @@ #include "rust/cxx.h" +#include "wrapper/include/owned.h" +#include "wrapper/include/periodic_table.h" #include #include +#include +#include #include #include +#include namespace RDKit { -std::shared_ptr rw_mol_from_mol_block(const std::string &mol_block, bool sanitize, bool remove_hs, +const ROMol &rw_mol_as_ro_mol(const RWMol &mol) { return mol; } +std::unique_ptr rw_mol_from_mol_block(const std::string &mol_block, bool sanitize, bool remove_hs, bool strict_parsing) { - RWMol *mol; - try { - mol = MolBlockToMol(mol_block, sanitize, remove_hs, strict_parsing); - } catch (const RDKit::FileParseException &e) { mol = nullptr; } catch (const RDKit::AtomValenceException &e) { - mol = nullptr; - } - return std::shared_ptr(mol); + auto mol = std::unique_ptr(MolBlockToMol(mol_block, sanitize, remove_hs, strict_parsing)); + if (!mol) { throw std::invalid_argument("invalid mol block"); } + return mol; } -std::shared_ptr rw_mol_from_ro_mol(const std::shared_ptr &mol, bool quick_copy, int conf_id) { - RWMol *rw_mol = new RWMol(*mol, quick_copy, conf_id); - return std::shared_ptr(rw_mol); +std::unique_ptr rw_mol_from_ro_mol(const ROMol &mol, bool quick_copy, int conf_id) { + RWMol *rw_mol = new RWMol(mol, quick_copy, conf_id); + return checked_owned(rw_mol); } -std::shared_ptr rw_mol_from_rw_mol(const std::shared_ptr &mol) { - RWMol *rw_mol = new RWMol(*mol); - return std::shared_ptr(rw_mol); +std::unique_ptr rw_mol_from_rw_mol(const RWMol &mol) { + RWMol *rw_mol = new RWMol(mol); + return checked_owned(rw_mol); } -std::shared_ptr rw_mol_to_ro_mol(std::shared_ptr mol) { return std::static_pointer_cast(mol); } +std::unique_ptr rw_mol_to_ro_mol(std::unique_ptr mol) { return checked_owned(std::move(mol)); } + +std::unique_ptr smarts_to_mol(const std::string &smarts) { + auto mol = std::unique_ptr(SmartsToMol(smarts)); + if (!mol) { throw std::invalid_argument("invalid SMARTS"); } + return mol; +} +std::unique_ptr new_rw_mol() { return std::make_unique(); } +ROMol &rw_mol_as_ro_mol_mut(RWMol &mol) { return mol; } +unsigned int rw_mol_add_atom(RWMol &mol, unsigned int atomic_num) { + if (atomic_num > periodic_table_max_atomic_number(*PeriodicTable::getTable())) { + throw std::invalid_argument("atomic number out of range"); + } + Atom atom(atomic_num); + return mol.addAtom(&atom, true, false); +} +unsigned int rw_mol_add_bond(RWMol &mol, unsigned int begin, unsigned int end, int order) { + if (begin >= mol.getNumAtoms() || end >= mol.getNumAtoms()) { throw std::out_of_range("bond atom index"); } + if (begin == end) { throw std::invalid_argument("self bond"); } + if (mol.getBondBetweenAtoms(begin, end)) { throw std::invalid_argument("bond already exists"); } + if (order < Bond::UNSPECIFIED || order > Bond::ZERO) { throw std::invalid_argument("invalid bond type"); } + mol.addBond(begin, end, static_cast(order)); + return mol.getNumBonds() - 1; +} +void rw_mol_remove_atom(RWMol &mol, unsigned int idx) { + if (idx >= mol.getNumAtoms()) { throw std::out_of_range("atom index"); } + mol.removeAtom(idx); +} +void rw_mol_remove_bond(RWMol &mol, unsigned int begin, unsigned int end) { + if (begin >= mol.getNumAtoms() || end >= mol.getNumAtoms()) { throw std::out_of_range("bond atom index"); } + if (!mol.getBondBetweenAtoms(begin, end)) { throw std::invalid_argument("bond does not exist"); } + mol.removeBond(begin, end); +} +void rw_mol_sanitize(RWMol &mol) { MolOps::sanitizeMol(mol); } -std::shared_ptr smarts_to_mol(const std::string &smarts) { return std::shared_ptr(SmartsToMol(smarts)); } } // namespace RDKit \ No newline at end of file diff --git a/rdkit-sys/wrapper/src/scaffold_network.cc b/rdkit-sys/wrapper/src/scaffold_network.cc index 8ac1f77..317a071 100644 --- a/rdkit-sys/wrapper/src/scaffold_network.cc +++ b/rdkit-sys/wrapper/src/scaffold_network.cc @@ -5,61 +5,124 @@ namespace RDKit { using ScaffoldNetworkParams = ScaffoldNetwork::ScaffoldNetworkParams; -std::shared_ptr default_scaffold_network_params() { +std::unique_ptr default_scaffold_network_params() { ScaffoldNetworkParams *network_params = new ScaffoldNetworkParams(); - return std::shared_ptr(network_params); + return std::unique_ptr(network_params); } -std::shared_ptr new_scaffold_network_params(const rust::Vec &bondBreakersSmarts) { +std::unique_ptr new_scaffold_network_params(const rust::Vec &bondBreakersSmarts) { std::vector cc_vec; for (auto smarts : bondBreakersSmarts) { cc_vec.push_back(std::string(smarts)); } ScaffoldNetworkParams *network_params = new ScaffoldNetworkParams(cc_vec); - return std::shared_ptr(network_params); + return std::unique_ptr(network_params); } -void set_include_generic_scaffolds(std::shared_ptr ¶ms, bool input) { - params->includeGenericScaffolds = input; +void set_include_generic_scaffolds(ScaffoldNetworkParams ¶ms, bool input) { + params.includeGenericScaffolds = input; } -void include_generic_bond_scaffolds(std::shared_ptr ¶ms, bool input) { - params->includeGenericBondScaffolds = input; +void include_generic_bond_scaffolds(ScaffoldNetworkParams ¶ms, bool input) { + params.includeGenericBondScaffolds = input; } -void include_scaffolds_without_attachments(std::shared_ptr ¶ms, bool input) { - params->includeScaffoldsWithoutAttachments = input; +void include_scaffolds_without_attachments(ScaffoldNetworkParams ¶ms, bool input) { + params.includeScaffoldsWithoutAttachments = input; } -void include_scaffolds_with_attachments(std::shared_ptr ¶ms, bool input) { - params->includeScaffoldsWithAttachments = input; +void include_scaffolds_with_attachments(ScaffoldNetworkParams ¶ms, bool input) { + params.includeScaffoldsWithAttachments = input; } -void keep_only_first_fragment(std::shared_ptr ¶ms, bool input) { - params->keepOnlyFirstFragment = input; +void keep_only_first_fragment(ScaffoldNetworkParams ¶ms, bool input) { params.keepOnlyFirstFragment = input; } + +void prune_before_fragmenting(ScaffoldNetworkParams ¶ms, bool input) { params.pruneBeforeFragmenting = input; } + +void flatten_isotopes(ScaffoldNetworkParams ¶ms, bool input) { params.flattenIsotopes = input; } + +void flatten_chirality(ScaffoldNetworkParams ¶ms, bool input) { params.flattenChirality = input; } + +void flatten_keep_largest(ScaffoldNetworkParams ¶ms, bool input) { params.flattenKeepLargest = input; } + +void collect_mol_counts(ScaffoldNetworkParams ¶ms, bool input) { params.collectMolCounts = input; } + +using ScaffoldNetworkClass = ScaffoldNetwork::ScaffoldNetwork; + +std::unique_ptr default_scaffold_network() { + ScaffoldNetworkClass *scaffold_network = new ScaffoldNetworkClass(); + return std::unique_ptr(scaffold_network); +} + +std::unique_ptr create_scaffold_network(const ROMol &mol, const ScaffoldNetworkParams ¶ms) { + std::vector> mols{std::make_shared(mol)}; + ScaffoldNetworkClass *scaffold_network = + new ScaffoldNetworkClass(ScaffoldNetwork::createScaffoldNetwork(mols, params)); + return std::unique_ptr(scaffold_network); } -void prune_before_fragmenting(std::shared_ptr ¶ms, bool input) { - params->pruneBeforeFragmenting = input; +void update_scaffold_network(ScaffoldNetworkClass &network, const ROMol &mol, const ScaffoldNetworkParams ¶ms) { + std::vector> mols{std::make_shared(mol)}; + ScaffoldNetwork::updateScaffoldNetwork(mols, network, params); } -void flatten_isotopes(std::shared_ptr ¶ms, bool input) { params->flattenIsotopes = input; } +rust::Vec scaffold_network_nodes(const ScaffoldNetworkClass &network) { + rust::Vec nodes; + nodes.reserve(network.nodes.size()); -void flatten_chirality(std::shared_ptr ¶ms, bool input) { params->flattenChirality = input; } + for (const auto &node : network.nodes) { nodes.push_back(rust::String(node)); } -void flatten_keep_largest(std::shared_ptr ¶ms, bool input) { - params->flattenKeepLargest = input; + return nodes; } -void collect_mol_counts(std::shared_ptr ¶ms, bool input) { - params->collectMolCounts = input; +rust::Vec scaffold_network_counts(const ScaffoldNetworkClass &network) { + rust::Vec counts; + counts.reserve(network.counts.size()); + + for (const auto count : network.counts) { counts.push_back(count); } + + return counts; } -using ScaffoldNetworkClass = ScaffoldNetwork::ScaffoldNetwork; +rust::Vec scaffold_network_mol_counts(const ScaffoldNetworkClass &network) { + rust::Vec mol_counts; + mol_counts.reserve(network.molCounts.size()); -std::shared_ptr default_scaffold_network() { - ScaffoldNetworkClass *scaffold_network = new ScaffoldNetworkClass(); - return std::shared_ptr(scaffold_network); + for (const auto mol_count : network.molCounts) { mol_counts.push_back(mol_count); } + + return mol_counts; +} + +rust::Vec scaffold_network_edge_begin_indices(const ScaffoldNetworkClass &network) { + rust::Vec begin_indices; + begin_indices.reserve(network.edges.size()); + + for (const auto &edge : network.edges) { begin_indices.push_back(edge.beginIdx); } + + return begin_indices; +} + +rust::Vec scaffold_network_edge_end_indices(const ScaffoldNetworkClass &network) { + rust::Vec end_indices; + end_indices.reserve(network.edges.size()); + + for (const auto &edge : network.edges) { end_indices.push_back(edge.endIdx); } + + return end_indices; } -} // namespace RDKit \ No newline at end of file +rust::Vec scaffold_network_edge_types(const ScaffoldNetworkClass &network) { + rust::Vec types; + types.reserve(network.edges.size()); + + std::ostringstream type_name; + for (const auto &edge : network.edges) { + type_name.str(""); + type_name << edge.type; + types.push_back(rust::String(type_name.str())); + } + + return types; +} + +} diff --git a/rdkit-sys/wrapper/src/substruct_match.cc b/rdkit-sys/wrapper/src/substruct_match.cc index 2796b05..9f962fd 100644 --- a/rdkit-sys/wrapper/src/substruct_match.cc +++ b/rdkit-sys/wrapper/src/substruct_match.cc @@ -5,59 +5,37 @@ namespace RDKit { using SubstructMatchItem = std::pair; -std::unique_ptr> substruct_match(const std::shared_ptr &mol, - const std::shared_ptr &other_mol, - const std::shared_ptr ¶ms) { - std::vector match = SubstructMatch(*mol, *other_mol, *params); - std::vector *heap_match = new std::vector(match); - return std::unique_ptr>(heap_match); +std::unique_ptr> substruct_match(const ROMol &mol, const ROMol &other_mol, + const SubstructMatchParameters ¶ms) { + return std::make_unique>(SubstructMatch(mol, other_mol, params)); } -std::shared_ptr new_substruct_match_parameters() { - return std::shared_ptr(new SubstructMatchParameters()); +std::unique_ptr new_substruct_match_parameters() { + return std::unique_ptr(new SubstructMatchParameters()); } -bool get_use_chirality(const std::shared_ptr ¶ms) { return params->useChirality; } -bool get_use_enhanced_stereo(const std::shared_ptr ¶ms) { - return params->useEnhancedStereo; +bool get_use_chirality(const SubstructMatchParameters ¶ms) { return params.useChirality; } +bool get_use_enhanced_stereo(const SubstructMatchParameters ¶ms) { return params.useEnhancedStereo; } +bool get_aromatic_matches_conjugated(const SubstructMatchParameters ¶ms) { + return params.aromaticMatchesConjugated; } -bool get_aromatic_matches_conjugated(const std::shared_ptr ¶ms) { - return params->aromaticMatchesConjugated; -} -bool get_use_query_query_matches(const std::shared_ptr ¶ms) { - return params->useQueryQueryMatches; -} -bool get_use_generic_matchers(const std::shared_ptr ¶ms) { - return params->useGenericMatchers; -} -bool get_recursion_possible(const std::shared_ptr ¶ms) { - return params->recursionPossible; -} -bool get_uniquify(const std::shared_ptr ¶ms) { return params->uniquify; } +bool get_use_query_query_matches(const SubstructMatchParameters ¶ms) { return params.useQueryQueryMatches; } +bool get_use_generic_matchers(const SubstructMatchParameters ¶ms) { return params.useGenericMatchers; } +bool get_recursion_possible(const SubstructMatchParameters ¶ms) { return params.recursionPossible; } +bool get_uniquify(const SubstructMatchParameters ¶ms) { return params.uniquify; } -void set_use_chirality(std::shared_ptr ¶ms, bool what) { params->useChirality = what; } -void set_use_enhanced_stereo(std::shared_ptr ¶ms, bool what) { - params->useEnhancedStereo = what; -} -void set_aromatic_matches_conjugated(std::shared_ptr ¶ms, bool what) { - params->aromaticMatchesConjugated = what; +void set_use_chirality(SubstructMatchParameters ¶ms, bool what) { params.useChirality = what; } +void set_use_enhanced_stereo(SubstructMatchParameters ¶ms, bool what) { params.useEnhancedStereo = what; } +void set_aromatic_matches_conjugated(SubstructMatchParameters ¶ms, bool what) { + params.aromaticMatchesConjugated = what; } -void set_use_query_query_matches(std::shared_ptr ¶ms, bool what) { - params->useQueryQueryMatches = what; -} -void set_use_generic_matchers(std::shared_ptr ¶ms, bool what) { - params->useGenericMatchers = what; -} -void set_recursion_possible(std::shared_ptr ¶ms, bool what) { - params->recursionPossible = what; -} -void set_uniquify(std::shared_ptr ¶ms, bool what) { params->uniquify = what; } +void set_use_query_query_matches(SubstructMatchParameters ¶ms, bool what) { params.useQueryQueryMatches = what; } +void set_use_generic_matchers(SubstructMatchParameters ¶ms, bool what) { params.useGenericMatchers = what; } +void set_recursion_possible(SubstructMatchParameters ¶ms, bool what) { params.recursionPossible = what; } +void set_uniquify(SubstructMatchParameters ¶ms, bool what) { params.uniquify = what; } std::unique_ptr> substruct_matchvect_type_to_vec_substruct_match_item(const MatchVectType &match_vect) { - std::vector *match_items = new std::vector(); - for (auto match : match_vect) { match_items->push_back(std::pair(match)); } - - return std::unique_ptr>(match_items); + return std::make_unique>(match_vect.begin(), match_vect.end()); } int substruct_match_item_query_atom_idx(const SubstructMatchItem &item) { return item.first; } diff --git a/src/descriptors.rs b/src/descriptors.rs index a3272c9..58c11d2 100644 --- a/src/descriptors.rs +++ b/src/descriptors.rs @@ -1,37 +1,46 @@ use std::collections::HashMap; -use cxx::SharedPtr; +use cxx::UniquePtr; +use rdkit_sys::descriptors_ffi; use crate::ROMol; pub struct Properties { - ptr: SharedPtr, + ptr: UniquePtr, } impl Default for Properties { fn default() -> Self { - Properties::new() + Self::new() } } impl Properties { pub fn new() -> Self { - Properties { - ptr: rdkit_sys::descriptors_ffi::new_properties(), - } + Self::try_new().expect("RDKit descriptor allocation failed") } - pub fn compute_properties(&self, ro_mol: &ROMol) -> HashMap { - let names = rdkit_sys::descriptors_ffi::get_property_names(&self.ptr); - let computed = rdkit_sys::descriptors_ffi::compute_properties(&self.ptr, &ro_mol.ptr); + pub fn try_new() -> Result { + Ok(Self { + ptr: descriptors_ffi::new_properties()?, + }) + } - assert!(names.len() != 0); - assert!(computed.len() == names.len()); + pub fn compute_properties(&self, mol: &ROMol) -> HashMap { + self.try_compute_properties(mol) + .expect("RDKit descriptor calculation failed") + } - names - .into_iter() - .zip(computed.as_slice()) - .map(|(k, v)| (k.to_string(), *v)) - .collect() + pub fn try_compute_properties( + &self, + mol: &ROMol, + ) -> Result, cxx::Exception> { + let names = descriptors_ffi::get_property_names(&self.ptr)?; + let values = descriptors_ffi::compute_properties(&self.ptr, &mol.ptr)?; + Ok(names + .iter() + .zip(values.iter()) + .map(|(name, value)| (name.to_string(), *value)) + .collect()) } } diff --git a/src/file_parsers.rs b/src/file_parsers.rs index 5cd88fd..6520c6b 100644 --- a/src/file_parsers.rs +++ b/src/file_parsers.rs @@ -4,23 +4,71 @@ use std::{ path::Path, }; +use crate::RWMol; use flate2::bufread::GzDecoder; -use crate::RWMol; +pub(crate) struct SdfRecords { + reader: R, + done: bool, +} + +impl SdfRecords { + pub(crate) fn new(reader: R) -> Self { + Self { + reader, + done: false, + } + } + + pub(crate) fn next_record(&mut self) -> Option> { + if self.done { + return None; + } + let mut record = Vec::new(); + let mut line = Vec::new(); + loop { + line.clear(); + match self.reader.read_until(b'\n', &mut line) { + Ok(0) => { + self.done = true; + if record.iter().all(u8::is_ascii_whitespace) { + return None; + } + break; + } + Ok(_) => { + let delimiter = line.strip_suffix(b"\n").unwrap_or(&line); + let delimiter = delimiter.strip_suffix(b"\r").unwrap_or(delimiter); + if delimiter == b"$$$$" { + if record.iter().all(u8::is_ascii_whitespace) { + record.clear(); + continue; + } + break; + } + record.extend_from_slice(&line); + } + Err(error) => { + self.done = true; + return Some(Err(format!("SDF read failed: {error}"))); + } + } + } + Some(String::from_utf8(record).map_err(|e| format!("SDF record is not UTF-8: {e}"))) + } +} pub struct MolBlockIter { - buf_read: R, - buf: Vec, + records: SdfRecords, sanitize: bool, remove_hs: bool, strict_parsing: bool, } impl MolBlockIter { - pub fn new(buf_read: R, sanitize: bool, remove_hs: bool, strict_parsing: bool) -> Self { - MolBlockIter { - buf_read, - buf: Vec::with_capacity(1024), + pub fn new(reader: R, sanitize: bool, remove_hs: bool, strict_parsing: bool) -> Self { + Self { + records: SdfRecords::new(reader), sanitize, remove_hs, strict_parsing, @@ -28,25 +76,23 @@ impl MolBlockIter { } } -pub type GzBufReader = BufReader>>; +pub type GzBufReader = BufReader>>; + +pub(crate) fn open_gz(path: impl AsRef) -> std::io::Result { + Ok(BufReader::new(GzDecoder::new(BufReader::new(File::open( + path, + )?)))) +} impl MolBlockIter { pub fn from_gz_file( - p: impl AsRef, + path: impl AsRef, sanitize: bool, remove_hs: bool, strict_parsing: bool, ) -> Result> { - let path = p.as_ref().to_owned(); - - let file = std::fs::File::open(path).unwrap(); - let buf_reader = std::io::BufReader::new(file); - - let gz_decoder = GzDecoder::new(buf_reader); - let gz_buf_reader = std::io::BufReader::new(gz_decoder); - Ok(Self::new( - gz_buf_reader, + open_gz(path)?, sanitize, remove_hs, strict_parsing, @@ -58,31 +104,12 @@ impl Iterator for MolBlockIter { type Item = Result; fn next(&mut self) -> Option { - // Consume all `$` characters and break when buffer is larger than 1. Exit - // function at EOF. - loop { - self.buf.clear(); - let read = self.buf_read.read_until(b'$', &mut self.buf).unwrap(); - if read == 0 { - return None; - } else if read == 1 { - continue; - } else { - break; - } - } - - let block = std::str::from_utf8(&self.buf).unwrap(); - let block = block.trim(); - - let rw_mol = - RWMol::from_mol_block(block, self.sanitize, self.remove_hs, self.strict_parsing); - - let result = match rw_mol { - Some(rw_mol) => Ok(rw_mol), - _ => Err(block.to_string()), - }; - - Some(result) + self.records.next_record().map(|record| { + let record = record?; + RWMol::try_from_mol_block(&record, self.sanitize, self.remove_hs, self.strict_parsing) + .map_err(|e| e.to_string()) + }) } } + +impl std::iter::FusedIterator for MolBlockIter {} diff --git a/src/fingerprint.rs b/src/fingerprint.rs index e2bdc46..5d193e8 100644 --- a/src/fingerprint.rs +++ b/src/fingerprint.rs @@ -1,28 +1,41 @@ use bitvec::prelude::*; -use cxx::SharedPtr; +use cxx::UniquePtr; +use rdkit_sys::fingerprint_ffi; #[derive(Clone, Debug)] pub struct Fingerprint(pub BitVec); impl Fingerprint { - pub fn new(ptr: SharedPtr) -> Self { - let unique_ptr_bytes = rdkit_sys::fingerprint_ffi::explicit_bit_vect_to_u64_vec(&ptr); - let rdkit_fingerprint_bytes: Vec = unique_ptr_bytes.into_iter().copied().collect(); - let mut bitvec_u64 = bitvec::vec::BitVec::::from_vec(rdkit_fingerprint_bytes); + pub fn new(ptr: UniquePtr) -> Self { + Self::try_new(ptr).expect("RDKit fingerprint conversion failed") + } - let mut idiomatic_bitvec_u8 = bitvec::vec::BitVec::::new(); - idiomatic_bitvec_u8.append(&mut bitvec_u64); + pub(crate) fn try_new( + ptr: UniquePtr, + ) -> Result { + let bits = fingerprint_ffi::explicit_bit_vect_num_bits(&ptr)? as usize; + let words = fingerprint_ffi::explicit_bit_vect_to_u64_vec(&ptr)?; + let mut bytes = Vec::with_capacity(words.len() * 8); + for word in words.iter() { + bytes.extend_from_slice(&word.to_le_bytes()); + } + let mut result = BitVec::from_vec(bytes); + result.truncate(bits); + Ok(Self(result)) + } - Fingerprint(idiomatic_bitvec_u8) + pub fn tanimoto_similarity(&self, other: &Fingerprint) -> f32 { + assert_eq!(self.0.len(), other.0.len(), "fingerprint sizes must match"); + let intersection = (self.0.clone() & &other.0).count_ones(); + let union = self.0.count_ones() + other.0.count_ones() - intersection; + if union == 0 { + 1.0 + } else { + intersection as f32 / union as f32 + } } pub fn tanimoto_distance(&self, other: &Fingerprint) -> f32 { - let and = self.0.clone() & &other.0; - let or = self.0.clone() | &other.0; - - let and_ones = and.count_ones(); - let or_ones = or.count_ones(); - - and_ones as f32 / or_ones as f32 + self.tanimoto_similarity(other) } } diff --git a/src/graphmol/atom.rs b/src/graphmol/atom.rs index 0a86743..be4f391 100644 --- a/src/graphmol/atom.rs +++ b/src/graphmol/atom.rs @@ -27,35 +27,35 @@ impl<'a> Atom<'a> { } pub fn symbol(&self) -> String { - ro_mol_ffi::get_symbol(self.ptr.as_ref()) + ro_mol_ffi::get_symbol(self.ptr.as_ref().get_ref()).expect("RDKit operation failed") } pub fn get_is_aromatic(&self) -> bool { - ro_mol_ffi::get_is_aromatic(self.ptr.as_ref()) + ro_mol_ffi::get_is_aromatic(self.ptr.as_ref().get_ref()).expect("RDKit operation failed") } pub fn get_atomic_num(&self) -> i32 { - ro_mol_ffi::get_atomic_num(self.ptr.as_ref()) + ro_mol_ffi::get_atomic_num(self.ptr.as_ref().get_ref()).expect("RDKit operation failed") } pub fn get_formal_charge(&self) -> i32 { - ro_mol_ffi::get_formal_charge(self.ptr.as_ref()) + ro_mol_ffi::get_formal_charge(self.ptr.as_ref().get_ref()).expect("RDKit operation failed") } pub fn get_total_num_hs(&self) -> u32 { - ro_mol_ffi::get_total_num_hs(self.ptr.as_ref()) + ro_mol_ffi::get_total_num_hs(self.ptr.as_ref().get_ref()).expect("RDKit operation failed") } pub fn get_total_valence(&self) -> u32 { - ro_mol_ffi::get_total_valence(self.ptr.as_ref()) + ro_mol_ffi::get_total_valence(self.ptr.as_ref().get_ref()).expect("RDKit operation failed") } pub fn set_formal_charge(&mut self, what: i32) { - ro_mol_ffi::set_formal_charge(self.ptr.as_mut(), what) + ro_mol_ffi::set_formal_charge(self.ptr.as_mut(), what).expect("RDKit operation failed") } pub fn set_num_explicit_hs(&mut self, what: i32) { - ro_mol_ffi::set_num_explicit_hs(self.ptr.as_mut(), what) + ro_mol_ffi::set_num_explicit_hs(self.ptr.as_mut(), what).expect("RDKit operation failed") } pub fn update_property_cache(&mut self, strict: bool) -> Result<(), cxx::Exception> { @@ -63,12 +63,14 @@ impl<'a> Atom<'a> { } pub fn set_hybridization_type(&mut self, what: HybridizationType) { - ro_mol_ffi::atom_set_hybridization(self.ptr.as_mut(), what); + ro_mol_ffi::atom_set_hybridization(self.ptr.as_mut(), what.repr) + .expect("RDKit operation failed"); } /// Returns the atom’s hybridization. pub fn get_hybridization_type(&self) -> HybridizationType { - ro_mol_ffi::atom_get_hybridization(self.ptr.as_ref()) + ro_mol_ffi::atom_get_hybridization(self.ptr.as_ref().get_ref()) + .expect("RDKit operation failed") } // We create a generic function set_prop that can set any property type. @@ -84,27 +86,28 @@ impl<'a> Atom<'a> { pub fn get_int_prop(&self, key: &str) -> Result { cxx::let_cxx_string!(key = key); - ro_mol_ffi::get_int_prop(self.ptr.as_ref(), &key) + ro_mol_ffi::get_int_prop(self.ptr.as_ref().get_ref(), &key) } pub fn get_float_prop(&self, key: &str) -> Result { cxx::let_cxx_string!(key = key); - ro_mol_ffi::get_float_prop(self.ptr.as_ref(), &key) + ro_mol_ffi::get_float_prop(self.ptr.as_ref().get_ref(), &key) } pub fn get_bool_prop(&self, key: &str) -> Result { cxx::let_cxx_string!(key = key); - ro_mol_ffi::get_bool_prop(self.ptr.as_ref(), &key) + ro_mol_ffi::get_bool_prop(self.ptr.as_ref().get_ref(), &key) } pub fn get_prop(&self, key: &str) -> Result { cxx::let_cxx_string!(key = key); - ro_mol_ffi::get_prop(self.ptr.as_ref(), &key) + ro_mol_ffi::get_prop(self.ptr.as_ref().get_ref(), &key) } /// Returns the number of radical electrons on the atom. pub fn get_num_radical_electrons(&self) -> u32 { - ro_mol_ffi::get_num_radical_electrons(self.ptr.as_ref()) + ro_mol_ffi::get_num_radical_electrons(self.ptr.as_ref().get_ref()) + .expect("RDKit operation failed") } /// Returns the degree of the atom in the molecule. @@ -113,39 +116,145 @@ impl<'a> Atom<'a> { /// independent of bond orders, but is dependent /// on whether or not Hs are explicit in the graph. pub fn get_degree(&self) -> u32 { - ro_mol_ffi::get_degree(self.ptr.as_ref()) + ro_mol_ffi::get_degree(self.ptr.as_ref().get_ref()).expect("RDKit operation failed") + } + pub fn try_symbol(&self) -> Result { + ro_mol_ffi::get_symbol(self.ptr.as_ref().get_ref()) + } + + pub fn try_get_is_aromatic(&self) -> Result { + ro_mol_ffi::get_is_aromatic(self.ptr.as_ref().get_ref()) + } + + pub fn try_get_atomic_num(&self) -> Result { + ro_mol_ffi::get_atomic_num(self.ptr.as_ref().get_ref()) + } + + pub fn try_get_formal_charge(&self) -> Result { + ro_mol_ffi::get_formal_charge(self.ptr.as_ref().get_ref()) + } + + pub fn try_get_total_num_hs(&self) -> Result { + ro_mol_ffi::get_total_num_hs(self.ptr.as_ref().get_ref()) + } + + pub fn try_get_total_valence(&self) -> Result { + ro_mol_ffi::get_total_valence(self.ptr.as_ref().get_ref()) + } + + pub fn try_set_formal_charge(&mut self, what: i32) -> Result<(), cxx::Exception> { + ro_mol_ffi::set_formal_charge(self.ptr.as_mut(), what) + } + + pub fn try_set_num_explicit_hs(&mut self, what: i32) -> Result<(), cxx::Exception> { + ro_mol_ffi::set_num_explicit_hs(self.ptr.as_mut(), what) + } + + pub fn try_set_hybridization_type( + &mut self, + what: HybridizationType, + ) -> Result<(), cxx::Exception> { + ro_mol_ffi::atom_set_hybridization(self.ptr.as_mut(), what.repr) + } + + pub fn try_get_hybridization_type(&self) -> Result { + ro_mol_ffi::atom_get_hybridization(self.ptr.as_ref().get_ref()) + } + + pub fn try_get_num_radical_electrons(&self) -> Result { + ro_mol_ffi::get_num_radical_electrons(self.ptr.as_ref().get_ref()) + } + + pub fn try_get_degree(&self) -> Result { + ro_mol_ffi::get_degree(self.ptr.as_ref().get_ref()) + } + + pub fn try_set_prop( + &mut self, + key: &str, + value: T, + ) -> Result<(), cxx::Exception> { + value.try_set_prop(self.ptr.as_mut(), key) } } -pub trait SetPropValue { +pub trait SetPropValue: Sized { fn set_prop(self, ptr: Pin<&mut ro_mol_ffi::Atom>, key: &str); + + fn try_set_prop( + self, + ptr: Pin<&mut ro_mol_ffi::Atom>, + key: &str, + ) -> Result<(), cxx::Exception> { + self.set_prop(ptr, key); + Ok(()) + } } impl SetPropValue for i32 { fn set_prop(self, ptr: Pin<&mut ro_mol_ffi::Atom>, key: &str) { + self.try_set_prop(ptr, key) + .expect("RDKit atom property update failed") + } + + fn try_set_prop( + self, + ptr: Pin<&mut ro_mol_ffi::Atom>, + key: &str, + ) -> Result<(), cxx::Exception> { cxx::let_cxx_string!(key = key); - ro_mol_ffi::set_int_prop(ptr, &key, self); + + ro_mol_ffi::set_int_prop(ptr, &key, self) } } impl SetPropValue for f64 { fn set_prop(self, ptr: Pin<&mut ro_mol_ffi::Atom>, key: &str) { + self.try_set_prop(ptr, key) + .expect("RDKit atom property update failed") + } + + fn try_set_prop( + self, + ptr: Pin<&mut ro_mol_ffi::Atom>, + key: &str, + ) -> Result<(), cxx::Exception> { cxx::let_cxx_string!(key = key); - ro_mol_ffi::set_float_prop(ptr, &key, self); + + ro_mol_ffi::set_float_prop(ptr, &key, self) } } impl SetPropValue for bool { fn set_prop(self, ptr: Pin<&mut ro_mol_ffi::Atom>, key: &str) { + self.try_set_prop(ptr, key) + .expect("RDKit atom property update failed") + } + + fn try_set_prop( + self, + ptr: Pin<&mut ro_mol_ffi::Atom>, + key: &str, + ) -> Result<(), cxx::Exception> { cxx::let_cxx_string!(key = key); - ro_mol_ffi::set_bool_prop(ptr, &key, self); + + ro_mol_ffi::set_bool_prop(ptr, &key, self) } } impl SetPropValue for &str { fn set_prop(self, ptr: Pin<&mut ro_mol_ffi::Atom>, key: &str) { + self.try_set_prop(ptr, key) + .expect("RDKit atom property update failed") + } + + fn try_set_prop( + self, + ptr: Pin<&mut ro_mol_ffi::Atom>, + key: &str, + ) -> Result<(), cxx::Exception> { cxx::let_cxx_string!(key = key); cxx::let_cxx_string!(value = self); - ro_mol_ffi::set_prop(ptr, &key, &value); + ro_mol_ffi::set_prop(ptr, &key, &value) } } diff --git a/src/graphmol/atom_ref.rs b/src/graphmol/atom_ref.rs new file mode 100644 index 0000000..5a9fdf2 --- /dev/null +++ b/src/graphmol/atom_ref.rs @@ -0,0 +1,119 @@ +use std::fmt::Formatter; + +use rdkit_sys::ro_mol_ffi; +pub use rdkit_sys::ro_mol_ffi::HybridizationType; + +pub struct AtomRef<'a> { + ptr: &'a ro_mol_ffi::Atom, +} + +impl<'a> std::fmt::Display for AtomRef<'a> { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let symbol = self.symbol(); + f.write_str(&symbol) + } +} + +impl<'a> std::fmt::Debug for AtomRef<'a> { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let symbol = self.symbol(); + f.write_str(&symbol) + } +} + +impl<'a> AtomRef<'a> { + pub fn from_ptr(ptr: &'a ro_mol_ffi::Atom) -> Self { + Self { ptr } + } + + pub fn symbol(&self) -> String { + ro_mol_ffi::get_symbol(self.ptr).expect("RDKit atom access failed") + } + + pub fn get_is_aromatic(&self) -> bool { + ro_mol_ffi::get_is_aromatic(self.ptr).expect("RDKit atom access failed") + } + + pub fn get_atomic_num(&self) -> i32 { + ro_mol_ffi::get_atomic_num(self.ptr).expect("RDKit atom access failed") + } + + pub fn get_formal_charge(&self) -> i32 { + ro_mol_ffi::get_formal_charge(self.ptr).expect("RDKit atom access failed") + } + + pub fn get_total_num_hs(&self) -> u32 { + ro_mol_ffi::get_total_num_hs(self.ptr).expect("RDKit atom access failed") + } + + pub fn get_total_valence(&self) -> u32 { + ro_mol_ffi::get_total_valence(self.ptr).expect("RDKit atom access failed") + } + + pub fn get_hybridization_type(&self) -> HybridizationType { + ro_mol_ffi::atom_get_hybridization(self.ptr).expect("RDKit atom access failed") + } + + pub fn get_num_radical_electrons(&self) -> u32 { + ro_mol_ffi::get_num_radical_electrons(self.ptr).expect("RDKit atom access failed") + } + + pub fn get_degree(&self) -> u32 { + ro_mol_ffi::get_degree(self.ptr).expect("RDKit atom access failed") + } + + pub fn get_int_prop(&self, key: &str) -> Result { + cxx::let_cxx_string!(key = key); + ro_mol_ffi::get_int_prop(self.ptr, &key) + } + + pub fn get_float_prop(&self, key: &str) -> Result { + cxx::let_cxx_string!(key = key); + ro_mol_ffi::get_float_prop(self.ptr, &key) + } + + pub fn get_bool_prop(&self, key: &str) -> Result { + cxx::let_cxx_string!(key = key); + ro_mol_ffi::get_bool_prop(self.ptr, &key) + } + + pub fn get_prop(&self, key: &str) -> Result { + cxx::let_cxx_string!(key = key); + ro_mol_ffi::get_prop(self.ptr, &key) + } + pub fn try_symbol(&self) -> Result { + ro_mol_ffi::get_symbol(self.ptr) + } + + pub fn try_get_is_aromatic(&self) -> Result { + ro_mol_ffi::get_is_aromatic(self.ptr) + } + + pub fn try_get_atomic_num(&self) -> Result { + ro_mol_ffi::get_atomic_num(self.ptr) + } + + pub fn try_get_formal_charge(&self) -> Result { + ro_mol_ffi::get_formal_charge(self.ptr) + } + + pub fn try_get_total_num_hs(&self) -> Result { + ro_mol_ffi::get_total_num_hs(self.ptr) + } + + pub fn try_get_total_valence(&self) -> Result { + ro_mol_ffi::get_total_valence(self.ptr) + } + + pub fn try_get_hybridization_type(&self) -> Result { + ro_mol_ffi::atom_get_hybridization(self.ptr) + } + + pub fn try_get_num_radical_electrons(&self) -> Result { + ro_mol_ffi::get_num_radical_electrons(self.ptr) + } + + pub fn try_get_degree(&self) -> Result { + ro_mol_ffi::get_degree(self.ptr) + } +} diff --git a/src/graphmol/bond.rs b/src/graphmol/bond.rs new file mode 100644 index 0000000..1e561c0 --- /dev/null +++ b/src/graphmol/bond.rs @@ -0,0 +1,67 @@ +use rdkit_sys::bond_ffi; +pub use rdkit_sys::bond_ffi::{BondDir, BondStereo, BondType}; + +pub struct Bond<'a> { + ptr: &'a bond_ffi::Bond, +} + +impl<'a> Bond<'a> { + pub fn from_ptr(ptr: &'a bond_ffi::Bond) -> Self { + Self { ptr } + } + + pub fn bond_type(&self) -> BondType { + bond_ffi::bond_get_bond_type(self.ptr).expect("RDKit bond access failed") + } + + pub fn bond_type_as_double(&self) -> f64 { + bond_ffi::bond_get_bond_type_as_double(self.ptr).expect("RDKit bond access failed") + } + + pub fn begin_atom_idx(&self) -> u32 { + bond_ffi::bond_get_begin_atom_idx(self.ptr).expect("RDKit bond access failed") + } + + pub fn end_atom_idx(&self) -> u32 { + bond_ffi::bond_get_end_atom_idx(self.ptr).expect("RDKit bond access failed") + } + + pub fn other_atom_idx(&self, this_idx: u32) -> u32 { + bond_ffi::bond_get_other_atom_idx(self.ptr, this_idx).expect("RDKit bond access failed") + } + + pub fn try_other_atom_idx(&self, this_idx: u32) -> Result { + bond_ffi::bond_get_other_atom_idx(self.ptr, this_idx) + } + + pub fn is_aromatic(&self) -> bool { + bond_ffi::bond_get_is_aromatic(self.ptr).expect("RDKit bond access failed") + } + + pub fn is_conjugated(&self) -> bool { + bond_ffi::bond_get_is_conjugated(self.ptr).expect("RDKit bond access failed") + } + + pub fn stereo(&self) -> BondStereo { + bond_ffi::bond_get_stereo(self.ptr).expect("RDKit bond access failed") + } + + pub fn bond_dir(&self) -> BondDir { + bond_ffi::bond_get_bond_dir(self.ptr).expect("RDKit bond access failed") + } + + pub fn idx(&self) -> u32 { + bond_ffi::bond_get_idx(self.ptr).expect("RDKit bond access failed") + } +} + +impl std::fmt::Debug for Bond<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Bond") + .field("idx", &self.idx()) + .field("type", &self.bond_type()) + .field("begin", &self.begin_atom_idx()) + .field("end", &self.end_atom_idx()) + .finish() + } +} diff --git a/src/graphmol/conformer.rs b/src/graphmol/conformer.rs new file mode 100644 index 0000000..bc18c96 --- /dev/null +++ b/src/graphmol/conformer.rs @@ -0,0 +1,45 @@ +use rdkit_sys::conformer_ffi; +pub use rdkit_sys::conformer_ffi::Point3D; +use std::pin::Pin; + +pub struct Conformer<'a> { + pub(crate) ptr: &'a conformer_ffi::Conformer, +} + +impl Conformer<'_> { + pub fn id(&self) -> u32 { + conformer_ffi::conformer_id(self.ptr).expect("RDKit conformer access failed") + } + + pub fn is_3d(&self) -> bool { + conformer_ffi::conformer_is_3d(self.ptr).expect("RDKit conformer access failed") + } + + pub fn num_atoms(&self) -> u32 { + conformer_ffi::conformer_num_atoms(self.ptr).expect("RDKit conformer access failed") + } + + pub fn position(&self, idx: u32) -> Result { + conformer_ffi::conformer_position(self.ptr, idx) + } +} + +pub struct ConformerMut<'a> { + pub(crate) ptr: Pin<&'a mut conformer_ffi::Conformer>, +} + +impl ConformerMut<'_> { + pub fn as_ref(&self) -> Conformer<'_> { + Conformer { + ptr: self.ptr.as_ref().get_ref(), + } + } + + pub fn position(&self, idx: u32) -> Result { + self.as_ref().position(idx) + } + + pub fn set_position(&mut self, idx: u32, pos: Point3D) -> Result<(), cxx::Exception> { + conformer_ffi::conformer_set_position(self.ptr.as_mut(), idx, pos) + } +} diff --git a/src/graphmol/mod.rs b/src/graphmol/mod.rs index f23a721..8857046 100644 --- a/src/graphmol/mod.rs +++ b/src/graphmol/mod.rs @@ -9,3 +9,10 @@ pub use ro_mol::*; mod rw_mol; pub use rw_mol::*; + +mod atom_ref; +pub use atom_ref::*; +mod bond; +pub use bond::*; +mod conformer; +pub use conformer::*; diff --git a/src/graphmol/mol_ops.rs b/src/graphmol/mol_ops.rs index 774cf85..dce4e46 100644 --- a/src/graphmol/mol_ops.rs +++ b/src/graphmol/mol_ops.rs @@ -1,10 +1,11 @@ -use cxx::SharedPtr; +use cxx::UniquePtr; use rdkit_sys::ro_mol_ffi as ro_mol; use crate::{ROMol, RWMol}; #[derive(Debug, PartialEq)] pub enum MolSanitizeException { + Other { kind: String }, MolSanitizeException, AtomSanitizeException { atom_idx: u32 }, KekulizeException, // todo don't support the vec return type just yet @@ -13,52 +14,67 @@ pub enum MolSanitizeException { } pub fn detect_chemistry_problems(mol: &ROMol) -> Vec { - let problems = rdkit_sys::ro_mol_ffi::detect_chemistry_problems(&mol.ptr); + try_detect_chemistry_problems(mol).expect("RDKit chemistry problem detection failed") +} + +pub fn try_detect_chemistry_problems( + mol: &ROMol, +) -> Result, cxx::Exception> { + let problems = ro_mol::detect_chemistry_problems(&mol.ptr)?; problems .iter() - .map(|p| { - let type_ = ro_mol::mol_sanitize_exception_type(p); - match type_.as_str() { + .map(|problem| { + let kind = ro_mol::mol_sanitize_exception_type(problem)?; + Ok(match kind.as_str() { "MolSanitizeException" => MolSanitizeException::MolSanitizeException, - "AtomSanitizeException" => { - let atom_idx = ro_mol::atom_sanitize_exception_get_atom_idx(p); - MolSanitizeException::AtomSanitizeException { atom_idx } - } + "AtomSanitizeException" => MolSanitizeException::AtomSanitizeException { + atom_idx: ro_mol::atom_sanitize_exception_get_atom_idx(problem)?, + }, "KekulizeException" => MolSanitizeException::KekulizeException, - "AtomKekulizeException" => { - let atom_idx = ro_mol::atom_sanitize_exception_get_atom_idx(p); - MolSanitizeException::AtomKekulizeException { atom_idx } - } - "AtomValenceException" => { - let atom_idx = ro_mol::atom_sanitize_exception_get_atom_idx(p); - MolSanitizeException::AtomValenceException { atom_idx } - } - _ => panic!("unsupported exception flavor"), - } + "AtomKekulizeException" => MolSanitizeException::AtomKekulizeException { + atom_idx: ro_mol::atom_sanitize_exception_get_atom_idx(problem)?, + }, + "AtomValenceException" => MolSanitizeException::AtomValenceException { + atom_idx: ro_mol::atom_sanitize_exception_get_atom_idx(problem)?, + }, + _ => MolSanitizeException::Other { kind }, + }) }) .collect() } pub fn add_hs(mol: &ROMol, explicit_only: bool, add_coords: bool, add_residue_info: bool) -> ROMol { - let ptr = rdkit_sys::mol_ops_ffi::add_hs(&mol.ptr, explicit_only, add_coords, add_residue_info); - ROMol { ptr } + try_add_hs(mol, explicit_only, add_coords, add_residue_info) + .expect("RDKit hydrogen addition failed") +} + +pub fn try_add_hs( + mol: &ROMol, + explicit_only: bool, + add_coords: bool, + add_residue_info: bool, +) -> Result { + Ok(ROMol { + ptr: rdkit_sys::mol_ops_ffi::add_hs(&mol.ptr, explicit_only, add_coords, add_residue_info)?, + }) +} + +pub fn remove_hs(mol: &ROMol, params: &RemoveHsParameters, sanitize: bool) -> ROMol { + try_remove_hs(mol, params, sanitize).expect("RDKit hydrogen removal failed") } -pub fn remove_hs( - ro_mol: &ROMol, - remove_hs_parameters: &RemoveHsParameters, +pub fn try_remove_hs( + mol: &ROMol, + params: &RemoveHsParameters, sanitize: bool, -) -> ROMol { - let ptr = rdkit_sys::mol_ops_ffi::remove_hs_parameters( - &ro_mol.ptr, - &remove_hs_parameters.ptr, - sanitize, - ); - ROMol { ptr } +) -> Result { + Ok(ROMol { + ptr: rdkit_sys::mol_ops_ffi::remove_hs_parameters(&mol.ptr, ¶ms.ptr, sanitize)?, + }) } pub struct RemoveHsParameters { - ptr: SharedPtr, + ptr: UniquePtr, } impl Default for RemoveHsParameters { @@ -69,143 +85,177 @@ impl Default for RemoveHsParameters { impl RemoveHsParameters { pub fn new() -> Self { - let ptr = rdkit_sys::mol_ops_ffi::new_remove_hs_parameters(); + let ptr = + rdkit_sys::mol_ops_ffi::new_remove_hs_parameters().expect("RDKit operation failed"); RemoveHsParameters { ptr } } pub fn get_remove_degree_zero(&self) -> bool { - rdkit_sys::mol_ops_ffi::get_remove_degree_zero(&self.ptr) + rdkit_sys::mol_ops_ffi::get_remove_degree_zero(&self.ptr).expect("RDKit operation failed") } pub fn set_remove_degree_zero(&mut self, what: bool) { - rdkit_sys::mol_ops_ffi::set_remove_degree_zero(&mut self.ptr, what) + rdkit_sys::mol_ops_ffi::set_remove_degree_zero(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn get_remove_higher_degrees(&self) -> bool { rdkit_sys::mol_ops_ffi::get_remove_higher_degrees(&self.ptr) + .expect("RDKit operation failed") } pub fn set_remove_higher_degrees(&mut self, what: bool) { - rdkit_sys::mol_ops_ffi::set_remove_higher_degrees(&mut self.ptr, what) + rdkit_sys::mol_ops_ffi::set_remove_higher_degrees(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn get_remove_only_h_neighbors(&self) -> bool { rdkit_sys::mol_ops_ffi::get_remove_only_h_neighbors(&self.ptr) + .expect("RDKit operation failed") } pub fn set_remove_only_h_neighbors(&mut self, what: bool) { - rdkit_sys::mol_ops_ffi::set_remove_only_h_neighbors(&mut self.ptr, what) + rdkit_sys::mol_ops_ffi::set_remove_only_h_neighbors(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn get_remove_isotopes(&self) -> bool { - rdkit_sys::mol_ops_ffi::get_remove_isotopes(&self.ptr) + rdkit_sys::mol_ops_ffi::get_remove_isotopes(&self.ptr).expect("RDKit operation failed") } pub fn set_remove_isotopes(&mut self, what: bool) { - rdkit_sys::mol_ops_ffi::set_remove_isotopes(&mut self.ptr, what) + rdkit_sys::mol_ops_ffi::set_remove_isotopes(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn get_remove_and_track_isotopes(&self) -> bool { rdkit_sys::mol_ops_ffi::get_remove_and_track_isotopes(&self.ptr) + .expect("RDKit operation failed") } pub fn set_remove_and_track_isotopes(&mut self, what: bool) { - rdkit_sys::mol_ops_ffi::set_remove_and_track_isotopes(&mut self.ptr, what) + rdkit_sys::mol_ops_ffi::set_remove_and_track_isotopes(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn get_remove_dummy_neighbors(&self) -> bool { rdkit_sys::mol_ops_ffi::get_remove_dummy_neighbors(&self.ptr) + .expect("RDKit operation failed") } pub fn set_remove_dummy_neighbors(&mut self, what: bool) { - rdkit_sys::mol_ops_ffi::set_remove_dummy_neighbors(&mut self.ptr, what) + rdkit_sys::mol_ops_ffi::set_remove_dummy_neighbors(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn get_remove_defining_bond_stereo(&self) -> bool { rdkit_sys::mol_ops_ffi::get_remove_defining_bond_stereo(&self.ptr) + .expect("RDKit operation failed") } pub fn set_remove_defining_bond_stereo(&mut self, what: bool) { - rdkit_sys::mol_ops_ffi::set_remove_defining_bond_stereo(&mut self.ptr, what) + rdkit_sys::mol_ops_ffi::set_remove_defining_bond_stereo(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn get_remove_with_wedged_bond(&self) -> bool { rdkit_sys::mol_ops_ffi::get_remove_with_wedged_bond(&self.ptr) + .expect("RDKit operation failed") } pub fn set_remove_with_wedged_bond(&mut self, what: bool) { - rdkit_sys::mol_ops_ffi::set_remove_with_wedged_bond(&mut self.ptr, what) + rdkit_sys::mol_ops_ffi::set_remove_with_wedged_bond(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn get_remove_with_query(&self) -> bool { - rdkit_sys::mol_ops_ffi::get_remove_with_query(&self.ptr) + rdkit_sys::mol_ops_ffi::get_remove_with_query(&self.ptr).expect("RDKit operation failed") } pub fn set_remove_with_query(&mut self, what: bool) { - rdkit_sys::mol_ops_ffi::set_remove_with_query(&mut self.ptr, what) + rdkit_sys::mol_ops_ffi::set_remove_with_query(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn get_remove_mapped(&self) -> bool { - rdkit_sys::mol_ops_ffi::get_remove_mapped(&self.ptr) + rdkit_sys::mol_ops_ffi::get_remove_mapped(&self.ptr).expect("RDKit operation failed") } pub fn set_remove_mapped(&mut self, what: bool) { - rdkit_sys::mol_ops_ffi::set_remove_mapped(&mut self.ptr, what) + rdkit_sys::mol_ops_ffi::set_remove_mapped(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn get_remove_in_s_groups(&self) -> bool { - rdkit_sys::mol_ops_ffi::get_remove_in_s_groups(&self.ptr) + rdkit_sys::mol_ops_ffi::get_remove_in_s_groups(&self.ptr).expect("RDKit operation failed") } pub fn set_remove_in_s_groups(&mut self, what: bool) { - rdkit_sys::mol_ops_ffi::set_remove_in_s_groups(&mut self.ptr, what) + rdkit_sys::mol_ops_ffi::set_remove_in_s_groups(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn get_show_warnings(&self) -> bool { - rdkit_sys::mol_ops_ffi::get_show_warnings(&self.ptr) + rdkit_sys::mol_ops_ffi::get_show_warnings(&self.ptr).expect("RDKit operation failed") } pub fn set_show_warnings(&mut self, what: bool) { - rdkit_sys::mol_ops_ffi::set_show_warnings(&mut self.ptr, what) + rdkit_sys::mol_ops_ffi::set_show_warnings(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn get_remove_nonimplicit(&self) -> bool { - rdkit_sys::mol_ops_ffi::get_remove_nonimplicit(&self.ptr) + rdkit_sys::mol_ops_ffi::get_remove_nonimplicit(&self.ptr).expect("RDKit operation failed") } pub fn set_remove_nonimplicit(&mut self, what: bool) { - rdkit_sys::mol_ops_ffi::set_remove_nonimplicit(&mut self.ptr, what) + rdkit_sys::mol_ops_ffi::set_remove_nonimplicit(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn get_update_explicit_count(&self) -> bool { rdkit_sys::mol_ops_ffi::get_update_explicit_count(&self.ptr) + .expect("RDKit operation failed") } pub fn set_update_explicit_count(&mut self, what: bool) { - rdkit_sys::mol_ops_ffi::set_update_explicit_count(&mut self.ptr, what) + rdkit_sys::mol_ops_ffi::set_update_explicit_count(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn get_remove_hydrides(&self) -> bool { - rdkit_sys::mol_ops_ffi::get_remove_hydrides(&self.ptr) + rdkit_sys::mol_ops_ffi::get_remove_hydrides(&self.ptr).expect("RDKit operation failed") } pub fn set_remove_hydrides(&mut self, what: bool) { - rdkit_sys::mol_ops_ffi::set_remove_hydrides(&mut self.ptr, what) + rdkit_sys::mol_ops_ffi::set_remove_hydrides(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn get_remove_nontetrahedral_neighbors(&self) -> bool { rdkit_sys::mol_ops_ffi::get_remove_nontetrahedral_neighbors(&self.ptr) + .expect("RDKit operation failed") } pub fn set_remove_nontetrahedral_neighbors(&mut self, what: bool) { - rdkit_sys::mol_ops_ffi::set_remove_nontetrahedral_neighbors(&mut self.ptr, what) + rdkit_sys::mol_ops_ffi::set_remove_nontetrahedral_neighbors(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } } pub fn set_hybridization(romol: &mut ROMol) { - rdkit_sys::mol_ops_ffi::romol_set_hybridization(&mut romol.ptr); + rdkit_sys::mol_ops_ffi::romol_set_hybridization(romol.ptr.pin_mut()) + .expect("RDKit operation failed"); } pub fn clean_up(rw_mol: &mut RWMol) { - rdkit_sys::mol_ops_ffi::clean_up(&mut rw_mol.ptr); + rdkit_sys::mol_ops_ffi::clean_up(rw_mol.ptr.pin_mut()).expect("RDKit operation failed"); +} + +pub fn try_set_hybridization(mol: &mut ROMol) -> Result<(), cxx::Exception> { + rdkit_sys::mol_ops_ffi::romol_set_hybridization(mol.ptr.pin_mut()) +} + +pub fn try_clean_up(mol: &mut RWMol) -> Result<(), cxx::Exception> { + rdkit_sys::mol_ops_ffi::clean_up(mol.ptr.pin_mut()) } diff --git a/src/graphmol/ro_mol.rs b/src/graphmol/ro_mol.rs index bcdd30c..f93880f 100644 --- a/src/graphmol/ro_mol.rs +++ b/src/graphmol/ro_mol.rs @@ -3,10 +3,10 @@ use std::fmt::{Debug, Formatter}; use cxx::let_cxx_string; use rdkit_sys::*; -use crate::{Atom, Fingerprint, RWMol}; +use crate::{Atom, AtomRef, Bond, Conformer, ConformerMut, Fingerprint, RWMol}; pub struct ROMol { - pub(crate) ptr: cxx::SharedPtr, + pub(crate) ptr: cxx::UniquePtr, } unsafe impl Send for ROMol {} @@ -21,17 +21,13 @@ pub enum ROMolError { impl ROMol { pub fn from_smiles(smiles: &str) -> Result { - let_cxx_string!(smiles_cxx_string = smiles); - let ptr = ro_mol_ffi::smiles_to_mol(&smiles_cxx_string); - match ptr { - Ok(ptr) => { - if ptr.is_null() { - Err(ROMolError::UnknownConversionError) - } else { - Ok(ROMol { ptr }) - } - } - Err(e) => Err(ROMolError::ConversionException(e.to_string())), + let_cxx_string!(smiles = smiles); + let ptr = ro_mol_ffi::smiles_to_mol(&smiles) + .map_err(|e| ROMolError::ConversionException(e.to_string()))?; + if ptr.is_null() { + Err(ROMolError::UnknownConversionError) + } else { + Ok(Self { ptr }) } } @@ -39,99 +35,222 @@ impl ROMol { smiles: &str, params: &SmilesParserParams, ) -> Result { - let_cxx_string!(smiles_cxx_string = smiles); - - // There is the risk that ptr is null, this is from rdkit c++ - let ptr = ro_mol_ffi::smiles_to_mol_with_params(&smiles_cxx_string, ¶ms.ptr) - .map_err(|except| except.what().to_owned())?; - + let_cxx_string!(smiles = smiles); + let ptr = ro_mol_ffi::smiles_to_mol_with_params(&smiles, ¶ms.ptr) + .map_err(|e| e.to_string())?; if ptr.is_null() { - let informative_string = format!( - "smiles_to_mol_with_params failed on inputs SMILES: `{}`, SmilesParserParams", - smiles, - params.get_sanitize() - ); - Err(informative_string) + Err("could not convert SMILES to molecule".into()) } else { Ok(Self { ptr }) } } - pub fn as_smiles(&self) -> String { + pub fn try_as_smiles(&self) -> Result { ro_mol_ffi::mol_to_smiles(&self.ptr) } - pub fn to_molblock(&self) -> String { + pub fn as_smiles(&self) -> String { + self.try_as_smiles().expect("RDKit SMILES writing failed") + } + + pub fn try_to_molblock(&self) -> Result { ro_mol_ffi::mol_to_molblock(&self.ptr) } + pub fn to_molblock(&self) -> String { + self.try_to_molblock() + .expect("RDKit mol block writing failed") + } + + pub fn try_as_rw_mol(&self, quick_copy: bool, conf_id: i32) -> Result { + Ok(RWMol { + ptr: rw_mol_ffi::rw_mol_from_ro_mol(&self.ptr, quick_copy, conf_id)?, + }) + } + pub fn as_rw_mol(&self, quick_copy: bool, conf_id: i32) -> RWMol { - let ptr = rw_mol_ffi::rw_mol_from_ro_mol(&self.ptr, quick_copy, conf_id); - RWMol { ptr } + self.try_as_rw_mol(quick_copy, conf_id) + .expect("RDKit molecule copy failed") + } + + pub fn try_clone(&self) -> Result { + Ok(Self { + ptr: ro_mol_ffi::copy_mol(&self.ptr)?, + }) + } + + pub fn try_rdk_fingerprint(&self) -> Result { + Fingerprint::try_new(fingerprint_ffi::rdk_fingerprint_mol(&self.ptr)?) } pub fn rdk_fingerprint(&self) -> Fingerprint { - let ptr = fingerprint_ffi::rdk_fingerprint_mol(&self.ptr); - Fingerprint::new(ptr) + self.try_rdk_fingerprint() + .expect("RDKit fingerprint failed") + } + + pub fn try_pattern_fingerprint(&self) -> Result { + Fingerprint::try_new(fingerprint_ffi::pattern_fingerprint_mol(&self.ptr)?) } pub fn pattern_fingerprint(&self) -> Fingerprint { - let ptr = fingerprint_ffi::pattern_fingerprint_mol(&self.ptr); - Fingerprint::new(ptr) + self.try_pattern_fingerprint() + .expect("RDKit fingerprint failed") + } + + pub fn try_morgan_fingerprint(&self) -> Result { + Fingerprint::try_new(fingerprint_ffi::morgan_fingerprint_mol(&self.ptr)?) } pub fn morgan_fingerprint(&self) -> Fingerprint { - let ptr = fingerprint_ffi::morgan_fingerprint_mol(&self.ptr); - Fingerprint::new(ptr) + self.try_morgan_fingerprint() + .expect("RDKit fingerprint failed") + } + + pub fn morgan_fingerprint_with_params( + &self, + radius: u32, + n_bits: u32, + ) -> Result { + Fingerprint::try_new(fingerprint_ffi::morgan_fingerprint_mol_with_params( + &self.ptr, radius, n_bits, + )?) + } + + pub fn rdk_fingerprint_with_params( + &self, + min_path: u32, + max_path: u32, + n_bits: u32, + ) -> Result { + Fingerprint::try_new(fingerprint_ffi::rdk_fingerprint_mol_with_params( + &self.ptr, min_path, max_path, n_bits, + )?) + } + + pub fn pattern_fingerprint_with_params( + &self, + n_bits: u32, + ) -> Result { + Fingerprint::try_new(fingerprint_ffi::pattern_fingerprint_mol_with_params( + &self.ptr, n_bits, + )?) + } + + pub fn maccs_fingerprint(&self) -> Result { + Fingerprint::try_new(fingerprint_ffi::maccs_fingerprint_mol(&self.ptr)?) } pub fn num_atoms(&self, only_explicit: bool) -> u32 { - ro_mol_ffi::get_num_atoms(&self.ptr, only_explicit) + ro_mol_ffi::get_num_atoms(&self.ptr, only_explicit).expect("RDKit atom count failed") + } + + pub fn atom_ref(&self, idx: u32) -> Result, cxx::Exception> { + Ok(AtomRef::from_ptr(ro_mol_ffi::get_atom_ref(&self.ptr, idx)?)) + } + + pub fn atoms(&self) -> impl ExactSizeIterator> + '_ { + (0..self.num_atoms(true)).map(|idx| self.atom_ref(idx).expect("RDKit atom access failed")) + } + + pub fn try_atom_with_idx(&mut self, idx: u32) -> Result, cxx::Exception> { + Ok(Atom::from_ptr(ro_mol_ffi::get_atom_with_idx( + self.ptr.pin_mut(), + idx, + )?)) } - pub fn atom_with_idx(&mut self, idx: u32) -> Atom { - let ptr = ro_mol_ffi::get_atom_with_idx(&mut self.ptr, idx); - Atom::from_ptr(ptr) + pub fn atom_with_idx(&mut self, idx: u32) -> Atom<'_> { + self.try_atom_with_idx(idx) + .expect("RDKit atom index out of range") + } + + pub fn num_bonds(&self) -> u32 { + bond_ffi::get_num_bonds(&self.ptr, true).expect("RDKit bond count failed") + } + + pub fn bond(&self, idx: u32) -> Result, cxx::Exception> { + Ok(Bond::from_ptr(bond_ffi::get_bond_with_idx(&self.ptr, idx)?)) + } + + pub fn bonds(&self) -> impl ExactSizeIterator> + '_ { + (0..self.num_bonds()).map(|idx| self.bond(idx).expect("RDKit bond access failed")) + } + + pub fn bond_between_atoms( + &self, + begin: u32, + end: u32, + ) -> Result>, cxx::Exception> { + let idx = bond_ffi::get_bond_idx_between_atoms(&self.ptr, begin, end)?; + if idx < 0 { + Ok(None) + } else { + self.bond(idx as u32).map(Some) + } + } + + pub fn try_update_property_cache(&mut self, strict: bool) -> Result<(), cxx::Exception> { + ro_mol_ffi::ro_mol_update_property_cache(self.ptr.pin_mut(), strict) } pub fn update_property_cache(&mut self, strict: bool) { - ro_mol_ffi::ro_mol_update_property_cache(&mut self.ptr, strict) + self.try_update_property_cache(strict) + .expect("RDKit property cache update failed") + } + + pub fn compute_2d_coords(&mut self) -> Result { + conformer_ffi::compute_2d_coords(self.ptr.pin_mut()) + } + + pub fn num_conformers(&self) -> u32 { + conformer_ffi::get_num_conformers(&self.ptr).expect("RDKit conformer count failed") + } + + pub fn conformer(&self, id: i32) -> Result, cxx::Exception> { + Ok(Conformer { + ptr: conformer_ffi::get_conformer(&self.ptr, id)?, + }) + } + + pub fn conformer_mut(&mut self, id: i32) -> Result, cxx::Exception> { + Ok(ConformerMut { + ptr: conformer_ffi::get_conformer_mut(self.ptr.pin_mut(), id)?, + }) } } impl Debug for ROMol { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - let smiles = self.as_smiles(); - f.debug_tuple("ROMol").field(&smiles).finish() + f.debug_tuple("ROMol").field(&self.try_as_smiles()).finish() } } impl Clone for ROMol { fn clone(&self) -> Self { - ROMol { - ptr: ro_mol_ffi::copy_mol(&self.ptr), - } + self.try_clone().expect("RDKit molecule copy failed") } } pub struct SmilesParserParams { - pub(crate) ptr: cxx::SharedPtr, + pub(crate) ptr: cxx::UniquePtr, } impl SmilesParserParams { pub fn set_sanitize(&mut self, value: bool) { - ro_mol_ffi::smiles_parser_params_set_sanitize(&self.ptr, value); + ro_mol_ffi::smiles_parser_params_set_sanitize(self.ptr.pin_mut(), value) + .expect("RDKit parser parameter update failed"); } pub fn get_sanitize(&self) -> bool { ro_mol_ffi::smiles_parser_params_get_sanitize(&self.ptr) + .expect("RDKit parser parameter access failed") } } impl Default for SmilesParserParams { fn default() -> Self { - SmilesParserParams { - ptr: ro_mol_ffi::new_smiles_parser_params(), + Self { + ptr: ro_mol_ffi::new_smiles_parser_params().expect("RDKit parser allocation failed"), } } } diff --git a/src/graphmol/rw_mol.rs b/src/graphmol/rw_mol.rs index 6467120..7dc6125 100644 --- a/src/graphmol/rw_mol.rs +++ b/src/graphmol/rw_mol.rs @@ -1,71 +1,195 @@ use std::fmt::Formatter; -use cxx::{let_cxx_string, SharedPtr}; +use cxx::{let_cxx_string, UniquePtr}; use rdkit_sys::*; -use crate::ROMol; +use crate::{Atom, AtomRef, Bond, BondType, Conformer, ConformerMut, ROMol}; pub struct RWMol { - pub(crate) ptr: SharedPtr, + pub(crate) ptr: UniquePtr, +} + +unsafe impl Send for RWMol {} + +#[derive(Debug, PartialEq, thiserror::Error)] +pub enum RWMolError { + #[error("could not parse molecule: {0}")] + ConversionException(String), + #[error("parser returned no molecule")] + UnknownConversionError, } impl RWMol { - pub fn from_mol_block( + pub fn new() -> Self { + Self::try_new().expect("RDKit molecule allocation failed") + } + + pub fn try_new() -> Result { + Ok(Self { + ptr: rw_mol_ffi::new_rw_mol()?, + }) + } + + pub fn try_from_mol_block( mol_block: &str, sanitize: bool, remove_hs: bool, strict_parsing: bool, - ) -> Option { + ) -> Result { let_cxx_string!(mol_block = mol_block); - let ptr = - rw_mol_ffi::rw_mol_from_mol_block(&mol_block, sanitize, remove_hs, strict_parsing); - + rw_mol_ffi::rw_mol_from_mol_block(&mol_block, sanitize, remove_hs, strict_parsing) + .map_err(|e| RWMolError::ConversionException(e.to_string()))?; if ptr.is_null() { - None + Err(RWMolError::UnknownConversionError) } else { - Some(RWMol { ptr }) + Ok(Self { ptr }) } } + pub fn from_mol_block( + mol_block: &str, + sanitize: bool, + remove_hs: bool, + strict_parsing: bool, + ) -> Option { + Self::try_from_mol_block(mol_block, sanitize, remove_hs, strict_parsing).ok() + } + + pub fn try_as_smiles(&self) -> Result { + ro_mol_ffi::mol_to_smiles(rw_mol_ffi::rw_mol_as_ro_mol(&self.ptr)) + } + pub fn as_smiles(&self) -> String { - let cast_ptr = unsafe { - std::mem::transmute::< - SharedPtr, - SharedPtr, - >(self.ptr.clone()) - }; - ro_mol_ffi::mol_to_smiles(&cast_ptr) + self.try_as_smiles().expect("RDKit SMILES writing failed") } pub fn to_ro_mol(self) -> ROMol { - let ptr = unsafe { - std::mem::transmute::< - SharedPtr, - SharedPtr, - >(self.ptr) - }; - ROMol { ptr } + ROMol { + ptr: rw_mol_ffi::rw_mol_to_ro_mol(self.ptr).expect("RDKit molecule conversion failed"), + } } - pub fn from_smarts(smarts: &str) -> Result> { + pub fn from_smarts(smarts: &str) -> Result { let_cxx_string!(smarts = smarts); + let ptr = rw_mol_ffi::smarts_to_mol(&smarts) + .map_err(|e| RWMolError::ConversionException(e.to_string()))?; + if ptr.is_null() { + Err(RWMolError::UnknownConversionError) + } else { + Ok(Self { ptr }) + } + } + + pub fn try_clone(&self) -> Result { + Ok(Self { + ptr: rw_mol_ffi::rw_mol_from_rw_mol(&self.ptr)?, + }) + } + + pub fn num_atoms(&self, only_explicit: bool) -> u32 { + ro_mol_ffi::get_num_atoms(rw_mol_ffi::rw_mol_as_ro_mol(&self.ptr), only_explicit) + .expect("RDKit atom count failed") + } + + pub fn atom_ref(&self, idx: u32) -> Result, cxx::Exception> { + Ok(AtomRef::from_ptr(ro_mol_ffi::get_atom_ref( + rw_mol_ffi::rw_mol_as_ro_mol(&self.ptr), + idx, + )?)) + } + + pub fn atoms(&self) -> impl ExactSizeIterator> + '_ { + (0..self.num_atoms(true)).map(|idx| self.atom_ref(idx).expect("RDKit atom access failed")) + } + + pub fn try_atom_with_idx(&mut self, idx: u32) -> Result, cxx::Exception> { + Ok(Atom::from_ptr(ro_mol_ffi::get_atom_with_idx( + rw_mol_ffi::rw_mol_as_ro_mol_mut(self.ptr.pin_mut()), + idx, + )?)) + } + + pub fn atom_with_idx(&mut self, idx: u32) -> Atom<'_> { + self.try_atom_with_idx(idx) + .expect("RDKit atom index out of range") + } + + pub fn num_bonds(&self) -> u32 { + bond_ffi::get_num_bonds(rw_mol_ffi::rw_mol_as_ro_mol(&self.ptr), true) + .expect("RDKit bond count failed") + } + + pub fn bond(&self, idx: u32) -> Result, cxx::Exception> { + Ok(Bond::from_ptr(bond_ffi::get_bond_with_idx( + rw_mol_ffi::rw_mol_as_ro_mol(&self.ptr), + idx, + )?)) + } + + pub fn bonds(&self) -> impl ExactSizeIterator> + '_ { + (0..self.num_bonds()).map(|idx| self.bond(idx).expect("RDKit bond access failed")) + } + + pub fn add_atom(&mut self, atomic_num: u32) -> Result { + rw_mol_ffi::rw_mol_add_atom(self.ptr.pin_mut(), atomic_num) + } + + pub fn add_bond( + &mut self, + begin: u32, + end: u32, + kind: BondType, + ) -> Result { + rw_mol_ffi::rw_mol_add_bond(self.ptr.pin_mut(), begin, end, kind.repr) + } + + pub fn remove_atom(&mut self, idx: u32) -> Result<(), cxx::Exception> { + rw_mol_ffi::rw_mol_remove_atom(self.ptr.pin_mut(), idx) + } + + pub fn remove_bond(&mut self, begin: u32, end: u32) -> Result<(), cxx::Exception> { + rw_mol_ffi::rw_mol_remove_bond(self.ptr.pin_mut(), begin, end) + } + + pub fn sanitize(&mut self) -> Result<(), cxx::Exception> { + rw_mol_ffi::rw_mol_sanitize(self.ptr.pin_mut()) + } + + pub fn compute_2d_coords(&mut self) -> Result { + conformer_ffi::compute_2d_coords(rw_mol_ffi::rw_mol_as_ro_mol_mut(self.ptr.pin_mut())) + } + + pub fn conformer(&self, id: i32) -> Result, cxx::Exception> { + Ok(Conformer { + ptr: conformer_ffi::get_conformer(rw_mol_ffi::rw_mol_as_ro_mol(&self.ptr), id)?, + }) + } + + pub fn conformer_mut(&mut self, id: i32) -> Result, cxx::Exception> { + Ok(ConformerMut { + ptr: conformer_ffi::get_conformer_mut( + rw_mol_ffi::rw_mol_as_ro_mol_mut(self.ptr.pin_mut()), + id, + )?, + }) + } +} - let ptr = rdkit_sys::rw_mol_ffi::smarts_to_mol(&smarts)?; - Ok(RWMol { ptr }) +impl Default for RWMol { + fn default() -> Self { + Self::new() } } impl Clone for RWMol { fn clone(&self) -> Self { - let ptr = rw_mol_ffi::rw_mol_from_rw_mol(&self.ptr); - RWMol { ptr } + self.try_clone().expect("RDKit molecule copy failed") } } impl std::fmt::Debug for RWMol { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - let smiles = self.as_smiles(); - f.debug_tuple("RWMol").field(&smiles).finish() + f.debug_tuple("RWMol").field(&self.try_as_smiles()).finish() } } diff --git a/src/lib.rs b/src/lib.rs index 01adaa4..579f4e1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -21,3 +21,6 @@ pub use substruct_match::*; mod verbose_file_parsers; pub use verbose_file_parsers::*; + +mod scaffold_network; +pub use scaffold_network::*; diff --git a/src/mol_standardize.rs b/src/mol_standardize.rs index b0db9c9..9e49768 100644 --- a/src/mol_standardize.rs +++ b/src/mol_standardize.rs @@ -1,128 +1,140 @@ -use cxx::SharedPtr; +use cxx::UniquePtr; +use rdkit_sys::mol_standardize_ffi as ffi; use crate::{ROMol, RWMol}; pub struct CleanupParameters { - pub(crate) ptr: SharedPtr, + pub(crate) ptr: UniquePtr, } impl Default for CleanupParameters { fn default() -> Self { - CleanupParameters { - ptr: rdkit_sys::mol_standardize_ffi::default_cleanup_parameters(), + Self { + ptr: ffi::default_cleanup_parameters().expect("RDKit cleanup allocation failed"), } } } pub struct TautomerEnumerator { - pub(crate) ptr: SharedPtr, + pub(crate) ptr: UniquePtr, } impl Default for TautomerEnumerator { fn default() -> Self { - TautomerEnumerator::new() + Self::new() } } impl TautomerEnumerator { pub fn new() -> Self { - let ptr = rdkit_sys::mol_standardize_ffi::tautomer_enumerator(); + Self::try_new().expect("RDKit tautomer enumerator allocation failed") + } - TautomerEnumerator { ptr } + pub fn try_new() -> Result { + Ok(Self { + ptr: ffi::tautomer_enumerator()?, + }) } - pub fn enumerate(&self, ro_mol: &crate::ROMol) -> TautomerEnumeratorResult { - let t_enumerator_result = - rdkit_sys::mol_standardize_ffi::tautomer_enumerate(&self.ptr, &ro_mol.ptr); - let size = rdkit_sys::mol_standardize_ffi::tautomer_enumerator_result_tautomers_size( - &t_enumerator_result, - ) as usize; - - TautomerEnumeratorResult { - pos: 0, - size, - t_enumerator_result, - } + pub fn enumerate(&self, mol: &ROMol) -> TautomerEnumeratorResult { + self.try_enumerate(mol) + .expect("RDKit tautomer enumeration failed") } - pub fn canonicalize(&self, ro_mol: &crate::ROMol) -> Result { - let canonical_mol_ptr = rdkit_sys::mol_standardize_ffi::tautomer_enumerator_canonicalize( - &self.ptr, - &ro_mol.ptr, - ); - Ok(crate::ROMol { - ptr: canonical_mol_ptr?, + pub fn try_enumerate(&self, mol: &ROMol) -> Result { + let ptr = ffi::tautomer_enumerate(&self.ptr, &mol.ptr)?; + let size = ffi::tautomer_enumerator_result_tautomers_size(&ptr)?; + Ok(TautomerEnumeratorResult { ptr, pos: 0, size }) + } + + pub fn canonicalize(&self, mol: &ROMol) -> Result { + Ok(ROMol { + ptr: ffi::tautomer_enumerator_canonicalize(&self.ptr, &mol.ptr)?, }) } } pub struct TautomerEnumeratorResult { - // t_enumerator: SharedPtr, - pub(crate) t_enumerator_result: - SharedPtr, + ptr: UniquePtr, pos: usize, size: usize, } +impl TautomerEnumeratorResult { + pub fn get(&self, idx: usize) -> Result { + Ok(ROMol { + ptr: ffi::tautomer_enumerator_result_tautomers_at(&self.ptr, idx)?, + }) + } + + pub fn try_next(&mut self) -> Result, cxx::Exception> { + if self.pos == self.size { + return Ok(None); + } + let next = self.get(self.pos)?; + self.pos += 1; + Ok(Some(next)) + } +} + impl Iterator for TautomerEnumeratorResult { - type Item = crate::ROMol; + type Item = ROMol; fn next(&mut self) -> Option { - if self.pos >= self.size { - None - } else { - let next = rdkit_sys::mol_standardize_ffi::tautomer_enumerator_result_tautomers_at( - &self.t_enumerator_result, - self.pos, - ); - if next.is_null() { - log::warn!( - "got a null ptr from tautomer_enumerator_result->at({})", - self.pos - ); - None - } else { - self.pos += 1; - Some(crate::ROMol { ptr: next }) - } - } + self.try_next().expect("RDKit tautomer copy failed") } fn size_hint(&self) -> (usize, Option) { - let size = rdkit_sys::mol_standardize_ffi::tautomer_enumerator_result_tautomers_size( - &self.t_enumerator_result, - ); - (size as usize, Some(size as usize)) + let remaining = self.size - self.pos; + (remaining, Some(remaining)) } } -pub fn fragment_parent( - rw_mol: &RWMol, - cleanup_params: &CleanupParameters, +impl ExactSizeIterator for TautomerEnumeratorResult {} +impl std::iter::FusedIterator for TautomerEnumeratorResult {} + +pub fn try_fragment_parent( + mol: &RWMol, + params: &CleanupParameters, skip_standardize: bool, -) -> RWMol { - let ptr = rdkit_sys::mol_standardize_ffi::fragment_parent( - &rw_mol.ptr, - &cleanup_params.ptr, - skip_standardize, - ); - RWMol { ptr } +) -> Result { + Ok(RWMol { + ptr: ffi::fragment_parent(&mol.ptr, ¶ms.ptr, skip_standardize)?, + }) +} + +pub fn fragment_parent(mol: &RWMol, params: &CleanupParameters, skip_standardize: bool) -> RWMol { + try_fragment_parent(mol, params, skip_standardize).expect("RDKit fragment parent failed") +} + +pub fn normalize(mol: &RWMol, params: &CleanupParameters) -> Result { + Ok(RWMol { + ptr: ffi::normalize(&mol.ptr, ¶ms.ptr)?, + }) } pub struct Uncharger { - pub(crate) ptr: SharedPtr, + ptr: UniquePtr, } impl Uncharger { - pub fn new(standardize: bool) -> Self { - Uncharger { - ptr: rdkit_sys::mol_standardize_ffi::new_uncharger(standardize), - } + pub fn new(canonical: bool) -> Self { + Self::try_new(canonical).expect("RDKit uncharger allocation failed") } - pub fn uncharge(&self, mol: &ROMol) -> ROMol { - ROMol { - ptr: rdkit_sys::mol_standardize_ffi::uncharger_uncharge(&self.ptr, &mol.ptr), - } + pub fn try_new(canonical: bool) -> Result { + Ok(Self { + ptr: ffi::new_uncharger(canonical)?, + }) + } + + pub fn uncharge(&mut self, mol: &ROMol) -> ROMol { + self.try_uncharge(mol).expect("RDKit uncharging failed") + } + + pub fn try_uncharge(&mut self, mol: &ROMol) -> Result { + Ok(ROMol { + ptr: ffi::uncharger_uncharge(self.ptr.pin_mut(), &mol.ptr)?, + }) } } diff --git a/src/periodic_table.rs b/src/periodic_table.rs index 60fc473..bbf20ee 100644 --- a/src/periodic_table.rs +++ b/src/periodic_table.rs @@ -1,132 +1,159 @@ -use cxx::{let_cxx_string, CxxVector}; -use rdkit_sys::PeriodicTableOps; +use cxx::let_cxx_string; +use rdkit_sys::{periodic_table_ffi as ffi, PeriodicTableOps}; pub struct PeriodicTable {} impl PeriodicTable { - /// Returns a vector of all stable valences. For atoms where we really don't - /// have any idea what a reasonable maximum valence is (like transition - /// metals), the vector ends with -1 - /// # Arguments - /// * `atomic_number` - The atomic number of the element - pub fn get_valence_list(atomic_number: u32) -> &'static CxxVector { - rdkit_sys::periodic_table_ffi::get_periodic_table().getValenceList(atomic_number) - } - - /// Returns the mass of the most common isotope - /// # Arguments - /// * `atom` - The symbol of the element + pub fn get_valence_list(atomic_number: u32) -> Vec { + Self::try_get_valence_list(atomic_number).expect("RDKit periodic table lookup failed") + } + + pub fn try_get_valence_list(atomic_number: u32) -> Result, cxx::Exception> { + let values = ffi::get_periodic_table()?.getValenceList(atomic_number)?; + Ok(values.iter().copied().collect()) + } + pub fn get_most_common_isotope_mass(atom: &str) -> f64 { - let_cxx_string!(atom_cxx_string = atom); - rdkit_sys::periodic_table_ffi::get_periodic_table() - .getMostCommonIsotopeMass(&atom_cxx_string) + Self::try_get_most_common_isotope_mass(atom).expect("RDKit periodic table lookup failed") + } + + pub fn try_get_most_common_isotope_mass(atom: &str) -> Result { + let_cxx_string!(atom = atom); + ffi::get_periodic_table()?.getMostCommonIsotopeMass(&atom) } - /// Returns the atomic weight of the atom pub fn get_atomic_weight(atomic_number: u32) -> f64 { - rdkit_sys::periodic_table_ffi::get_periodic_table().getAtomicWeight(atomic_number) + Self::try_get_atomic_weight(atomic_number).expect("RDKit periodic table lookup failed") + } + + pub fn try_get_atomic_weight(atomic_number: u32) -> Result { + ffi::get_periodic_table()?.getAtomicWeight(atomic_number) } - /// Returns the atomic number of the atom - /// # Arguments - /// * `atom` - The symbol of the element pub fn get_atomic_number(atom: &str) -> i32 { - let_cxx_string!(atom_cxx_string = atom); - rdkit_sys::periodic_table_ffi::get_periodic_table().getAtomicNumber(&atom_cxx_string) + Self::try_get_atomic_number(atom).expect("RDKit periodic table lookup failed") + } + + pub fn try_get_atomic_number(atom: &str) -> Result { + let_cxx_string!(atom = atom); + ffi::get_periodic_table()?.getAtomicNumber(&atom) } - /// Returns the symbol of the element - /// # Arguments - /// * `atomic_number` - The atomic number of the element pub fn get_element_symbol(atomic_number: u32) -> String { - rdkit_sys::periodic_table_ffi::getElementSymbol(atomic_number) + Self::try_get_element_symbol(atomic_number).expect("RDKit periodic table lookup failed") + } + + pub fn try_get_element_symbol(atomic_number: u32) -> Result { + ffi::getElementSymbol(atomic_number) } - /// Returns the full element name - /// # Arguments - /// * `atomic_number` - The atomic number of the element pub fn get_element_name(atomic_number: u32) -> String { - rdkit_sys::periodic_table_ffi::getElementName(atomic_number) + Self::try_get_element_name(atomic_number).expect("RDKit periodic table lookup failed") + } + + pub fn try_get_element_name(atomic_number: u32) -> Result { + ffi::getElementName(atomic_number) } - /// Returns the atom's Van der Waals radius - /// # Arguments - /// * `atomic_number` - The atomic number of the element pub fn get_radius_van_der_waals(atomic_number: u32) -> f64 { - rdkit_sys::periodic_table_ffi::get_periodic_table().getRvdw(atomic_number) + Self::try_get_radius_van_der_waals(atomic_number) + .expect("RDKit periodic table lookup failed") + } + + pub fn try_get_radius_van_der_waals(atomic_number: u32) -> Result { + ffi::get_periodic_table()?.getRvdw(atomic_number) } - /// Returns the atom's covalent radius - /// # Arguments - /// * `atomic_number` - The atomic number of the element pub fn get_radius_covalent(atomic_number: u32) -> f64 { - rdkit_sys::periodic_table_ffi::get_periodic_table().getRcovalent(atomic_number) + Self::try_get_radius_covalent(atomic_number).expect("RDKit periodic table lookup failed") + } + + pub fn try_get_radius_covalent(atomic_number: u32) -> Result { + ffi::get_periodic_table()?.getRcovalent(atomic_number) } - /// Returns the atom's bond radius - /// # Arguments - /// * `atomic_number` - The atomic number of the element pub fn get_radius_b0(atomic_number: u32) -> f64 { - rdkit_sys::periodic_table_ffi::get_periodic_table().getRb0(atomic_number) + Self::try_get_radius_b0(atomic_number).expect("RDKit periodic table lookup failed") + } + + pub fn try_get_radius_b0(atomic_number: u32) -> Result { + ffi::get_periodic_table()?.getRb0(atomic_number) } - /// Returns the atom's default valence - /// # Arguments - /// * `atomic_number` - The atomic number of the element pub fn get_default_valence(atomic_number: u32) -> i32 { - rdkit_sys::periodic_table_ffi::get_periodic_table().getDefaultValence(atomic_number) + Self::try_get_default_valence(atomic_number).expect("RDKit periodic table lookup failed") + } + + pub fn try_get_default_valence(atomic_number: u32) -> Result { + ffi::get_periodic_table()?.getDefaultValence(atomic_number) } - /// Returns the number of outer shell electrons - /// # Arguments - /// * `atomic_number` - The atomic number of the element pub fn get_n_outer_elecs(atomic_number: u32) -> i32 { - rdkit_sys::periodic_table_ffi::get_periodic_table().getNouterElecs(atomic_number) + Self::try_get_n_outer_elecs(atomic_number).expect("RDKit periodic table lookup failed") + } + + pub fn try_get_n_outer_elecs(atomic_number: u32) -> Result { + ffi::get_periodic_table()?.getNouterElecs(atomic_number) } - /// Returns the atom's most common isotope - /// # Arguments - /// * `atomic_number` - The atomic number of the element pub fn get_most_common_isotope(atomic_number: u32) -> i32 { - rdkit_sys::periodic_table_ffi::get_periodic_table().getMostCommonIsotope(atomic_number) + Self::try_get_most_common_isotope(atomic_number) + .expect("RDKit periodic table lookup failed") + } + + pub fn try_get_most_common_isotope(atomic_number: u32) -> Result { + ffi::get_periodic_table()?.getMostCommonIsotope(atomic_number) } - /// Returns the mass of the isotope - /// # Arguments - /// * `atomic_number` - The atomic number of the element - /// * `isotope` - The isotope number pub fn get_mass_for_isotope(atomic_number: u32, isotope: u32) -> f64 { - rdkit_sys::periodic_table_ffi::get_periodic_table() - .getMassForIsotope(atomic_number, isotope) + Self::try_get_mass_for_isotope(atomic_number, isotope) + .expect("RDKit periodic table lookup failed") + } + + pub fn try_get_mass_for_isotope( + atomic_number: u32, + isotope: u32, + ) -> Result { + ffi::get_periodic_table()?.getMassForIsotope(atomic_number, isotope) } - /// Returns the maximum recognized atomic number pub fn get_max_atomic_number() -> u32 { - rdkit_sys::periodic_table_ffi::get_periodic_table().getMaxAtomicNumber() + Self::try_get_max_atomic_number().expect("RDKit periodic table lookup failed") + } + + pub fn try_get_max_atomic_number() -> Result { + ffi::get_periodic_table()?.getMaxAtomicNumber() } - /// Returns the abundance of the isotope - /// # Arguments - /// * `atomic_number` - The atomic number of the element - /// * `isotope` - The isotope number pub fn get_abundance_for_isotope(atomic_number: u32, isotope: u32) -> f64 { - rdkit_sys::periodic_table_ffi::get_periodic_table() - .getAbundanceForIsotope(atomic_number, isotope) + Self::try_get_abundance_for_isotope(atomic_number, isotope) + .expect("RDKit periodic table lookup failed") + } + + pub fn try_get_abundance_for_isotope( + atomic_number: u32, + isotope: u32, + ) -> Result { + ffi::get_periodic_table()?.getAbundanceForIsotope(atomic_number, isotope) } - /// Returns true if the first atom is more electronegative than the second - /// # Arguments - /// * `atomic_number1` - The atomic number of the first element - /// * `atomic_number2` - The atomic number of the second element pub fn more_electro_negative(atomic_number1: u32, atomic_number2: u32) -> bool { - rdkit_sys::periodic_table_ffi::get_periodic_table() - .moreElectroNegative(atomic_number1, atomic_number2) + Self::try_more_electro_negative(atomic_number1, atomic_number2) + .expect("RDKit periodic table lookup failed") + } + + pub fn try_more_electro_negative( + atomic_number1: u32, + atomic_number2: u32, + ) -> Result { + ffi::get_periodic_table()?.moreElectroNegative(atomic_number1, atomic_number2) } - /// Returns the row of the periodic table - /// # Arguments - /// * `atomic_number` - The atomic number of the element pub fn get_row(atomic_number: u32) -> u32 { - rdkit_sys::periodic_table_ffi::get_periodic_table().getRow(atomic_number) + Self::try_get_row(atomic_number).expect("RDKit periodic table lookup failed") + } + + pub fn try_get_row(atomic_number: u32) -> Result { + ffi::get_periodic_table()?.getRow(atomic_number) } } diff --git a/src/scaffold_network.rs b/src/scaffold_network.rs new file mode 100644 index 0000000..18d36b6 --- /dev/null +++ b/src/scaffold_network.rs @@ -0,0 +1,231 @@ +use cxx::UniquePtr; +use rdkit_sys::scaffold_network_ffi; + +use crate::ROMol; + +#[derive(Debug, PartialEq, thiserror::Error)] +pub enum ScaffoldNetworkError { + #[error("could not build scaffold network (exception): {0}")] + CreationException(String), +} + +pub struct ScaffoldNetworkParams { + pub(crate) ptr: UniquePtr, +} + +impl Default for ScaffoldNetworkParams { + fn default() -> Self { + ScaffoldNetworkParams::new() + } +} + +impl ScaffoldNetworkParams { + pub fn new() -> Self { + let ptr = scaffold_network_ffi::default_scaffold_network_params() + .expect("RDKit scaffold allocation failed"); + + ScaffoldNetworkParams { ptr } + } + + pub fn with_bond_breakers(bond_breaker_smarts: &[String]) -> Self { + let ptr = scaffold_network_ffi::new_scaffold_network_params(&bond_breaker_smarts.to_vec()) + .expect("RDKit scaffold parameters failed"); + + ScaffoldNetworkParams { ptr } + } + + pub fn try_with_bond_breakers(bond_breaker_smarts: &[String]) -> Result { + Ok(Self { + ptr: scaffold_network_ffi::new_scaffold_network_params(&bond_breaker_smarts.to_vec())?, + }) + } + + pub fn set_include_generic_scaffolds(&mut self, what: bool) { + scaffold_network_ffi::set_include_generic_scaffolds(self.ptr.pin_mut(), what) + .expect("RDKit scaffold parameters failed") + } + + pub fn set_include_generic_bond_scaffolds(&mut self, what: bool) { + scaffold_network_ffi::include_generic_bond_scaffolds(self.ptr.pin_mut(), what) + .expect("RDKit scaffold parameters failed") + } + + pub fn set_include_scaffolds_without_attachments(&mut self, what: bool) { + scaffold_network_ffi::include_scaffolds_without_attachments(self.ptr.pin_mut(), what) + .expect("RDKit scaffold parameters failed") + } + + pub fn set_include_scaffolds_with_attachments(&mut self, what: bool) { + scaffold_network_ffi::include_scaffolds_with_attachments(self.ptr.pin_mut(), what) + .expect("RDKit scaffold parameters failed") + } + + pub fn set_keep_only_first_fragment(&mut self, what: bool) { + scaffold_network_ffi::keep_only_first_fragment(self.ptr.pin_mut(), what) + .expect("RDKit scaffold parameters failed") + } + + pub fn set_prune_before_fragmenting(&mut self, what: bool) { + scaffold_network_ffi::prune_before_fragmenting(self.ptr.pin_mut(), what) + .expect("RDKit scaffold parameters failed") + } + + pub fn set_flatten_isotopes(&mut self, what: bool) { + scaffold_network_ffi::flatten_isotopes(self.ptr.pin_mut(), what) + .expect("RDKit scaffold parameters failed") + } + + pub fn set_flatten_chirality(&mut self, what: bool) { + scaffold_network_ffi::flatten_chirality(self.ptr.pin_mut(), what) + .expect("RDKit scaffold parameters failed") + } + + pub fn set_flatten_keep_largest(&mut self, what: bool) { + scaffold_network_ffi::flatten_keep_largest(self.ptr.pin_mut(), what) + .expect("RDKit scaffold parameters failed") + } + + pub fn set_collect_mol_counts(&mut self, what: bool) { + scaffold_network_ffi::collect_mol_counts(self.ptr.pin_mut(), what) + .expect("RDKit scaffold parameters failed") + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ScaffoldNetworkEdgeType { + Fragment, + Generic, + GenericBond, + RemoveAttachment, + Initialize, + Unknown, +} + +impl ScaffoldNetworkEdgeType { + pub fn as_str(&self) -> &'static str { + match self { + ScaffoldNetworkEdgeType::Fragment => "Fragment", + ScaffoldNetworkEdgeType::Generic => "Generic", + ScaffoldNetworkEdgeType::GenericBond => "GenericBond", + ScaffoldNetworkEdgeType::RemoveAttachment => "RemoveAttachment", + ScaffoldNetworkEdgeType::Initialize => "Initialize", + ScaffoldNetworkEdgeType::Unknown => "UNKNOWN", + } + } +} + +impl From<&str> for ScaffoldNetworkEdgeType { + fn from(value: &str) -> Self { + match value { + "Fragment" => ScaffoldNetworkEdgeType::Fragment, + "Generic" => ScaffoldNetworkEdgeType::Generic, + "GenericBond" => ScaffoldNetworkEdgeType::GenericBond, + "RemoveAttachment" => ScaffoldNetworkEdgeType::RemoveAttachment, + "Initialize" => ScaffoldNetworkEdgeType::Initialize, + _ => ScaffoldNetworkEdgeType::Unknown, + } + } +} + +impl std::fmt::Display for ScaffoldNetworkEdgeType { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.as_str()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ScaffoldNetworkNode { + pub scaffold_smiles: String, + pub count: u32, + pub mol_count: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ScaffoldNetworkEdge { + pub begin_idx: usize, + pub end_idx: usize, + pub edge_type: ScaffoldNetworkEdgeType, +} + +impl ScaffoldNetworkEdge { + pub fn child_idx(&self) -> usize { + self.begin_idx + } + + pub fn parent_idx(&self) -> usize { + self.end_idx + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ScaffoldNetwork { + pub nodes: Vec, + pub edges: Vec, +} + +impl ScaffoldNetwork { + fn from_ffi(ptr: &scaffold_network_ffi::ScaffoldNetworkClass) -> Result { + let scaffold_smiles = scaffold_network_ffi::scaffold_network_nodes(ptr)?; + let counts = scaffold_network_ffi::scaffold_network_counts(ptr)?; + let mol_counts = scaffold_network_ffi::scaffold_network_mol_counts(ptr)?; + + let mol_counts_match = mol_counts.len() == scaffold_smiles.len(); + + let nodes = scaffold_smiles + .into_iter() + .enumerate() + .map(|(idx, smiles)| ScaffoldNetworkNode { + scaffold_smiles: smiles, + count: counts.get(idx).copied().unwrap_or_default(), + mol_count: match mol_counts_match { + true => Some(mol_counts[idx]), + false => None, + }, + }) + .collect::>(); + + let begin_indices = scaffold_network_ffi::scaffold_network_edge_begin_indices(ptr)?; + let end_indices = scaffold_network_ffi::scaffold_network_edge_end_indices(ptr)?; + let edge_types = scaffold_network_ffi::scaffold_network_edge_types(ptr)?; + + let edges = begin_indices + .into_iter() + .zip(end_indices) + .zip(edge_types) + .map(|((begin_idx, end_idx), edge_type)| ScaffoldNetworkEdge { + begin_idx, + end_idx, + edge_type: edge_type.as_str().into(), + }) + .collect::>(); + + Ok(ScaffoldNetwork { nodes, edges }) + } +} + +pub fn scaffold_network_for_mol( + mol: &ROMol, + params: &ScaffoldNetworkParams, +) -> Result { + let ptr = scaffold_network_ffi::create_scaffold_network(&mol.ptr, ¶ms.ptr) + .map_err(|e| ScaffoldNetworkError::CreationException(e.what().to_owned()))?; + + ScaffoldNetwork::from_ffi(&ptr) + .map_err(|e| ScaffoldNetworkError::CreationException(e.to_string())) +} + +pub fn scaffold_network_for_mols( + mols: &[ROMol], + params: &ScaffoldNetworkParams, +) -> Result { + let mut ptr = scaffold_network_ffi::default_scaffold_network() + .map_err(|e| ScaffoldNetworkError::CreationException(e.to_string()))?; + + for mol in mols { + scaffold_network_ffi::update_scaffold_network(ptr.pin_mut(), &mol.ptr, ¶ms.ptr) + .map_err(|e| ScaffoldNetworkError::CreationException(e.what().to_owned()))?; + } + + ScaffoldNetwork::from_ffi(&ptr) + .map_err(|e| ScaffoldNetworkError::CreationException(e.to_string())) +} diff --git a/src/substruct_match/mod.rs b/src/substruct_match/mod.rs index 0302ebe..e88d95e 100644 --- a/src/substruct_match/mod.rs +++ b/src/substruct_match/mod.rs @@ -5,21 +5,28 @@ mod substruct_match_parameters; pub use substruct_match_parameters::*; use crate::ROMol; +use rdkit_sys::substruct_match_ffi; pub fn substruct_match( mol: &ROMol, query: &ROMol, params: &SubstructMatchParameters, ) -> Vec> { - let matches = - rdkit_sys::substruct_match_ffi::substruct_match(&mol.ptr, &query.ptr, ¶ms.ptr); + try_substruct_match(mol, query, params).expect("RDKit substructure matching failed") +} + +pub fn try_substruct_match( + mol: &ROMol, + query: &ROMol, + params: &SubstructMatchParameters, +) -> Result>, cxx::Exception> { + let matches = substruct_match_ffi::substruct_match(&mol.ptr, &query.ptr, ¶ms.ptr)?; matches - .into_iter() - .map(|x| { - rdkit_sys::substruct_match_ffi::substruct_matchvect_type_to_vec_substruct_match_item(x) - .iter() - .map(SubstructMatchItem::from) - .collect::>() + .iter() + .map(|matched| { + let items = + substruct_match_ffi::substruct_matchvect_type_to_vec_substruct_match_item(matched)?; + Ok(items.iter().map(SubstructMatchItem::from).collect()) }) .collect() } diff --git a/src/substruct_match/substruct_match_item.rs b/src/substruct_match/substruct_match_item.rs index 7baba1b..418ccb7 100644 --- a/src/substruct_match/substruct_match_item.rs +++ b/src/substruct_match/substruct_match_item.rs @@ -12,8 +12,10 @@ impl From<&SubstructMatchItemFFI> for SubstructMatchItem { Self { query_atom_idx: rdkit_sys::substruct_match_ffi::substruct_match_item_query_atom_idx( value, - ), - mol_atom_idx: rdkit_sys::substruct_match_ffi::substruct_match_item_mol_atom_idx(value), + ) + .expect("RDKit operation failed"), + mol_atom_idx: rdkit_sys::substruct_match_ffi::substruct_match_item_mol_atom_idx(value) + .expect("RDKit operation failed"), } } } diff --git a/src/substruct_match/substruct_match_parameters.rs b/src/substruct_match/substruct_match_parameters.rs index a31d2c2..d40c1ed 100644 --- a/src/substruct_match/substruct_match_parameters.rs +++ b/src/substruct_match/substruct_match_parameters.rs @@ -1,8 +1,8 @@ -use cxx::SharedPtr; +use cxx::UniquePtr; use rdkit_sys::substruct_match_ffi::new_substruct_match_parameters; pub struct SubstructMatchParameters { - pub ptr: SharedPtr, + pub(crate) ptr: UniquePtr, } impl Default for SubstructMatchParameters { @@ -14,64 +14,77 @@ impl Default for SubstructMatchParameters { #[allow(dead_code)] impl SubstructMatchParameters { pub fn new() -> Self { - let ptr = new_substruct_match_parameters(); + let ptr = new_substruct_match_parameters().expect("RDKit operation failed"); SubstructMatchParameters { ptr } } pub fn get_use_chirality(&self) -> bool { rdkit_sys::substruct_match_ffi::get_use_chirality(&self.ptr) + .expect("RDKit operation failed") } pub fn get_use_enhanced_stereo(&self) -> bool { rdkit_sys::substruct_match_ffi::get_use_enhanced_stereo(&self.ptr) + .expect("RDKit operation failed") } pub fn get_aromatic_matches_conjugated(&self) -> bool { rdkit_sys::substruct_match_ffi::get_aromatic_matches_conjugated(&self.ptr) + .expect("RDKit operation failed") } pub fn get_use_query_query_matches(&self) -> bool { rdkit_sys::substruct_match_ffi::get_use_query_query_matches(&self.ptr) + .expect("RDKit operation failed") } pub fn get_use_generic_matchers(&self) -> bool { rdkit_sys::substruct_match_ffi::get_use_generic_matchers(&self.ptr) + .expect("RDKit operation failed") } pub fn get_recursion_possible(&self) -> bool { rdkit_sys::substruct_match_ffi::get_recursion_possible(&self.ptr) + .expect("RDKit operation failed") } pub fn get_uniquify(&self) -> bool { - rdkit_sys::substruct_match_ffi::get_uniquify(&self.ptr) + rdkit_sys::substruct_match_ffi::get_uniquify(&self.ptr).expect("RDKit operation failed") } pub fn set_use_chirality(&mut self, what: bool) { - rdkit_sys::substruct_match_ffi::set_use_chirality(&mut self.ptr, what) + rdkit_sys::substruct_match_ffi::set_use_chirality(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn set_use_enhanced_stereo(&mut self, what: bool) { - rdkit_sys::substruct_match_ffi::set_use_enhanced_stereo(&mut self.ptr, what) + rdkit_sys::substruct_match_ffi::set_use_enhanced_stereo(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn set_aromatic_matches_conjugated(&mut self, what: bool) { - rdkit_sys::substruct_match_ffi::set_aromatic_matches_conjugated(&mut self.ptr, what) + rdkit_sys::substruct_match_ffi::set_aromatic_matches_conjugated(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn set_use_query_query_matches(&mut self, what: bool) { - rdkit_sys::substruct_match_ffi::set_use_query_query_matches(&mut self.ptr, what) + rdkit_sys::substruct_match_ffi::set_use_query_query_matches(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn set_use_generic_matchers(&mut self, what: bool) { - rdkit_sys::substruct_match_ffi::set_use_generic_matchers(&mut self.ptr, what) + rdkit_sys::substruct_match_ffi::set_use_generic_matchers(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn set_recursion_possible(&mut self, what: bool) { - rdkit_sys::substruct_match_ffi::set_recursion_possible(&mut self.ptr, what) + rdkit_sys::substruct_match_ffi::set_recursion_possible(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } pub fn set_uniquify(&mut self, what: bool) { - rdkit_sys::substruct_match_ffi::set_uniquify(&mut self.ptr, what) + rdkit_sys::substruct_match_ffi::set_uniquify(self.ptr.pin_mut(), what) + .expect("RDKit operation failed") } } diff --git a/src/verbose_file_parsers.rs b/src/verbose_file_parsers.rs index d199a60..dd81d51 100644 --- a/src/verbose_file_parsers.rs +++ b/src/verbose_file_parsers.rs @@ -1,22 +1,20 @@ +use crate::{ + file_parsers::{open_gz, SdfRecords}, + GzBufReader, RWMol, +}; use std::{io::BufRead, path::Path}; -use flate2::bufread::GzDecoder; - -use crate::{GzBufReader, RWMol}; - pub struct VerboseMolBlockIter { - buf_read: R, - buf: Vec, + records: SdfRecords, sanitize: bool, remove_hs: bool, strict_parsing: bool, } impl VerboseMolBlockIter { - pub fn new(buf_read: R, sanitize: bool, remove_hs: bool, strict_parsing: bool) -> Self { - VerboseMolBlockIter { - buf_read, - buf: Vec::with_capacity(1024), + pub fn new(reader: R, sanitize: bool, remove_hs: bool, strict_parsing: bool) -> Self { + Self { + records: SdfRecords::new(reader), sanitize, remove_hs, strict_parsing, @@ -26,21 +24,13 @@ impl VerboseMolBlockIter { impl VerboseMolBlockIter { pub fn from_gz_file( - p: impl AsRef, + path: impl AsRef, sanitize: bool, remove_hs: bool, strict_parsing: bool, ) -> Result> { - let path = p.as_ref().to_owned(); - - let file = std::fs::File::open(path).unwrap(); - let buf_reader = std::io::BufReader::new(file); - - let gz_decoder = GzDecoder::new(buf_reader); - let gz_buf_reader = std::io::BufReader::new(gz_decoder); - Ok(Self::new( - gz_buf_reader, + open_gz(path)?, sanitize, remove_hs, strict_parsing, @@ -52,31 +42,18 @@ impl Iterator for VerboseMolBlockIter { type Item = Result<(RWMol, String), String>; fn next(&mut self) -> Option { - // Consume all `$` characters and break when buffer is larger than 1. Exit - // function at EOF. - loop { - self.buf.clear(); - let read = self.buf_read.read_until(b'$', &mut self.buf).unwrap(); - if read == 0 { - return None; - } else if read == 1 { - continue; - } else { - break; - } - } - - let block = std::str::from_utf8(&self.buf).unwrap(); - let block = block.trim(); - - let rw_mol = - RWMol::from_mol_block(block, self.sanitize, self.remove_hs, self.strict_parsing); - - let result = match rw_mol { - Some(rw_mol) => Ok((rw_mol, block.to_string())), - _ => Err(block.to_string()), - }; - - Some(result) + self.records.next_record().map(|record| { + let record = record?; + let mol = RWMol::try_from_mol_block( + &record, + self.sanitize, + self.remove_hs, + self.strict_parsing, + ) + .map_err(|e| e.to_string())?; + Ok((mol, record)) + }) } } + +impl std::iter::FusedIterator for VerboseMolBlockIter {} diff --git a/tests/test_atom.rs b/tests/test_atom.rs index 187d55b..590d9d9 100644 --- a/tests/test_atom.rs +++ b/tests/test_atom.rs @@ -40,15 +40,15 @@ fn test_set_and_get_properties() { } { let mut carbon = romol.atom_with_idx(0); - carbon.set_prop("float", 3.14); + carbon.set_prop("float", 2.5); let carbon_3 = romol.atom_with_idx(0); - assert_eq!(carbon_3.get_float_prop("float").unwrap(), 3.14); + assert_eq!(carbon_3.get_float_prop("float").unwrap(), 2.5); } { let mut carbon = romol.atom_with_idx(0); carbon.set_prop("bool", true); let carbon_4 = romol.atom_with_idx(0); - assert_eq!(carbon_4.get_bool_prop("bool").unwrap(), true); + assert!(carbon_4.get_bool_prop("bool").unwrap()); } { let mut carbon = romol.atom_with_idx(0); @@ -58,7 +58,7 @@ fn test_set_and_get_properties() { } let carbon = romol.atom_with_idx(0); assert_eq!(carbon.get_int_prop("int").unwrap(), 42); - assert_eq!(carbon.get_float_prop("float").unwrap(), 3.14); + assert_eq!(carbon.get_float_prop("float").unwrap(), 2.5); } #[test] diff --git a/tests/test_borrowing.rs b/tests/test_borrowing.rs new file mode 100644 index 0000000..b953b18 --- /dev/null +++ b/tests/test_borrowing.rs @@ -0,0 +1,5 @@ +#[test] +fn borrowed_views_cannot_outlive_or_alias_mutation() { + let tests = trybuild::TestCases::new(); + tests.compile_fail("tests/ui/*.rs"); +} diff --git a/tests/test_graphmol.rs b/tests/test_graphmol.rs index 64587f1..95192b9 100644 --- a/tests/test_graphmol.rs +++ b/tests/test_graphmol.rs @@ -13,7 +13,7 @@ fn test_romol() { fn test_neutralize() { let smiles = "CCOC(=O)C(C)(C)OC1=CC=C(C=C1)Cl.CO.C1=CC(=CC=C1C(=O)N[C@@H](CCC(=O)O)C(=O)O)NCC2=CN=C3C(=N2)C(=O)NC(=N3)N"; let romol = ROMol::from_smiles(smiles).unwrap(); - let uncharger = Uncharger::new(false); + let mut uncharger = Uncharger::new(false); let uncharged_mol = uncharger.uncharge(&romol); assert_eq!("CCOC(=O)C(C)(C)Oc1ccc(Cl)cc1.CO.Nc1nc2ncc(CNc3ccc(C(=O)N[C@@H](CCC(=O)O)C(=O)O)cc3)nc2c(=O)[nH]1", uncharged_mol.as_smiles()); } @@ -33,7 +33,7 @@ fn test_fragment_parent() { } #[test] -fn test_bad_canonicalization() { +fn test_version_specific_canonicalization_result() { let smiles = "C1=CC=C([N+]2=NOC([O-])=C2Br)C=C1"; let romol = ROMol::from_smiles(smiles).unwrap(); let rwmol = romol.as_rw_mol(false, 1); @@ -41,10 +41,14 @@ fn test_bad_canonicalization() { let parent_rwmol = fragment_parent(&rwmol, &cleanup_params, false); let te = TautomerEnumerator::new(); let canon_taut = te.canonicalize(&parent_rwmol.to_ro_mol()); - assert_eq!( - canon_taut.err().unwrap().what(), - "Can't kekulize mol. Unkekulized atoms: 5 9" - ); + match canon_taut { + Ok(canonical) => { + assert_eq!(canonical.as_smiles(), "O=C1ONN(c2ccccc2)C1Br"); + assert!(detect_chemistry_problems(&canonical).is_empty()); + assert!(ROMol::from_smiles(&canonical.as_smiles()).is_ok()); + } + Err(error) => assert_eq!(error.what(), "Can't kekulize mol. Unkekulized atoms: 5 9"), + } } #[test] @@ -85,7 +89,7 @@ fn test_stdz() { let cleanup_params = CleanupParameters::default(); let parent_rwmol = fragment_parent(&rwmol, &cleanup_params, true); - let uncharger = Uncharger::new(false); + let mut uncharger = Uncharger::new(false); let uncharged_mol = uncharger.uncharge(&parent_rwmol.to_ro_mol()); let te = TautomerEnumerator::new(); @@ -324,7 +328,7 @@ fn test_build_romol_from_really_bad_smiles() { #[test] fn mol_to_molblock_test() { let smiles = "CC"; - let romol = ROMol::from_smiles(&smiles).unwrap(); + let romol = ROMol::from_smiles(smiles).unwrap(); let molblock = romol.to_molblock(); assert_eq!(molblock, "\n RDKit 2D\n\n 2 1 0 0 0 0 0 0 0 0999 V2000\n 0.0000 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n 1.2990 0.7500 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n 1 2 1 0\nM END\n"); } diff --git a/tests/test_periodic_table.rs b/tests/test_periodic_table.rs index 8dc37d1..e1f022b 100644 --- a/tests/test_periodic_table.rs +++ b/tests/test_periodic_table.rs @@ -99,5 +99,5 @@ fn get_abundance_for_isotope() { #[test] fn more_electro_negative() { let more_electro = PeriodicTable::more_electro_negative(6, 7); - assert_eq!(more_electro, false); + assert!(!more_electro); } diff --git a/tests/test_safety.rs b/tests/test_safety.rs new file mode 100644 index 0000000..7e2c0bf --- /dev/null +++ b/tests/test_safety.rs @@ -0,0 +1,318 @@ +use bitvec::prelude::*; +use rdkit::*; +use static_assertions::{assert_impl_all, assert_not_impl_any}; +use std::io::{self, BufRead, Cursor, Read}; + +assert_impl_all!(ROMol: Send); +assert_impl_all!(RWMol: Send); +assert_not_impl_any!(ROMol: Sync); +assert_not_impl_any!(RWMol: Sync); +assert_not_impl_any!(AtomRef<'static>: Send, Sync); +assert_not_impl_any!(Atom<'static>: Send, Sync); +assert_not_impl_any!(ConformerMut<'static>: Send, Sync); +assert_not_impl_any!(Bond<'static>: Send, Sync); +assert_not_impl_any!(Conformer<'static>: Send, Sync); +assert_not_impl_any!(rdkit_sys::ro_mol_ffi::ROMol: Send, Sync); +assert_not_impl_any!(rdkit_sys::rw_mol_ffi::RWMol: Send, Sync); + +#[test] +fn parsers_reject_invalid_input_and_preserve_empty_molecules() { + assert!(ROMol::from_smiles("C1").is_err()); + assert!(RWMol::from_smarts("[C").is_err()); + assert!(RWMol::try_from_mol_block("invalid", true, true, true).is_err()); + assert!(RWMol::from_mol_block("invalid", true, true, true).is_none()); + assert_eq!(ROMol::from_smiles("").unwrap().num_atoms(true), 0); + assert_eq!(RWMol::from_smarts("").unwrap().num_atoms(true), 0); +} + +#[test] +fn borrowed_atoms_coexist_and_clones_are_independent() { + let original = ROMol::from_smiles("CO").unwrap(); + let carbon = original.atom_ref(0).unwrap(); + let oxygen = original.atom_ref(1).unwrap(); + assert_eq!((carbon.symbol(), oxygen.symbol()), ("C".into(), "O".into())); + assert_eq!(original.atoms().len(), 2); + let mut cloned = original.clone(); + cloned.atom_with_idx(1).set_formal_charge(-1); + assert_eq!(oxygen.get_formal_charge(), 0); + assert_eq!(cloned.atom_ref(1).unwrap().get_formal_charge(), -1); + drop(original); + assert_eq!(cloned.atom_ref(0).unwrap().symbol(), "C"); +} + +#[test] +fn graph_bounds_and_editing_are_checked() { + let mut mol = RWMol::new(); + assert!(mol.add_atom(119).is_err()); + let carbon = mol.add_atom(6).unwrap(); + let oxygen = mol.add_atom(8).unwrap(); + mol.add_bond(carbon, oxygen, BondType::SINGLE).unwrap(); + assert!(mol.add_bond(carbon, oxygen, BondType::SINGLE).is_err()); + assert!(mol.add_bond(carbon, carbon, BondType::SINGLE).is_err()); + assert!(mol.add_bond(carbon, 42, BondType::SINGLE).is_err()); + assert!(mol + .add_bond(carbon, oxygen, BondType { repr: i32::MAX }) + .is_err()); + assert!(mol.atom_ref(2).is_err()); + assert!(mol.try_atom_with_idx(u32::MAX).is_err()); + assert!(mol.bond(1).is_err()); + mol.sanitize().unwrap(); + assert_eq!(mol.as_smiles(), "CO"); + let bond = mol.bond(0).unwrap(); + assert_eq!(bond.bond_type(), BondType::SINGLE); + assert_eq!(bond.other_atom_idx(carbon), oxygen); + assert!(bond.try_other_atom_idx(42).is_err()); + assert!(mol.remove_atom(8).is_err()); + assert!(mol.remove_bond(0, 8).is_err()); + mol.remove_bond(carbon, oxygen).unwrap(); + assert!(mol.remove_bond(carbon, oxygen).is_err()); + mol.remove_atom(oxygen).unwrap(); + mol.sanitize().unwrap(); + assert_eq!(mol.to_ro_mol().as_smiles(), "C"); +} + +#[test] +fn invalid_enum_and_hydrogen_counts_return_errors() { + let mut mol = ROMol::from_smiles("C").unwrap(); + let mut atom = mol.atom_with_idx(0); + assert!(atom.try_set_formal_charge(128).is_err()); + assert!(atom.try_set_formal_charge(-129).is_err()); + assert!(atom.try_set_num_explicit_hs(-1).is_err()); + assert!(atom.try_set_num_explicit_hs(256).is_err()); + assert!(atom + .try_set_hybridization_type(HybridizationType { repr: i32::MAX }) + .is_err()); + assert_eq!(atom.get_total_num_hs(), 4); +} + +#[test] +fn chemistry_exceptions_reach_rust() { + let mut params = SmilesParserParams::default(); + params.set_sanitize(false); + let mut mol = ROMol::from_smiles_with_params("F(C)(C)(C)(C)(C)", ¶ms).unwrap(); + assert!(!try_detect_chemistry_problems(&mol).unwrap().is_empty()); + assert!(mol.try_update_property_cache(true).is_err()); + assert!(mol.atom_with_idx(0).update_property_cache(true).is_err()); +} + +#[test] +fn low_level_exception_downcast_is_checked() { + use rdkit_sys::ro_mol_ffi as ffi; + let mut params = ffi::new_smiles_parser_params().unwrap(); + ffi::smiles_parser_params_set_sanitize(params.pin_mut(), false).unwrap(); + cxx::let_cxx_string!(smiles = "c1cccc1"); + let mol = ffi::smiles_to_mol_with_params(&smiles, ¶ms).unwrap(); + let problems = ffi::detect_chemistry_problems(&mol).unwrap(); + let problem = problems + .iter() + .find(|p| ffi::mol_sanitize_exception_type(p).unwrap() == "KekulizeException") + .unwrap(); + assert!(ffi::atom_sanitize_exception_get_atom_idx(problem).is_err()); +} + +#[test] +fn bond_lookup_distinguishes_missing_from_invalid() { + let mol = ROMol::from_smiles("CC.O").unwrap(); + assert!(mol.bond_between_atoms(0, 1).unwrap().is_some()); + assert!(mol.bond_between_atoms(0, 2).unwrap().is_none()); + assert!(mol.bond_between_atoms(0, 3).is_err()); +} + +#[test] +fn conformer_coordinates_are_owned_and_checked() { + let mut mol = ROMol::from_smiles("CCO").unwrap(); + assert!(mol.conformer(-1).is_err()); + let id = mol.compute_2d_coords().unwrap(); + assert_eq!(mol.num_conformers(), 1); + let conf = mol.conformer(id as i32).unwrap(); + assert_eq!(conf.id(), id); + assert_eq!(conf.num_atoms(), 3); + assert!(!conf.is_3d()); + assert!(conf.position(3).is_err()); + let original = conf.position(0).unwrap(); + let mut cloned = mol.clone(); + let position = Point3D { + x: 1.5, + y: -2.0, + z: 0.25, + }; + cloned + .conformer_mut(id as i32) + .unwrap() + .set_position(0, position) + .unwrap(); + assert_eq!( + cloned.conformer(id as i32).unwrap().position(0).unwrap(), + position + ); + assert_eq!( + mol.conformer(id as i32).unwrap().position(0).unwrap(), + original + ); + let mut conf = mol.conformer_mut(id as i32).unwrap(); + assert!(conf.set_position(3, position).is_err()); + assert!(conf + .set_position( + 0, + Point3D { + x: f64::NAN, + y: 0.0, + z: 0.0 + } + ) + .is_err()); +} + +#[test] +fn fingerprint_bit_lengths_and_similarity_are_exact() { + let mol = ROMol::from_smiles("CCO").unwrap(); + for bits in [1, 63, 64, 65, 167, 2048] { + let fp = mol.morgan_fingerprint_with_params(2, bits).unwrap(); + assert_eq!(fp.0.len(), bits as usize); + assert_eq!(fp.tanimoto_similarity(&fp), 1.0); + } + assert_eq!(mol.maccs_fingerprint().unwrap().0.len(), 167); + assert!(mol.morgan_fingerprint_with_params(2, 0).is_err()); + assert!(mol.pattern_fingerprint_with_params(0).is_err()); + assert!(mol.rdk_fingerprint_with_params(5, 2, 64).is_err()); + let empty = Fingerprint(BitVec::new()); + assert_eq!(empty.tanimoto_similarity(&empty), 1.0); + let zeros = Fingerprint(bitvec![u8, Lsb0; 0; 64]); + assert_eq!(zeros.tanimoto_distance(&zeros), 1.0); + let a = Fingerprint(bitvec![u8, Lsb0; 1, 1, 0]); + let b = Fingerprint(bitvec![u8, Lsb0; 0, 1, 1]); + assert_eq!(a.tanimoto_similarity(&b), 1.0 / 3.0); + assert!(std::panic::catch_unwind(|| empty.tanimoto_similarity(&zeros)).is_err()); +} + +#[test] +fn tautomer_iterator_reports_remaining_items() { + let mol = ROMol::from_smiles("CC(=O)C").unwrap(); + let mut tautomers = TautomerEnumerator::new().try_enumerate(&mol).unwrap(); + let total = tautomers.len(); + assert!(total > 1); + assert!(tautomers.get(total).is_err()); + let first = tautomers.try_next().unwrap().unwrap(); + assert_eq!(tautomers.len(), total - 1); + assert_eq!(tautomers.size_hint(), (total - 1, Some(total - 1))); + while tautomers.next().is_some() {} + assert_eq!(tautomers.size_hint(), (0, Some(0))); + assert!(tautomers.next().is_none()); + drop(tautomers); + assert!(!first.as_smiles().is_empty()); +} + +#[test] +fn periodic_table_bad_inputs_return_errors() { + assert!(PeriodicTable::try_get_atomic_weight(119).is_err()); + assert!(PeriodicTable::try_get_element_symbol(u32::MAX).is_err()); + assert!(PeriodicTable::try_get_atomic_number("not-an-element").is_err()); + assert!(PeriodicTable::try_get_valence_list(119).is_err()); + assert_eq!(PeriodicTable::get_max_atomic_number(), 118); + let row_ends = [0, 2, 10, 18, 36, 54, 86, 118]; + for number in 0..=118 { + let expected = row_ends.iter().position(|end| number <= *end).unwrap() as u32; + assert_eq!(PeriodicTable::try_get_row(number).unwrap(), expected); + } + assert!(PeriodicTable::try_get_row(119).is_err()); +} + +#[test] +fn sdf_reader_preserves_dollars_and_empty_title() { + let mol = ROMol::from_smiles("CO").unwrap(); + let block = mol.to_molblock(); + let record = format!("{block}> \nprice $5\n\n$$$$\n{block}$$$$\n"); + let mut records = VerboseMolBlockIter::new(Cursor::new(record), true, true, true); + let (parsed, text) = records.next().unwrap().unwrap(); + assert_eq!(parsed.as_smiles(), "CO"); + assert!(text.contains("price $5")); + assert!(text.starts_with('\n')); + assert!(records.next().unwrap().is_ok()); + assert!(records.next().is_none()); +} + +struct BrokenReader; +impl Read for BrokenReader { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Err(io::Error::other("broken reader")) + } +} +impl BufRead for BrokenReader { + fn fill_buf(&mut self) -> io::Result<&[u8]> { + Err(io::Error::other("broken reader")) + } + fn consume(&mut self, _: usize) {} +} + +#[test] +fn sdf_io_and_utf8_errors_are_reported_once() { + let mut reader = MolBlockIter::new(BrokenReader, true, true, true); + assert!(reader + .next() + .unwrap() + .unwrap_err() + .contains("broken reader")); + assert!(reader.next().is_none()); + let mut reader = MolBlockIter::new(Cursor::new(vec![0xff]), true, true, true); + assert!(reader.next().unwrap().unwrap_err().contains("UTF-8")); + assert!(reader.next().is_none()); + assert!( + MolBlockIter::from_gz_file("/path/that/does/not/exist.sdf.gz", true, true, true).is_err() + ); +} + +#[test] +fn unique_molecule_can_move_between_threads() { + let mol = ROMol::from_smiles("CCO").unwrap(); + let mol = std::thread::spawn(move || { + let mut copy = mol.clone(); + copy.atom_with_idx(2).set_formal_charge(-1); + (mol.as_smiles(), copy.as_smiles()) + }) + .join() + .unwrap(); + assert_eq!(mol.0, "CCO"); + assert_eq!(mol.1, "CC[O-]"); +} + +#[test] +fn smiles_error_display_remains_compatible_and_retains_native_details() { + let error = ROMol::from_smiles("F(C)(C)(C)(C)(C)").unwrap_err(); + assert_eq!( + error.to_string(), + "could not convert smiles to romol (exception)" + ); + match error { + ROMolError::ConversionException(message) => assert!(message.contains("valence")), + other => panic!("unexpected error: {other:?}"), + } + assert_eq!( + ROMolError::UnknownConversionError.to_string(), + "could not convert smiles to romol (nullptr)" + ); +} + +#[test] +fn low_level_smiles_null_remains_explicitly_checkable() { + cxx::let_cxx_string!(smiles = "C1"); + let ptr = rdkit_sys::ro_mol_ffi::smiles_to_mol(&smiles).unwrap(); + assert!(ptr.is_null()); + assert_eq!( + ROMol::from_smiles("C1").unwrap_err(), + ROMolError::UnknownConversionError + ); +} + +#[test] +fn periodic_valence_lists_own_their_storage() { + use rdkit_sys::PeriodicTableOps; + let list = { + let table = rdkit_sys::periodic_table_ffi::get_periodic_table().unwrap(); + table.getValenceList(6).unwrap() + }; + assert_eq!(list.as_slice(), &[4]); + let mut first = PeriodicTable::get_valence_list(6); + let second = PeriodicTable::get_valence_list(6); + first.push(99); + assert_eq!(second, vec![4]); +} diff --git a/tests/test_scaffold_network.rs b/tests/test_scaffold_network.rs new file mode 100644 index 0000000..5131688 --- /dev/null +++ b/tests/test_scaffold_network.rs @@ -0,0 +1,170 @@ +use rdkit::{ + scaffold_network_for_mol, scaffold_network_for_mols, ROMol, ScaffoldNetworkEdgeType, + ScaffoldNetworkError, ScaffoldNetworkParams, +}; + +const PHENYLQUINOLINE: &str = "c1ccc(-c2ccc3ncccc3c2)cc1"; + +fn params_without_generics() -> ScaffoldNetworkParams { + let mut params = ScaffoldNetworkParams::default(); + params.set_include_generic_scaffolds(false); + params.set_include_generic_bond_scaffolds(false); + params +} + +fn scaffold_smiles(network: &rdkit::ScaffoldNetwork) -> Vec<&str> { + network + .nodes + .iter() + .map(|n| n.scaffold_smiles.as_str()) + .collect() +} + +#[test] +fn test_scaffold_network_for_mol() { + let mol = ROMol::from_smiles(PHENYLQUINOLINE).unwrap(); + let network = scaffold_network_for_mol(&mol, ¶ms_without_generics()).unwrap(); + + assert_eq!( + scaffold_smiles(&network), + [ + PHENYLQUINOLINE, + "*c1ccccc1", + "c1ccccc1", + "*c1ccc2ncccc2c1", + "c1ccc2ncccc2c1", + ] + ); + assert!(network.nodes.iter().all(|n| n.count == 1)); + assert!(network.nodes.iter().all(|n| n.mol_count == Some(1))); + + let hierarchy = network + .edges + .iter() + .map(|e| { + ( + network.nodes[e.child_idx()].scaffold_smiles.as_str(), + network.nodes[e.parent_idx()].scaffold_smiles.as_str(), + e.edge_type, + ) + }) + .collect::>(); + + assert_eq!( + hierarchy, + [ + ( + PHENYLQUINOLINE, + "*c1ccccc1", + ScaffoldNetworkEdgeType::Fragment + ), + ( + "*c1ccccc1", + "c1ccccc1", + ScaffoldNetworkEdgeType::RemoveAttachment + ), + ( + PHENYLQUINOLINE, + "*c1ccc2ncccc2c1", + ScaffoldNetworkEdgeType::Fragment + ), + ( + "*c1ccc2ncccc2c1", + "c1ccc2ncccc2c1", + ScaffoldNetworkEdgeType::RemoveAttachment + ), + ] + ); +} + +#[test] +fn test_scaffold_network_default_params_include_generics() { + let mol = ROMol::from_smiles(PHENYLQUINOLINE).unwrap(); + let network = scaffold_network_for_mol(&mol, &ScaffoldNetworkParams::default()).unwrap(); + + assert!(scaffold_smiles(&network).contains(&"*1:*:*:*:*:*:1")); + assert!(network + .edges + .iter() + .any(|e| e.edge_type == ScaffoldNetworkEdgeType::Generic)); +} + +#[test] +fn test_scaffold_network_single_ring() { + let mol = ROMol::from_smiles("c1ccccc1").unwrap(); + let network = scaffold_network_for_mol(&mol, ¶ms_without_generics()).unwrap(); + + assert_eq!(scaffold_smiles(&network), ["c1ccccc1"]); + assert!(network.edges.is_empty()); +} + +#[test] +fn test_scaffold_network_no_rings() { + let mol = ROMol::from_smiles("CCO").unwrap(); + let network = scaffold_network_for_mol(&mol, ¶ms_without_generics()).unwrap(); + + assert_eq!(scaffold_smiles(&network), ["CCO", ""]); + assert_eq!( + network.edges[0].edge_type, + ScaffoldNetworkEdgeType::Initialize + ); +} + +#[test] +fn test_scaffold_network_for_mols_shares_nodes() { + let mols = [ + ROMol::from_smiles(PHENYLQUINOLINE).unwrap(), + ROMol::from_smiles("c1ccc(-c2ccccc2)cc1").unwrap(), + ]; + let network = scaffold_network_for_mols(&mols, ¶ms_without_generics()).unwrap(); + + let benzene = network + .nodes + .iter() + .find(|n| n.scaffold_smiles == "c1ccccc1") + .unwrap(); + assert_eq!(benzene.mol_count, Some(2)); + assert!(benzene.count > 1); +} + +#[test] +fn test_scaffold_network_without_mol_counts() { + let mut params = params_without_generics(); + params.set_collect_mol_counts(false); + + let mol = ROMol::from_smiles(PHENYLQUINOLINE).unwrap(); + let network = scaffold_network_for_mol(&mol, ¶ms).unwrap(); + + assert!(network.nodes.iter().all(|n| n.mol_count.is_none())); + assert!(network.nodes.iter().all(|n| n.count == 1)); +} + +#[test] +fn test_scaffold_network_with_bond_breakers() { + let mol = ROMol::from_smiles(PHENYLQUINOLINE).unwrap(); + + let params = ScaffoldNetworkParams::with_bond_breakers(&[]); + let network = scaffold_network_for_mol(&mol, ¶ms).unwrap(); + assert_eq!(scaffold_smiles(&network), [PHENYLQUINOLINE]); + + let params = ScaffoldNetworkParams::with_bond_breakers(&[ + "[!#0;R:1]-!@[!#0:2]>>[*:1]-[#0].[#0]-[*:2]".to_string(), + ]); + let network = scaffold_network_for_mol(&mol, ¶ms).unwrap(); + assert!(network.nodes.len() > 1); +} + +#[test] +fn test_scaffold_network_bad_params() { + let mut params = ScaffoldNetworkParams::default(); + params.set_include_scaffolds_with_attachments(false); + params.set_include_scaffolds_without_attachments(false); + + let mol = ROMol::from_smiles(PHENYLQUINOLINE).unwrap(); + assert_eq!( + scaffold_network_for_mol(&mol, ¶ms), + Err(ScaffoldNetworkError::CreationException( + "must include at least one of scaffolds with attachments or scaffolds without attachments".to_string() + )) + ); +} diff --git a/tests/ui/atom_outlives_molecule.rs b/tests/ui/atom_outlives_molecule.rs new file mode 100644 index 0000000..52717d4 --- /dev/null +++ b/tests/ui/atom_outlives_molecule.rs @@ -0,0 +1,8 @@ +use rdkit::ROMol; +fn main() { + let atom = { + let mol = ROMol::from_smiles("C").unwrap(); + mol.atom_ref(0).unwrap() + }; + println!("{}", atom.symbol()); +} diff --git a/tests/ui/atom_outlives_molecule.stderr b/tests/ui/atom_outlives_molecule.stderr new file mode 100644 index 0000000..2c74bb7 --- /dev/null +++ b/tests/ui/atom_outlives_molecule.stderr @@ -0,0 +1,11 @@ +error[E0597]: `mol` does not live long enough + --> tests/ui/atom_outlives_molecule.rs:5:9 + | +3 | let atom = { + | ---- borrow later stored here +4 | let mol = ROMol::from_smiles("C").unwrap(); + | --- binding `mol` declared here +5 | mol.atom_ref(0).unwrap() + | ^^^ borrowed value does not live long enough +6 | }; + | - `mol` dropped here while still borrowed diff --git a/tests/ui/bond_blocks_graph_edit.rs b/tests/ui/bond_blocks_graph_edit.rs new file mode 100644 index 0000000..d19b2b2 --- /dev/null +++ b/tests/ui/bond_blocks_graph_edit.rs @@ -0,0 +1,7 @@ +use rdkit::RWMol; +fn main() { + let mut mol = RWMol::from_smarts("CC").unwrap(); + let bond = mol.bond(0).unwrap(); + mol.remove_atom(0).unwrap(); + println!("{}", bond.idx()); +} diff --git a/tests/ui/bond_blocks_graph_edit.stderr b/tests/ui/bond_blocks_graph_edit.stderr new file mode 100644 index 0000000..d966c21 --- /dev/null +++ b/tests/ui/bond_blocks_graph_edit.stderr @@ -0,0 +1,9 @@ +error[E0502]: cannot borrow `mol` as mutable because it is also borrowed as immutable + --> tests/ui/bond_blocks_graph_edit.rs:5:5 + | +4 | let bond = mol.bond(0).unwrap(); + | --- immutable borrow occurs here +5 | mol.remove_atom(0).unwrap(); + | ^^^^^^^^^^^^^^^^^^ mutable borrow occurs here +6 | println!("{}", bond.idx()); + | ---- immutable borrow later used here diff --git a/tests/ui/conformer_blocks_coordinates.rs b/tests/ui/conformer_blocks_coordinates.rs new file mode 100644 index 0000000..8d094ca --- /dev/null +++ b/tests/ui/conformer_blocks_coordinates.rs @@ -0,0 +1,8 @@ +use rdkit::ROMol; +fn main() { + let mut mol = ROMol::from_smiles("C").unwrap(); + mol.compute_2d_coords().unwrap(); + let conf = mol.conformer(-1).unwrap(); + mol.compute_2d_coords().unwrap(); + println!("{}", conf.id()); +} diff --git a/tests/ui/conformer_blocks_coordinates.stderr b/tests/ui/conformer_blocks_coordinates.stderr new file mode 100644 index 0000000..e7b5184 --- /dev/null +++ b/tests/ui/conformer_blocks_coordinates.stderr @@ -0,0 +1,9 @@ +error[E0502]: cannot borrow `mol` as mutable because it is also borrowed as immutable + --> tests/ui/conformer_blocks_coordinates.rs:6:5 + | +5 | let conf = mol.conformer(-1).unwrap(); + | --- immutable borrow occurs here +6 | mol.compute_2d_coords().unwrap(); + | ^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here +7 | println!("{}", conf.id()); + | ---- immutable borrow later used here diff --git a/tests/ui/low_level_mutable_alias.rs b/tests/ui/low_level_mutable_alias.rs new file mode 100644 index 0000000..0b9bfaa --- /dev/null +++ b/tests/ui/low_level_mutable_alias.rs @@ -0,0 +1,9 @@ +use rdkit_sys::ro_mol_ffi as ffi; +fn main() { + cxx::let_cxx_string!(smiles = "CC"); + let mut mol = ffi::smiles_to_mol(&smiles).unwrap(); + let first = ffi::get_atom_with_idx(mol.pin_mut(), 0).unwrap(); + let second = ffi::get_atom_with_idx(mol.pin_mut(), 0).unwrap(); + ffi::set_formal_charge(first, 1).unwrap(); + ffi::set_formal_charge(second, 2).unwrap(); +} diff --git a/tests/ui/low_level_mutable_alias.stderr b/tests/ui/low_level_mutable_alias.stderr new file mode 100644 index 0000000..5a3a210 --- /dev/null +++ b/tests/ui/low_level_mutable_alias.stderr @@ -0,0 +1,9 @@ +error[E0499]: cannot borrow `mol` as mutable more than once at a time + --> tests/ui/low_level_mutable_alias.rs:6:41 + | +5 | let first = ffi::get_atom_with_idx(mol.pin_mut(), 0).unwrap(); + | --- first mutable borrow occurs here +6 | let second = ffi::get_atom_with_idx(mol.pin_mut(), 0).unwrap(); + | ^^^ second mutable borrow occurs here +7 | ffi::set_formal_charge(first, 1).unwrap(); + | ----- first borrow later used here diff --git a/tests/ui/low_level_ownership_cannot_clone.rs b/tests/ui/low_level_ownership_cannot_clone.rs new file mode 100644 index 0000000..6cdf7f2 --- /dev/null +++ b/tests/ui/low_level_ownership_cannot_clone.rs @@ -0,0 +1,7 @@ +use rdkit_sys::ro_mol_ffi as ffi; +fn main() { + cxx::let_cxx_string!(smiles = "C"); + let mol = ffi::smiles_to_mol(&smiles).unwrap(); + let alias = mol.clone(); + drop(alias); +} diff --git a/tests/ui/low_level_ownership_cannot_clone.stderr b/tests/ui/low_level_ownership_cannot_clone.stderr new file mode 100644 index 0000000..451b243 --- /dev/null +++ b/tests/ui/low_level_ownership_cannot_clone.stderr @@ -0,0 +1,5 @@ +error[E0599]: no method named `clone` found for struct `UniquePtr` in the current scope + --> tests/ui/low_level_ownership_cannot_clone.rs:5:21 + | +5 | let alias = mol.clone(); + | ^^^^^ method not found in `UniquePtr` diff --git a/tests/ui/shared_atom_blocks_mutation.rs b/tests/ui/shared_atom_blocks_mutation.rs new file mode 100644 index 0000000..46e4eac --- /dev/null +++ b/tests/ui/shared_atom_blocks_mutation.rs @@ -0,0 +1,7 @@ +use rdkit::ROMol; +fn main() { + let mut mol = ROMol::from_smiles("C").unwrap(); + let shared = mol.atom_ref(0).unwrap(); + mol.atom_with_idx(0).set_formal_charge(1); + println!("{}", shared.symbol()); +} diff --git a/tests/ui/shared_atom_blocks_mutation.stderr b/tests/ui/shared_atom_blocks_mutation.stderr new file mode 100644 index 0000000..812d068 --- /dev/null +++ b/tests/ui/shared_atom_blocks_mutation.stderr @@ -0,0 +1,9 @@ +error[E0502]: cannot borrow `mol` as mutable because it is also borrowed as immutable + --> tests/ui/shared_atom_blocks_mutation.rs:5:5 + | +4 | let shared = mol.atom_ref(0).unwrap(); + | --- immutable borrow occurs here +5 | mol.atom_with_idx(0).set_formal_charge(1); + | ^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here +6 | println!("{}", shared.symbol()); + | ------ immutable borrow later used here From d2de00eada189e858787ac73b17d94c20e467f56 Mon Sep 17 00:00:00 2001 From: Xavier Lange Date: Fri, 9 Oct 2026 20:35:33 +0000 Subject: [PATCH 3/8] Validate Ubuntu RDKit packages and document the audited binding scope --- .github/workflows/clang-format-check.yml | 22 +-- .github/workflows/test_suite.yml | 166 ++++++++--------------- README.md | 59 ++++---- ci/install-deps.sh | 13 ++ ci/test-sanitizers.sh | 11 ++ docs/binding-audit.md | 62 +++++++++ docs/binding-inventory.md | 100 ++++++++++++++ docs/building.md | 77 +++++++++++ docs/migration.md | 61 +++++++++ docs/validation.md | 54 ++++++++ rdkit-sys/README.md | 54 ++------ rdkit-sys/tests/test_periodic_table.rs | 5 +- tests/test_periodic_table.rs | 5 +- 13 files changed, 493 insertions(+), 196 deletions(-) create mode 100644 ci/install-deps.sh create mode 100644 ci/test-sanitizers.sh create mode 100644 docs/binding-audit.md create mode 100644 docs/binding-inventory.md create mode 100644 docs/building.md create mode 100644 docs/migration.md create mode 100644 docs/validation.md diff --git a/.github/workflows/clang-format-check.yml b/.github/workflows/clang-format-check.yml index 4f193cb..eb4a66b 100644 --- a/.github/workflows/clang-format-check.yml +++ b/.github/workflows/clang-format-check.yml @@ -1,13 +1,13 @@ -name: clang-format Check -on: [push, pull_request] +name: C++ formatting +on: + pull_request: + workflow_dispatch: +permissions: + contents: read jobs: - formatting-check: - name: Formatting Check - runs-on: ubuntu-latest + convention_checker: + runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v4 - - name: Run clang-format style check for C/C++/Protobuf programs. - uses: jidicula/clang-format-action@v4.13.0 - with: - clang-format-version: "13" - check-path: "rdkit-sys/wrapper" + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + - run: sudo apt-get update && sudo apt-get install -y clang-format-18 + - run: find rdkit-sys/wrapper -type f \( -name '*.h' -o -name '*.cc' \) -print0 | xargs -0 clang-format-18 --dry-run --Werror diff --git a/.github/workflows/test_suite.yml b/.github/workflows/test_suite.yml index 3a167ea..31ed285 100644 --- a/.github/workflows/test_suite.yml +++ b/.github/workflows/test_suite.yml @@ -1,119 +1,69 @@ -name: Tests, Clippy, and Format +name: Packaged RDKit on: - pull_request: { } + pull_request: + workflow_dispatch: -env: - REGISTRY: ghcr.io - REPO_LOWER: rdkit-rs/cheminee +permissions: + contents: read jobs: - test_suite: - runs-on: buildjet-16vcpu-ubuntu-2204 - env: - ARCH: amd64 - DEBIAN_FRONTEND: noninteractive - permissions: - contents: read - packages: write - steps: - - name: Git checkout - uses: actions/checkout@v2 - - - name: Run sccache-cache - uses: mozilla/sccache-action@eaed7fb9f8fb32adea8bd40d7f276f312de9beaf - with: - version: "v0.4.0-pre.10" - - - name: Run sccache stat for check + test: + name: Ubuntu ${{ matrix.ubuntu }} / RDKit ${{ matrix.rdkit }} + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + include: + - ubuntu: '26.04' + rdkit: '2025.03.6' + image: ubuntu:26.04@sha256:f144425ff09be612d6d9ad965196e9cdc23dae1f42110a8a11a3e9a8198759f7 + - ubuntu: '24.04' + rdkit: '2023.09.3' + image: ubuntu:24.04@sha256:534baea6a22c03a63003dbc8dbe78fe34bc0d7e595d9a9dc9834884ff530eb55 + container: + image: ${{ matrix.image }} + defaults: + run: shell: bash - run: ${SCCACHE_PATH} --show-stats - - - name: Install dependencies - run: | - sudo apt-get update - sudo apt-get install -y build-essential libssl-dev libboost-iostreams-dev libboost-serialization-dev pkg-config curl tar - - - name: Install RDKit - run: | - cd /tmp - if [ $(dpkg --print-architecture) = "amd64" ]; then - curl -O https://rdkit-rs-debian.s3.eu-central-1.amazonaws.com/rdkit_2024_09_1_ubuntu_22_04_amd64.tar.gz - sudo tar xf rdkit_2024_09_1_ubuntu_22_04_amd64.tar.gz - else - curl -O https://rdkit-rs-debian.s3.eu-central-1.amazonaws.com/rdkit_2024_09_1_ubuntu_22_04_arm64.tar.gz - sudo tar xf rdkit_2024_09_1_ubuntu_22_04_arm64.tar.gz - fi - sudo mv /tmp/rdkit-Release_2024_09_1/Code /usr/local/include/rdkit - sudo mv /tmp/rdkit-Release_2024_09_1/build/lib/* /usr/lib/ - - - name: Install latest stable - uses: actions-rs/toolchain@v1 - with: - toolchain: stable - override: true - components: rustfmt, clippy - - - name: Cargo test - run: | - RUST_WRAPPER=$SCCACHE_PATH cargo clean - RUST_WRAPPER=$SCCACHE_PATH cargo test --workspace - - convention_checker: - env: - ARCH: amd64 - runs-on: buildjet-16vcpu-ubuntu-2204 - permissions: - contents: read - packages: write steps: - - name: Git checkout - uses: actions/checkout@v2 - - - name: Run sccache-cache - uses: mozilla/sccache-action@eaed7fb9f8fb32adea8bd40d7f276f312de9beaf + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + - run: bash ci/install-deps.sh + - uses: dtolnay/rust-toolchain@e2a55d2ffb04f378e9626c28d38b36d230d1e12f with: - version: "v0.4.0-pre.10" - - - name: Run sccache stat for check + toolchain: '1.99.0' + components: rustfmt, clippy + - run: cargo fmt --all --check + - run: cargo test --workspace --locked + - run: cargo clippy --workspace --all-targets --locked -- -D warnings + - run: cargo doc --workspace --no-deps --locked + env: + RUSTDOCFLAGS: -D warnings + - run: cargo check --workspace --all-features --locked + env: + CONDA_PREFIX: /usr + + sanitizers: + name: C++ ASan and UBSan / Ubuntu 26.04 + runs-on: ubuntu-24.04 + container: + image: ubuntu:26.04@sha256:f144425ff09be612d6d9ad965196e9cdc23dae1f42110a8a11a3e9a8198759f7 + defaults: + run: shell: bash - run: ${SCCACHE_PATH} --show-stats - - - name: Install dependencies - run: | - sudo apt-get update - sudo apt-get install -y build-essential libssl-dev libboost-iostreams-dev libboost-serialization-dev pkg-config curl tar - - - name: Install RDKit - run: | - cd /tmp - if [ $(dpkg --print-architecture) = "amd64" ]; then - curl -O https://rdkit-rs-debian.s3.eu-central-1.amazonaws.com/rdkit_2024_09_1_ubuntu_22_04_amd64.tar.gz - sudo tar xf rdkit_2024_09_1_ubuntu_22_04_amd64.tar.gz - else - curl -O https://rdkit-rs-debian.s3.eu-central-1.amazonaws.com/rdkit_2024_09_1_ubuntu_22_04_arm64.tar.gz - sudo tar xf rdkit_2024_09_1_ubuntu_22_04_arm64.tar.gz - fi - sudo mv /tmp/rdkit-Release_2024_09_1/Code /usr/local/include/rdkit - sudo mv /tmp/rdkit-Release_2024_09_1/build/lib/* /usr/lib/ - - - name: Install latest stable - uses: actions-rs/toolchain@v1 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + - run: bash ci/install-deps.sh + - uses: dtolnay/rust-toolchain@e2a55d2ffb04f378e9626c28d38b36d230d1e12f with: - toolchain: nightly - override: true - components: rustfmt, clippy - - - name: Rust Format Check - run: | - RUST_WRAPPER=$SCCACHE_PATH cargo fmt --check - pushd rdkit-sys - RUST_WRAPPER=$SCCACHE_PATH cargo fmt --check - popd + toolchain: '1.99.0' + - run: bash ci/test-sanitizers.sh + env: + CARGO_BUILD_JOBS: '2' - - name: Clippy Check - run: | - RUST_WRAPPER=$SCCACHE_PATH cargo clippy - pushd rdkit-sys - RUST_WRAPPER=$SCCACHE_PATH cargo clippy - popd \ No newline at end of file + test_suite: + runs-on: ubuntu-24.04 + needs: [test, sanitizers] + if: always() + steps: + - run: test '${{ needs.test.result }}' = success && test '${{ needs.sanitizers.result }}' = success diff --git a/README.md b/README.md index a3a1a69..b72804a 100644 --- a/README.md +++ b/README.md @@ -1,43 +1,44 @@ -RDKit ---- +# RDKit for Rust -A high-level library for performing common RDKit tasks such as SMILES parsing, molecule normalization, etc. Uses -the C++ API via bindings from [rdkit-sys](https://crates.io/crate/rdkit-sys). +The [rdkit crate](https://crates.io/crates/rdkit) provides Rust interfaces for molecule parsing, graph inspection and editing, fingerprints, descriptors, standardization, substructure matching, scaffold networks, and conformer coordinates. The workspace member [rdkit-sys](https://crates.io/crates/rdkit-sys) bridges to the installed RDKit C++ library using CXX; its source is in [rdkit-sys/](rdkit-sys). -Notice: Requires rdkit 2023.09.1 or higher (like Ubuntu Noble 24.04) +## Install and build -Prerequisites ---- +The primary target is Ubuntu 26.04 LTS, x86_64, with RDKit 2025.03.6 from Ubuntu's `librdkit-dev=202503.6-4` package. Ubuntu 24.04 LTS with `202309.3-3build2` is the compatibility target. The native library and its matching development headers must both be installed. -On a Mac: +```sh +sudo bash ci/install-deps.sh +cargo test --workspace --locked +``` - brew install rdkit +The checkout pins Rust 1.99.0 and commits `Cargo.lock` for repeatable validation. See [building](docs/building.md) for exact package versions, containers, custom installations, Conda, and the target matrix. -On Linux you will need a custom build of rdkit with static libraries. At the moment, we have some pre-compiled tar balls -available for AMD64 and ARM64 for the latest RKDit which get the job done for our CI (Note: these have been compiled on -Ubuntu 22.04): +Use the crate named `rdkit`, with `use rdkit::ROMol`. The unrelated `rdkit-rs` crate is not this workspace. -https://rdkit-rs-debian.s3.eu-central-1.amazonaws.com/rdkit_2024_09_1_ubuntu_22_04_amd64.tar.gz -https://rdkit-rs-debian.s3.eu-central-1.amazonaws.com/rdkit_2024_09_1_ubuntu_22_04_arm64.tar.gz +```rust +use rdkit::ROMol; -Release Both rdkit and rdkit-sys ---- +fn main() -> Result<(), Box> { + let mol = ROMol::from_smiles("OCC")?; + println!("{}", mol.try_as_smiles()?); + Ok(()) +} +``` -The `rdkit-sys` crate is a member of the `rdkit` workspace. All crates in the workspace should move in lockstep versions -for simplicity's sake, making it easy to tell which crates are compatible. +## Scope and compatibility -Managing multiple crates in a single repository: +This is a selected binding surface, not a Rust reimplementation or a claim of complete RDKit API coverage. The [binding audit](docs/binding-audit.md) defines the inventory and ownership rules. The [migration guide](docs/migration.md) covers breaking low-level changes, checked methods, and the compatibility convenience methods. [Validation](docs/validation.md) records what was actually run and the remaining gaps. - rdkit % cargo workspaces version patch - rdkit % cd rdkit-sys - rdkit-sys % cargo publish - rdkit-sys % cd .. - rdkit % cargo publish +Canonicalization, descriptors, and fingerprints follow the linked RDKit release. Persisted chemical indexes may need rebuilding when that release changes. ABI compatibility across arbitrary RDKit, Boost, or platform versions is not promised. +## Development -## Formatting -### C++ formatting -Clang formatting should be automatically applied when saving files in VSCode if you have the `clangd` extension installed. If you don't have it installed, you can install it from the marketplace. Else by right-clicking on the file and selecting `Format Document` should do the work. +```sh +cargo fmt --all --check +cargo test --workspace --locked +cargo clippy --workspace --all-targets --locked -- -D warnings +cargo doc --workspace --no-deps --locked +find rdkit-sys/wrapper -type f \( -name '*.h' -o -name '*.cc' \) -print0 | xargs -0 clang-format-18 --dry-run --Werror +``` -### Rust formatting -Rust formatting should be automatically applied when saving files in VSCode if you have the `rust-analyzer` extension installed. Else by running `cargo fmt` in the root directory the entire project will be formatted. \ No newline at end of file +Both crates remain at their existing versions during this unreleased modernization. Publishing requires a coordinated version decision for both crates because the low-level API changes are breaking. No release or tag is part of this work. diff --git a/ci/install-deps.sh b/ci/install-deps.sh new file mode 100644 index 0000000..2e19fc2 --- /dev/null +++ b/ci/install-deps.sh @@ -0,0 +1,13 @@ +set -euo pipefail +. /etc/os-release +case "$ID:$VERSION_ID" in + ubuntu:26.04) rdkit_package_version=202503.6-4 ;; + ubuntu:24.04) rdkit_package_version=202309.3-3build2 ;; + debian:13) rdkit_package_version=202503.1-4 ;; + *) printf 'Unsupported package target: %s %s\n' "$ID" "$VERSION_ID" >&2; exit 1 ;; +esac +apt-get update +DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ + build-essential ca-certificates curl git pkg-config \ + "librdkit-dev=$rdkit_package_version" libboost-dev libboost-serialization-dev libeigen3-dev +dpkg-query -W librdkit-dev libboost-dev libeigen3-dev diff --git a/ci/test-sanitizers.sh b/ci/test-sanitizers.sh new file mode 100644 index 0000000..9ffbdbf --- /dev/null +++ b/ci/test-sanitizers.sh @@ -0,0 +1,11 @@ +set -euo pipefail + +export CXXFLAGS="${CXXFLAGS:-} -fsanitize=address,undefined -fno-omit-frame-pointer" +export RUSTFLAGS="${RUSTFLAGS:-} -C link-arg=-lasan -C link-arg=-lubsan" +export CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER="env LD_PRELOAD=$(gcc -print-file-name=libasan.so)" +export ASAN_OPTIONS=detect_leaks=1 +export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 +export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-target/sanitizers}" + +cargo test -p rdkit --locked --test test_safety --test test_graphmol --test test_scaffold_network --test test_substruct --test test_mol_ops --test test_file_parsers +cargo test -p rdkit-sys --locked --tests diff --git a/docs/binding-audit.md b/docs/binding-audit.md new file mode 100644 index 0000000..f534d72 --- /dev/null +++ b/docs/binding-audit.md @@ -0,0 +1,62 @@ +# Binding audit and supported surface + +The baseline at `79a26ead54b2dbec2bedfc82976136b6c19017a6` had **145 callable CXX declarations in nine modules**. Every declaration, corresponding C++ shim, and high-level wrapper was reviewed for ownership, borrowing, mutation, nullability, exceptions, allocation pairing, bounds and thread traits. The branch currently has **189 callable declarations in eleven modules**, including bonds and conformers. The [complete name inventory](binding-inventory.md) defines that count; the three original Rust `PeriodicTableOps` helpers are reviewed but are not native declarations. + +These counts describe this repository's binding surface. They are not a percentage of all RDKit APIs or a proof of memory safety. There is no claim of complete coverage of every RDKit overload, class, Python wrapper, platform or algorithm. The selected scope is a useful molecule workflow: parse, inspect, edit, sanitize, standardize, fingerprint, describe, search, generate 2D coordinates and construct scaffold networks. + +## Ownership and aliasing + +Native objects exposed as owners now use `UniquePtr`. Inputs borrow the native object as `&T` or `Pin<&mut T>`, instead of borrowing a nullable shared owner. A clone of a shared pointer previously allowed two safe callers to obtain mutable access to the same molecule or parameter object. The new signatures require an exclusive owner borrow for mutation, including atom setters and parameter setters. + +Native atom, bond and conformer views borrow their molecule. Graph edits, coordinate regeneration, owner moves and destruction are blocked while those views are used. `AtomRef`, `Bond` and `Conformer` are read views; `Atom` and `ConformerMut` hold exclusive borrows. Atom and conformer access validates indices, and graph edits also reject invalid atomic numbers, invalid bond enums, self-bonds, duplicate bonds and nonexistent bonds. Integer inputs are checked before conversion to narrower native fields or enums. + +`ROMol::clone`, `RWMol::clone`, ROMol-to-RWMol conversion and tautomer extraction use native copies with independently owned atom/bond/conformer data. RWMol-to-ROMol conversion transfers the existing owner through C++'s actual base-class conversion; the former Rust `transmute` is gone. No safe Rust function exposes a raw owning pointer or accepts a raw pointer argument. The scaffold shim's internal shared-pointer input vector owns copies and does not expose shared native mutation to Rust. + +## Nulls, exceptions and allocations + +The two SMILES factories intentionally preserve RDKit's nullable `UniquePtr` result when parsing fails without throwing. Their high-level callers check it before constructing a molecule and preserve the existing `UnknownConversionError` behavior. This is the explicit exception to the otherwise checked molecule-factory contract. SMARTS and mol-block factories report null results as errors; empty SMILES and SMARTS remain valid empty molecules. + +All native callable declarations except the two infallible RWMol reference upcasts translate C++ exceptions through `Result`. Allocation, parsing, chemistry operations, property lookup, indexing and parameter construction are included. High-level fallible methods preserve those errors; existing convenience methods generally panic in Rust on a translated failure. This does not catch native undefined behavior or promise recovery from process-level allocation failure. + +Raw RDKit factory returns are immediately adopted by their matching C++ smart pointer. Chemistry-problem and substructure-result containers previously remained raw while potentially throwing reserve/push operations ran; they now acquire ownership immediately. Native destruction stays in C++ with the correct type. Sanitize-exception access checks nulls and uses a checked dynamic cast before requesting an atom-specific index. + +Periodic-table ownership is separate from the RDKit singleton: owned handles are copies. Valence lists are copied into owned vectors instead of exposing a static reference tied to native singleton destruction order. Two methods missing from RDKit 2023.09 use small compatibility shims: they call the native methods when present, otherwise use the 118-element table and the same row boundaries. Regression tests check every supported atomic number and an invalid one. + +## Threads + +Only the high-level, exclusively owned `ROMol` and `RWMol` opt into `Send`. They do not implement `Sync`, because apparently const RDKit chemistry operations can mutate caches. Native opaque types, borrowed views and auxiliary native owners do not gain unsafe thread traits. Compile-time assertions check these choices, and a runtime regression moves an owned molecule between threads and verifies independent copy mutation. + +The argument for `Send` depends on exclusive native ownership, native deep-copy behavior and the packaged RDKit build. It is not a general thread-safety guarantee for arbitrary RDKit builds, global extension state or caller-written unsafe code. + +## Review and regression map + +Each row covers every declaration in that module, including repetitive parameter getters/setters. Test files identify the exercised operations; their presence does not imply exhaustive branch or input coverage. Executed results belong in the [validation record](validation.md). + +| Area | Review findings and resulting contract | Regression evidence | +| --- | --- | --- | +| `ro_mol` | Unique molecule/parser owners; exclusive atom mutation; shared atom reads; nullable SMILES result checked; all throwing calls translated; checked subtype access; deep copies | High-level atom/graph tests; sys atom/ROMol tests; safety and borrowing tests | +| `rw_mol` | Native upcast replaces transmute; invalid SMARTS rejected; valid empty queries retained; checked graph edits and sanitization | Sys RWMol tests; graph/safety tests; borrow-failure fixtures | +| `bond` | Parent-borrowed read view; checked lookup/endpoints; no mutable alias; unknown returned enum representations remain representable | Graph/safety tests; bond edit borrow-failure fixture | +| `conformer` | Shared/exclusive parent borrows; checked atom positions and finite coordinate writes; 2D generation takes exclusive access | Safety tests; conformer regeneration borrow-failure fixture | +| `descriptors` | Unique property collection; borrowed molecule; owned result vectors; native exceptions translated | High-level and sys descriptor tests; downstream descriptor workflows | +| `fingerprint` | Unique native bit vectors; portable public-bit extraction; exact bit length; checked sizes; similarity edge cases | High-level and sys fingerprint tests; safety tests; downstream search workflows | +| `mol_ops` | Unique parameter objects; exclusive setters; copied hydrogen-operation results; exclusive cleanup/hybridization | High-level and sys mol-ops tests; downstream processing workflows | +| `mol_standardize` | Unique enumerator/result/cleanup/uncharger; native non-const uncharging requires mutation; owned yielded molecules; checked indices and decreasing iterator length | High-level graph and sys standardization tests; safety tests; downstream processing workflows | +| `periodic_table` | Copied table and valence-list ownership; translated invalid lookups; older-version row/max shims | High-level and sys periodic tests; exhaustive row and invalid-input regressions | +| `scaffold_network` | Unique parameters/network; copied input molecules; owned Rust node/edge/count data; native exceptions translated | High-level and sys scaffold tests, including default versus empty rules and edge direction | +| `substruct_match` | Unique parameters; exclusive setters; owned nested match vectors; immediate ownership of allocations | High-level and sys matching tests; downstream search workflows | +| SDF readers and Rust iterators | Complete delimiter lines; preserve title/dollar characters; propagate stream/UTF-8 failures; fused iteration; checked remaining length | Existing parser tests; added malformed-stream, record-content and iterator regressions | + +Six compile-fail fixtures reject an atom outliving its molecule, graph mutation while a bond is borrowed, coordinate regeneration while a conformer is borrowed, two simultaneous low-level mutable atom views, cloning a unique native owner, and mutation while an `AtomRef` remains in use. Positive cases also run in the safety tests. + +The ASan/UBSan lane instruments the C++ bridge and inlined native header code. The distribution's RDKit shared libraries and Rust code are not sanitizer-instrumented. It can expose real defects in executed paths, but it cannot establish whole-library memory safety. + +## Compatibility and remaining scope + +Compatibility means the crate builds and its selected behavioral tests pass against the exact native/platform matrix in [building](building.md), and the tested downstream workflows retain their documented behavior. It does not mean binary ABI interchangeability, identical chemistry results across every RDKit version, or source compatibility for every previous low-level caller. The [migration guide](migration.md) lists deliberate signature changes. + +The `Properties` collection exposes the descriptors registered by the selected native build; it does not claim all Python descriptors. Remaining gaps include dedicated ring-information APIs, additional named descriptors, 3D embedding and ensemble generation, ETKDG options, MMFF/UFF force fields, standalone Murcko helpers, reactions, drawing, databases and many advanced stereochemistry/query controls. Native Windows, macOS and arm64 are not in this PR's validated matrix. The current-upstream reference-package lane depends on a separately produced artifact. + +## Contributor work + +This implementation preserves and adapts useful work from [#19](https://github.com/rdkit-rs/rdkit/pull/19) (Alexandra Ebberg: invalid SMARTS), [#45](https://github.com/rdkit-rs/rdkit/pull/45) (Guillaume CHARIFI: explicit installation prefix), [#50](https://github.com/rdkit-rs/rdkit/pull/50), [#51](https://github.com/rdkit-rs/rdkit/pull/51), [#52](https://github.com/rdkit-rs/rdkit/pull/52), [#54](https://github.com/rdkit-rs/rdkit/pull/54) (Sharif Haason: modernization, atom/bond views, graph editing, fingerprints and coordinate direction), and [#56](https://github.com/rdkit-rs/rdkit/pull/56) (Chris Petersen: functional scaffold networks and tests). Ownership and exception signatures were reworked as part of this audit. Incorporation into a draft does not by itself resolve or merge the original requests. diff --git a/docs/binding-inventory.md b/docs/binding-inventory.md new file mode 100644 index 0000000..546ab24 --- /dev/null +++ b/docs/binding-inventory.md @@ -0,0 +1,100 @@ +# Callable binding inventory + +Baseline commit: `79a26ead54b2dbec2bedfc82976136b6c19017a6`. Names below are callable declarations inside the CXX `unsafe extern "C++"` blocks; shared structs, enums, Rust helper methods and overloads in upstream RDKit are not counted. Every baseline declaration and its native implementation was reviewed. A review entry does not mean every parameter combination has a runtime test. See [audit](binding-audit.md) for the ownership contracts and [validation](validation.md) for executed checks. + +| Module | Before | Branch | +| --- | ---: | ---: | +| `bond` | 0 | 13 | +| `conformer` | 0 | 9 | +| `descriptors` | 3 | 3 | +| `fingerprint` | 5 | 10 | +| `mol_ops` | 37 | 37 | +| `mol_standardize` | 10 | 10 | +| `periodic_table` | 18 | 18 | +| `ro_mol` | 35 | 36 | +| `rw_mol` | 5 | 13 | +| `scaffold_network` | 13 | 21 | +| `substruct_match` | 19 | 19 | +| Total | 145 | 189 | + +## bond + +[Bridge](../rdkit-sys/src/bridge/bond.rs) · [C++ shim](../rdkit-sys/wrapper/src/bond.cc) + +Baseline reviewed: new module. + +Added callable names reviewed: `get_num_bonds`, `get_bond_with_idx`, `get_bond_idx_between_atoms`, `bond_get_bond_type`, `bond_get_bond_type_as_double`, `bond_get_begin_atom_idx`, `bond_get_end_atom_idx`, `bond_get_other_atom_idx`, `bond_get_is_aromatic`, `bond_get_is_conjugated`, `bond_get_stereo`, `bond_get_bond_dir`, `bond_get_idx`. + +## conformer + +[Bridge](../rdkit-sys/src/bridge/conformer.rs) · [C++ shim](../rdkit-sys/wrapper/src/conformer.cc) + +Baseline reviewed: new module. + +Added callable names reviewed: `compute_2d_coords`, `get_num_conformers`, `get_conformer`, `get_conformer_mut`, `conformer_id`, `conformer_is_3d`, `conformer_num_atoms`, `conformer_position`, `conformer_set_position`. + +## descriptors + +[Bridge](../rdkit-sys/src/bridge/descriptors.rs) · [C++ shim](../rdkit-sys/wrapper/src/descriptors.cc) + +Baseline reviewed: `new_properties`, `get_property_names`, `compute_properties`. + +## fingerprint + +[Bridge](../rdkit-sys/src/bridge/fingerprint.rs) · [C++ shim](../rdkit-sys/wrapper/src/fingerprint.cc) + +Baseline reviewed: `rdk_fingerprint_mol`, `pattern_fingerprint_mol`, `morgan_fingerprint_mol`, `copy_explicit_bit_vect`, `explicit_bit_vect_to_u64_vec`. + +Added callable names reviewed: `explicit_bit_vect_num_bits`, `morgan_fingerprint_mol_with_params`, `rdk_fingerprint_mol_with_params`, `pattern_fingerprint_mol_with_params`, `maccs_fingerprint_mol`. + +## mol_ops + +[Bridge](../rdkit-sys/src/bridge/mol_ops.rs) · [C++ shim](../rdkit-sys/wrapper/src/mol_ops.cc) + +Baseline reviewed: `new_remove_hs_parameters`, `get_remove_degree_zero`, `set_remove_degree_zero`, `get_remove_higher_degrees`, `set_remove_higher_degrees`, `get_remove_only_h_neighbors`, `set_remove_only_h_neighbors`, `get_remove_isotopes`, `set_remove_isotopes`, `get_remove_and_track_isotopes`, `set_remove_and_track_isotopes`, `get_remove_dummy_neighbors`, `set_remove_dummy_neighbors`, `get_remove_defining_bond_stereo`, `set_remove_defining_bond_stereo`, `get_remove_with_wedged_bond`, `set_remove_with_wedged_bond`, `get_remove_with_query`, `set_remove_with_query`, `get_remove_mapped`, `set_remove_mapped`, `get_remove_in_s_groups`, `set_remove_in_s_groups`, `get_show_warnings`, `set_show_warnings`, `get_remove_nonimplicit`, `set_remove_nonimplicit`, `get_update_explicit_count`, `set_update_explicit_count`, `get_remove_hydrides`, `set_remove_hydrides`, `get_remove_nontetrahedral_neighbors`, `set_remove_nontetrahedral_neighbors`, `remove_hs_parameters`, `add_hs`, `romol_set_hybridization`, `clean_up`. + +## mol_standardize + +[Bridge](../rdkit-sys/src/bridge/mol_standardize.rs) · [C++ shim](../rdkit-sys/wrapper/src/mol_standardize.cc) + +Baseline reviewed: `tautomer_enumerator`, `tautomer_enumerate`, `tautomer_enumerator_result_tautomers_size`, `tautomer_enumerator_result_tautomers_at`, `tautomer_enumerator_canonicalize`, `default_cleanup_parameters`, `new_uncharger`, `uncharger_uncharge`, `fragment_parent`, `normalize`. + +## periodic_table + +[Bridge](../rdkit-sys/src/bridge/periodic_table.rs) · [C++ shim](../rdkit-sys/wrapper/src/periodic_table.cc) + +Baseline reviewed: `get_periodic_table`, `getAtomicWeight`, `getAtomicNumber`, `getElementSymbol`, `getElementName`, `getRvdw`, `getRcovalent`, `getRb0`, `getDefaultValence`, `getValenceList`, `getNouterElecs`, `getMostCommonIsotope`, `getMostCommonIsotopeMass`, `getMassForIsotope`, `getMaxAtomicNumber`, `getAbundanceForIsotope`, `moreElectroNegative`, `getRow`. + +Added callable names reviewed: `periodic_table_max_atomic_number`, `periodic_table_row`. + +The former native `getMaxAtomicNumber` and `getRow` declarations are Rust forwarding methods over the compatibility shims. Their Rust call syntax is preserved. + +## ro_mol + +[Bridge](../rdkit-sys/src/bridge/ro_mol.rs) · [C++ shim](../rdkit-sys/wrapper/src/ro_mol.cc) + +Baseline reviewed: `copy_mol`, `smiles_to_mol`, `smiles_to_mol_with_params`, `new_smiles_parser_params`, `smiles_parser_params_set_sanitize`, `smiles_parser_params_get_sanitize`, `mol_to_smiles`, `mol_to_molblock`, `detect_chemistry_problems`, `mol_sanitize_exception_type`, `atom_sanitize_exception_get_atom_idx`, `get_num_atoms`, `get_atom_with_idx`, `get_symbol`, `get_is_aromatic`, `get_atomic_num`, `get_formal_charge`, `get_total_num_hs`, `get_total_valence`, `set_formal_charge`, `set_num_explicit_hs`, `atom_update_property_cache`, `atom_set_hybridization`, `atom_get_hybridization`, `ro_mol_update_property_cache`, `set_int_prop`, `get_int_prop`, `set_float_prop`, `get_float_prop`, `set_bool_prop`, `get_bool_prop`, `set_prop`, `get_prop`, `get_num_radical_electrons`, `get_degree`. + +Added callable names reviewed: `get_atom_ref`. + +## rw_mol + +[Bridge](../rdkit-sys/src/bridge/rw_mol.rs) · [C++ shim](../rdkit-sys/wrapper/src/rw_mol.cc) + +Baseline reviewed: `rw_mol_from_mol_block`, `rw_mol_from_ro_mol`, `rw_mol_from_rw_mol`, `rw_mol_to_ro_mol`, `smarts_to_mol`. + +Added callable names reviewed: `rw_mol_as_ro_mol`, `new_rw_mol`, `rw_mol_as_ro_mol_mut`, `rw_mol_add_atom`, `rw_mol_add_bond`, `rw_mol_remove_atom`, `rw_mol_remove_bond`, `rw_mol_sanitize`. + +## scaffold_network + +[Bridge](../rdkit-sys/src/bridge/scaffold_network.rs) · [C++ shim](../rdkit-sys/wrapper/src/scaffold_network.cc) + +Baseline reviewed: `default_scaffold_network_params`, `new_scaffold_network_params`, `set_include_generic_scaffolds`, `include_generic_bond_scaffolds`, `include_scaffolds_without_attachments`, `include_scaffolds_with_attachments`, `keep_only_first_fragment`, `prune_before_fragmenting`, `flatten_isotopes`, `flatten_chirality`, `flatten_keep_largest`, `collect_mol_counts`, `default_scaffold_network`. + +Added callable names reviewed: `create_scaffold_network`, `update_scaffold_network`, `scaffold_network_nodes`, `scaffold_network_counts`, `scaffold_network_mol_counts`, `scaffold_network_edge_begin_indices`, `scaffold_network_edge_end_indices`, `scaffold_network_edge_types`. + +## substruct_match + +[Bridge](../rdkit-sys/src/bridge/substruct_match.rs) · [C++ shim](../rdkit-sys/wrapper/src/substruct_match.cc) + +Baseline reviewed: `substruct_match`, `new_substruct_match_parameters`, `get_use_chirality`, `get_use_enhanced_stereo`, `get_aromatic_matches_conjugated`, `get_use_query_query_matches`, `get_use_generic_matchers`, `get_recursion_possible`, `get_uniquify`, `set_use_chirality`, `set_use_enhanced_stereo`, `set_aromatic_matches_conjugated`, `set_use_query_query_matches`, `set_use_generic_matchers`, `set_recursion_possible`, `set_uniquify`, `substruct_matchvect_type_to_vec_substruct_match_item`, `substruct_match_item_query_atom_idx`, `substruct_match_item_mol_atom_idx`. diff --git a/docs/building.md b/docs/building.md new file mode 100644 index 0000000..34c6424 --- /dev/null +++ b/docs/building.md @@ -0,0 +1,77 @@ +# Building with packaged RDKit + +## Version decision, verified 2026-10-09 + +[RDKit 2026.09.1](https://github.com/rdkit/rdkit/releases/tag/Release_2026_09_1) is the current upstream release, published 2026-10-03. Upstream's newest release and the newest distro package are different things. + +[Ubuntu 26.04 LTS](https://documentation.ubuntu.com/release-notes/26.04/) was released 2026-04-23. It is the newest released stable Ubuntu on this verification date. [Ubuntu 26.10's schedule](https://documentation.ubuntu.com/release-notes/26.10/schedule/) places final release on 2026-10-15; its package archive is not our supported baseline. + +| Platform | RDKit / development package | Role | +| --- | --- | --- | +| Ubuntu 26.04 LTS x86_64 | 2025.03.6 / `202503.6-4` | Primary CI and installation target | +| Ubuntu 24.04 LTS x86_64 | 2023.09.3 / `202309.3-3build2` | Older supported CI target | +| Debian 13 x86_64 | 2025.03.1 / `202503.1-4` | Saved environment validation | +| Ubuntu 22.04 LTS | 2021.09.2 / `202109.2-1build1` | Too old for this binding surface | +| Ubuntu 25.10 | 2025.03.1 / `202503.1-4` | Interim release; not a CI target | +| Ubuntu 26.10 prerelease | 2025.03.6 / `202503.6-4` | No advantage over released 26.04 for this work | +| Upstream 2026.09.1 | Separate Ubuntu 26.04 reference package | Additional compatibility lane pending the package artifact | +| macOS, Windows, Linux arm64 | Varies | Not validated by this PR | + +Sources: [Ubuntu package versions](https://packages.ubuntu.com/librdkit-dev), [26.04 package](https://packages.ubuntu.com/resolute/librdkit-dev), [Debian 13 package](https://packages.debian.org/trixie/librdkit-dev). Both Ubuntu package pins were also checked against their actual apt repositories in clean containers. + +The LTS package supplies a matched native RDKit, Boost dependency set, and development headers through ordinary package management. The baseline can be installed without a custom binary distribution. Selecting it does not imply that it contains every fix or feature from newer upstream releases, or that Ubuntu Universe has the same support guarantees as Ubuntu Main. + +The project's [Debian packaging tutorial](https://github.com/rdkit-rs/rdkit-rs.github.io/blob/1d3778e/content/tutorials/forking-a-debian-package.md) explains the earlier need for newer upstream packages, isolated native builds and CI-produced artifacts. A separate reference-package effort carries that goal forward for current upstream on Ubuntu 26.04. Its artifact should be tested as an additional lane with an exact version and checksum, while keeping the distro installation path working. + +## Native installation + +Run from this checkout on one of the three listed Linux releases: + +```sh +sudo bash ci/install-deps.sh +cargo test --workspace --locked +``` + +The script installs the exact RDKit package above plus a C++ compiler, Boost development headers and serialization library, and Eigen headers. Rustup honors the pinned Rust 1.99.0 toolchain in `rust-toolchain.toml`. CI uses the committed Cargo lockfile. These are tested toolchain versions, not a claim that all older Rust compilers fail. + +The Ubuntu CI jobs run on a Linux x86_64 host inside digest-pinned Ubuntu containers. Package versions are explicit; other apt dependencies receive the distribution's current updates. This reproduces the RDKit/API baseline, not a bit-for-bit frozen operating system. If a pinned package leaves the active archive, use the corresponding Ubuntu snapshot and record that change rather than silently taking a different RDKit release. + +Install `clang-format-18` for C++ formatting. Standard Rust formatting works without nightly. + +## Prefixes and runtime linking + +By default, Linux uses `/usr`, Apple Silicon macOS uses `/opt/homebrew`, and Intel macOS uses `/usr/local`. These macOS paths are supported discovery conventions, not macOS validation evidence. Override them explicitly: + +```sh +RDKIT_PREFIX=/opt/rdkit cargo build --locked +``` + +`RDKIT_PREFIX` expects `include/rdkit/GraphMol/ROMol.h`, sibling dependency headers under `include`, optional `include/eigen3`, and native libraries under `lib`. `RDKIT_INCLUDE_DIR` overrides the directory containing `GraphMol`; `RDKIT_LIB_DIR` overrides the RDKit library directory. All inputs are tracked by Cargo so changes cause a rebuild. Cross compilation requires matching target libraries, a target compiler, and explicit paths; it is not in the tested matrix. + +```sh +RDKIT_PREFIX=/opt/rdkit \ +RDKIT_INCLUDE_DIR=/opt/rdkit/include/rdkit \ +RDKIT_LIB_DIR=/opt/rdkit/lib64 \ +cargo build --locked +``` + +Link-time discovery does not configure the runtime loader. Distro packages already install libraries in configured loader paths. With a private installation, set the loader path before running the executable: + +```sh +export LD_LIBRARY_PATH=/opt/rdkit/lib64${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} +cargo test --workspace --locked +``` + +Use the installation's matched RDKit and Boost libraries. Renaming a Boost SONAME or creating a symlink between incompatible Boost releases does not make their ABIs compatible. + +## Conda and other platforms + +An activated native Conda installation can use the existing feature: + +```sh +cargo test --workspace --features dynamic-linking-from-conda --locked +``` + +The high-level crate now forwards this feature to `rdkit-sys`. `RDKIT_PREFIX` takes precedence; otherwise the feature requires `CONDA_PREFIX`. Install native C++ development headers as well as shared libraries. A Python wheel alone is not a C++ development installation. A Conda package solve and native Windows build have not been tested here; the feature is not a promise of Windows support. + +The build reads Cargo's target OS and architecture instead of the build host's values. Unsupported targets fail explicitly. A full upstream source build remains an optional integration task; it is not required for the supported packaged targets. diff --git a/docs/migration.md b/docs/migration.md new file mode 100644 index 0000000..c4b4c92 --- /dev/null +++ b/docs/migration.md @@ -0,0 +1,61 @@ +# Migrating to the ownership API + +This branch deliberately changes the low-level API and a few high-level signatures. It does not change crate versions or publish a release. Consumers should test against this branch before a release is chosen. + +## Molecules and borrowed views + +`ROMol` and `RWMol` exclusively own their native molecules. `clone()` makes a native deep copy; `try_clone()` reports native exceptions. `RWMol::to_ro_mol()` consumes the editable owner through C++'s base-class conversion. No Rust layout cast is involved. + +Use `atom_ref(index)` or `atoms()` to read atoms through a shared molecule borrow. The existing `atom_with_idx(index)` needs a mutable molecule and returns an exclusive atom view; `try_atom_with_idx(index)` reports a bad index. Bond and conformer views are also tied to their molecule. Finish using a view before moving, editing or dropping its owner. + +```rust +use rdkit::{BondType, RWMol}; + +let mut mol = RWMol::new(); +let carbon = mol.add_atom(6)?; +let oxygen = mol.add_atom(8)?; +mol.add_bond(carbon, oxygen, BondType::SINGLE)?; +mol.sanitize()?; +assert_eq!(mol.atom_ref(oxygen)?.symbol(), "O"); +assert_eq!(mol.as_smiles(), "CO"); +``` + +Atom formal charges and explicit hydrogen counts are checked before conversion to RDKit's narrower storage. Graph edits validate atom indices, bond types, duplicate bonds and self-bonds. Successful edits can still produce chemically invalid molecules: explicitly call `sanitize()` or update property caches as appropriate to the workflow. A sanitization error does not roll the molecule back to its previous state. + +Coordinate generation takes a mutable molecule. `conformer(id)` reads an existing conformer; `conformer_mut(id)` permits checked coordinate changes. An ID of `-1` asks RDKit for the default conformer. Only 2D generation is added here; these coordinate views do not imply ETKDG, MMFF or UFF support. + +Owned molecules remain `Send`, so they can move to another thread or be protected by a mutex. They are not `Sync`: RDKit can update caches in apparently const operations. Borrowed views and raw native types do not promise cross-thread access. Do not add an unsafe `Sync` implementation to bypass this restriction. + +## Fallible chemistry and parsing + +Potentially throwing native calls return `Result` at the bridge. High-level `try_` alternatives cover molecule writing/copying, fingerprints, descriptor evaluation, hydrogen operations, standardization, periodic-table lookups and substructure matching. Existing convenience methods generally retain their return types and panic in Rust if a translated native exception occurs. Use fallible methods where input errors are expected. + +`RWMol::from_smarts` now returns `Result` and rejects a native null result. The empty string remains a valid empty query, matching RDKit. `RWMol::try_from_mol_block` preserves an error; the existing `from_mol_block` remains an `Option` convenience method. Code that explicitly expects the old SMARTS error type must migrate to `RWMolError` or convert the error to text. + +`MolSanitizeException` gains `Other { kind: String }`, preserving unknown native exception kinds instead of panicking. Exhaustive matches need a fallback. Existing `ROMolError` display text is retained; its exception variant still carries native detail. + +`Uncharger::uncharge` and `try_uncharge` require `&mut self`, matching the native non-const method. Declare an uncharger binding mutable before calling them. Public raw owner fields have been hidden where they could invalidate the wrapper's invariants. + +Periodic-table valence lists now return an owned `Vec` at the high level and an owned C++ vector at the bridge. Callers can keep using `.as_slice()`; code explicitly naming `&'static CxxVector` must change its type. This removes the assumption that RDKit's singleton storage outlives every Rust reference. + +SDF iterators keep their existing item shapes. An I/O failure is returned once, followed by exhaustion. Invalid UTF-8 returns an error for that record; later delimiter-separated records can still be read. Records end at a complete `$$$$` line, and a missing final delimiter is accepted. Embedded dollar characters and an empty molecule title are preserved. + +## Fingerprints, tautomers and scaffolds + +Default fingerprints retain their previous parameters. New configurable Morgan, pattern and RDK fingerprints validate sizes and parameters; MACCS exposes the native 167-bit vector including its unused first bit. The bit vector length is exactly the native length, including nonmultiples of 64, and extraction no longer depends on Boost's internal block width. + +Use `tanimoto_similarity` for the clearly named operation. The historical `tanimoto_distance` remains an alias for similarity to preserve callers' numerical behavior. Two empty or all-zero equal-length fingerprints have similarity 1; different lengths cause a Rust assertion instead of silently comparing a prefix. + +Tautomer iteration reports the remaining count and returns independent molecule copies. `get(index)` and `try_next()` expose native errors without the iterator convenience method's panic behavior. + +Scaffold networks now return owned nodes, edges and count data. Default fragmentation rules and explicitly empty bond-breaker rules are different choices. Edge direction and empty ring-free scaffolds follow RDKit; see the scaffold tests before imposing application-specific filtering. + +## Low-level callers + +Replace `SharedPtr` owners with `UniquePtr`. Borrow native inputs as `&T`; use `owner.pin_mut()` for `Pin<&mut T>` inputs. Handle the new `Result` values. Most factories turn a missing native object into an error. The two SMILES factories preserve nullable results to distinguish a nonthrowing parse failure; high-level constructors check those results before constructing a molecule. Safe borrowed inputs no longer accept a nullable smart-pointer reference. The consuming RWMol conversion still accepts a unique owner and checks it for null. + +Borrowed native outputs cannot outlive their inputs. Cloning a smart pointer to manufacture another mutable path is no longer supported. The bridge's two reference upcasts are infallible; the remaining native calls translate exceptions. The [binding audit](binding-audit.md) records the reviewed surface and its limits. + +For native installation, prefix overrides and the supported platform matrix, see [building](building.md). The matching native libraries must be present at runtime; this branch uses dynamic linking. + +Supported native releases can legitimately return different chemistry results. One canonicalization regression yields a valid, reparsable molecule on 2023.09 and a kekulization error on 2025.03. The carbon covalent-radius table entry is 0.68 in the older package and 0.76 in the newer ones. Tests explicitly cover those observed outcomes; the wrappers preserve the selected native library's behavior. diff --git a/docs/validation.md b/docs/validation.md new file mode 100644 index 0000000..ca5a853 --- /dev/null +++ b/docs/validation.md @@ -0,0 +1,54 @@ +# Validation record + +Recorded 2026-10-09 for this modernization. The PR's GitHub checks identify the tested final commit; this document records the local validation and its limits. No release, tag or merge is included. + +## Executed local checks + +| Environment / check | Result | +| --- | --- | +| Ubuntu 26.04 amd64, RDKit `202503.6-4`, GCC 15 | 107 workspace tests passed, including the compile-fail harness | +| Ubuntu 24.04 amd64, RDKit `202309.3-3build2`, GCC 13 | 107 workspace tests passed, including the compile-fail harness | +| Saved Debian 13 amd64, RDKit `202503.1-4`, GCC 14 | 107 tests passed with `--workspace --all-targets`; examples compiled and stable benchmark smoke ran | +| Borrow checking | All six expected compile failures matched their checked-in diagnostics | +| Focused regressions | 17 safety/correctness tests passed on both Ubuntu versions and the saved environment | +| Ubuntu 26.04 C++ ASan + UBSan | 78 targeted high-level and sys tests passed; leak detection enabled; no reported findings | +| Actual downstream application in an isolated checkout | All 50 existing tests passed with both crates patched to this branch | +| Rust formatting | `cargo fmt --all --check` passed on pinned Rust 1.99.0 | +| C++ formatting | clang-format 18 dry run with warnings as errors passed | +| Clippy | All-targets workspace checking with warnings denied passed in the saved environment and both Ubuntu versions | +| Rustdoc | Workspace documentation with warnings denied passed on both Ubuntu versions | +| Conda feature forwarding | All-features workspace check passed with the distro prefix on Ubuntu 26.04; this is not a Conda package solve | +| Whitespace | `git diff --check` passed | + +The 107 count includes one Rust harness test that runs six compile-fail fixtures; it does not count those fixtures as six additional runtime tests. Tests are behavioral samples, not exhaustive input or instruction coverage. Empty test/example/doc-test harnesses are not added to the count. The native declaration inventory is separate from the test count. + +The isolated downstream validation exercised existing parsing, processing, descriptor/fingerprint, indexing/search and API workflows. Only dependency path overrides, necessary lockfile resolution and local build-output discovery were changed in the isolated checkout. No downstream application source or tests were changed or pushed. A public error-display regression found by that suite was fixed in the bindings while preserving native detail in the error payload. Private downstream implementation/data are intentionally not reproduced here. + +## Reproduce + +Install the pinned native package as described in [building](building.md), then run: + +```sh +cargo fmt --all --check +cargo test --workspace --locked +cargo clippy --workspace --all-targets --locked -- -D warnings +RUSTDOCFLAGS='-D warnings' cargo doc --workspace --no-deps --locked +CONDA_PREFIX=/usr cargo check --workspace --all-features --locked +bash ci/test-sanitizers.sh +``` + +The last command is the Linux x86_64 GCC sanitizer lane. It instruments the C++ bridge and code instantiated from native headers, links ASan/UBSan, and preloads ASan only for test execution through Cargo's target runner. It tests the safety, molecule, scaffold, matching, hydrogen and parser paths plus all sys tests. Rust and the packaged RDKit shared libraries are not themselves rebuilt with sanitizers. This run provides useful executed-path evidence, not a whole-library memory-safety proof. + +The all-features command checks feature forwarding/prefix discovery against the installed distro package. It does not validate a real Conda solve. Use a separate target directory for sanitizer builds when overriding `CARGO_TARGET_DIR`. + +## Failures investigated and corrected + +The first Ubuntu 24.04 build exposed header organization and periodic-table methods that differ in RDKit 2023.09. The bridge now includes the common parser header and uses small checked compatibility shims for row/max-atomic-number lookup. Every atomic number from 0 through 118 is tested for row lookup. + +Two existing tests assumed newer native chemistry data or behavior: a tautomer canonicalization case and carbon's covalent radius. The tests now assert the specific observed results of the supported native versions. The canonicalization success case also requires no chemistry problems and a successful sanitized reparse; failures must match the expected native exception. The binding does not substitute one release's chemistry behavior for another's. + +Initial development runs also exposed the old nightly-only benchmark, missing compile-fail snapshots, and Clippy failures. The benchmark now uses stable timing/black-box operations, the six diagnostics are checked in, and the lint failures were corrected. Final results above supersede those development failures. + +## Not run or not established + +Current-upstream RDKit 2026.09.1 validation awaits the separate Ubuntu 26.04 reference-package artifact and its checksum/install contract. It must be added as its own compatibility lane without removing the distro matrix. macOS, Windows, Linux arm64, a real Conda environment, Miri, and sanitizer-instrumented RDKit/Rust builds were not run. Miri alone cannot validate these native C++ algorithms. No fuzzing campaign, whole-upstream API coverage or general memory-safety proof is claimed. diff --git a/rdkit-sys/README.md b/rdkit-sys/README.md index 31da49e..c0f4e51 100644 --- a/rdkit-sys/README.md +++ b/rdkit-sys/README.md @@ -1,51 +1,13 @@ -RDKit-Sys ---- +# rdkit-sys -Rust code that binds to the C++ rdkit library! +CXX bindings to selected RDKit C++ functionality. This crate is a member of the [rdkit workspace](..) and underpins the safe [rdkit crate](https://crates.io/crates/rdkit). -How does it work? ---- +Install the native library using the workspace [build instructions](../docs/building.md). The bridge uses C++20, exclusive owning pointers, borrowed references tied to their owner, and exception translation. See the [binding audit](../docs/binding-audit.md) and [migration guide](../docs/migration.md) before calling the low-level API directly. -RDKit is a C++ mega-library, full of cheminformatics wisdom. We don't want to rewrite RDKit in Rust, we should instead meet somewhere in the middle and -"bridge" Rust to C++ through some wrappers. +The public low-level surface intentionally does not mirror every C++ overload. CXX checks bridge types; ownership, aliasing, nullability, and exception contracts still require manual review and regression testing. -The goal is to do 1-1 bindings with the C++ library, exposing all the classes as we need them. The goal is _not_ to create -a high-level functionality like the MinimalLib (cffiwrapper). Our goal is to expose the building blocks. If you're looking -for idiomatic Rust, check out the [rdkit](https://crates.io/crate/rdkit) crate. +```sh +cargo test -p rdkit-sys --locked +``` -Prerequisites ---- - -On Mac: - - brew install rdkit - -Also known to work with conda-managed RDKit, be sure to set the `dynamic-linking-from-conda` feature. Not as tested, please open an issue if you have a hard time. - -Testing ---- - -Or just run the test suite: - - cargo test - -TODO ---- - - - [ ] figure out how to `cargo publish` without `--no-verify` (otherwise it detects changes outside of OUTDIR) - - [X] specify path to RDKit's cffiwrapper.h and all required search paths for other dependent headers - - [X] use conditional rebuild logic to make the library build experience more reliable (for now, if you get stuck, try `cargo clean` and retry with `cargo build -vv`) - -Related Documentation ---- - - - https://www.rdkit.org/docs/cppapi/index.html - - https://cxx.rs/ - -Prior art ---- - - - https://github.com/apahl/rdkit_cxx - - [rdkafka's excellent librdkafka build.rs](https://github.com/fede1024/rust-rdkafka/blob/master/rdkafka-sys/build.rs) - - https://iwatobipen.wordpress.com/2022/01/29/use-rdkit-from-rust-rdkit-rdkitcffi-rust/ - - [an attempt at using rdkit in rust but without docs on how to build rdkit](https://github.com/iwatobipen/rust_rdkit/) +References: [RDKit C++ API](https://www.rdkit.org/docs/cppapi/index.html), [CXX](https://cxx.rs/), and [prior rdkit_cxx work](https://github.com/apahl/rdkit_cxx). diff --git a/rdkit-sys/tests/test_periodic_table.rs b/rdkit-sys/tests/test_periodic_table.rs index eb6edcb..320364b 100644 --- a/rdkit-sys/tests/test_periodic_table.rs +++ b/rdkit-sys/tests/test_periodic_table.rs @@ -81,7 +81,10 @@ fn test_getRcovalent() { let rcovalent = periodic_table .getRcovalent(6) .expect("RDKit operation failed"); - assert_eq!(rcovalent, 0.76); + assert!( + [0.68, 0.76].contains(&rcovalent), + "unexpected carbon radius: {rcovalent}" + ); } #[test] diff --git a/tests/test_periodic_table.rs b/tests/test_periodic_table.rs index e1f022b..430742b 100644 --- a/tests/test_periodic_table.rs +++ b/tests/test_periodic_table.rs @@ -45,7 +45,10 @@ fn test_radius_van_der_waals() { #[test] fn test_radius_covalent() { let radius = PeriodicTable::get_radius_covalent(6); - assert_eq!(radius, 0.76); + assert!( + [0.68, 0.76].contains(&radius), + "unexpected carbon radius: {radius}" + ); } #[test] From fbb5e24f4cad16a8486ed2899a4f83c00ca4e070 Mon Sep 17 00:00:00 2001 From: Xavier Lange Date: Fri, 9 Oct 2026 20:42:20 +0000 Subject: [PATCH 4/8] Avoid word-count overflow independently of native pointer width --- rdkit-sys/wrapper/src/fingerprint.cc | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/rdkit-sys/wrapper/src/fingerprint.cc b/rdkit-sys/wrapper/src/fingerprint.cc index edf9a47..0ffca83 100644 --- a/rdkit-sys/wrapper/src/fingerprint.cc +++ b/rdkit-sys/wrapper/src/fingerprint.cc @@ -25,8 +25,9 @@ std::unique_ptr copy_explicit_bit_vect(const ExplicitBitVect &o } std::unique_ptr> explicit_bit_vect_to_u64_vec(const ExplicitBitVect &bitvect) { - auto words = std::make_unique>((static_cast(bitvect.getNumBits()) + 63u) / 64u, 0); - for (unsigned int i = 0; i < bitvect.getNumBits(); ++i) { + const auto num_bits = bitvect.getNumBits(); + auto words = std::make_unique>(num_bits / 64u + (num_bits % 64u != 0), 0); + for (unsigned int i = 0; i < num_bits; ++i) { if (bitvect.getBit(i)) { (*words)[i / 64u] |= uint64_t{1} << (i % 64u); } } return words; @@ -49,4 +50,4 @@ std::unique_ptr pattern_fingerprint_mol_with_params(const ROMol std::unique_ptr maccs_fingerprint_mol(const ROMol &mol) { return checked_owned(MACCSFingerprints::getFingerprintAsBitVect(mol)); } -} // namespace RDKit \ No newline at end of file +} // namespace RDKit From 18ed53359fbbd21df813b23868d9f5a02261cc4c Mon Sep 17 00:00:00 2001 From: Xavier Lange Date: Fri, 9 Oct 2026 20:42:51 +0000 Subject: [PATCH 5/8] Apply the repository alignment style to fingerprint storage --- rdkit-sys/wrapper/src/fingerprint.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rdkit-sys/wrapper/src/fingerprint.cc b/rdkit-sys/wrapper/src/fingerprint.cc index 0ffca83..adcde49 100644 --- a/rdkit-sys/wrapper/src/fingerprint.cc +++ b/rdkit-sys/wrapper/src/fingerprint.cc @@ -26,7 +26,7 @@ std::unique_ptr copy_explicit_bit_vect(const ExplicitBitVect &o std::unique_ptr> explicit_bit_vect_to_u64_vec(const ExplicitBitVect &bitvect) { const auto num_bits = bitvect.getNumBits(); - auto words = std::make_unique>(num_bits / 64u + (num_bits % 64u != 0), 0); + auto words = std::make_unique>(num_bits / 64u + (num_bits % 64u != 0), 0); for (unsigned int i = 0; i < num_bits; ++i) { if (bitvect.getBit(i)) { (*words)[i / 64u] |= uint64_t{1} << (i % 64u); } } From cd2d55e17a6bb01ad59e28028e653b0b1d5a836b Mon Sep 17 00:00:00 2001 From: Xavier Lange Date: Fri, 9 Oct 2026 21:30:19 +0000 Subject: [PATCH 6/8] Support RDKit 2026 native enums and noncopyable periodic tables --- docs/binding-audit.md | 10 +-- docs/binding-inventory.md | 4 + docs/migration.md | 4 +- rdkit-sys/src/bridge/bond.rs | 5 +- rdkit-sys/src/bridge/periodic_table.rs | 1 + rdkit-sys/src/bridge/ro_mol.rs | 1 - rdkit-sys/tests/test_descriptors.rs | 11 ++- rdkit-sys/wrapper/include/bond.h | 8 +- rdkit-sys/wrapper/include/periodic_table.h | 41 ++++++++- rdkit-sys/wrapper/include/ro_mol.h | 3 +- rdkit-sys/wrapper/src/bond.cc | 96 ++++++++++++++++++++-- rdkit-sys/wrapper/src/periodic_table.cc | 18 ++-- rdkit-sys/wrapper/src/ro_mol.cc | 31 ++++++- rdkit-sys/wrapper/src/rw_mol.cc | 6 +- tests/test_descriptors.rs | 13 ++- tests/test_safety.rs | 84 +++++++++++++++++++ 16 files changed, 292 insertions(+), 44 deletions(-) diff --git a/docs/binding-audit.md b/docs/binding-audit.md index f534d72..8fa855d 100644 --- a/docs/binding-audit.md +++ b/docs/binding-audit.md @@ -8,7 +8,7 @@ These counts describe this repository's binding surface. They are not a percenta Native objects exposed as owners now use `UniquePtr`. Inputs borrow the native object as `&T` or `Pin<&mut T>`, instead of borrowing a nullable shared owner. A clone of a shared pointer previously allowed two safe callers to obtain mutable access to the same molecule or parameter object. The new signatures require an exclusive owner borrow for mutation, including atom setters and parameter setters. -Native atom, bond and conformer views borrow their molecule. Graph edits, coordinate regeneration, owner moves and destruction are blocked while those views are used. `AtomRef`, `Bond` and `Conformer` are read views; `Atom` and `ConformerMut` hold exclusive borrows. Atom and conformer access validates indices, and graph edits also reject invalid atomic numbers, invalid bond enums, self-bonds, duplicate bonds and nonexistent bonds. Integer inputs are checked before conversion to narrower native fields or enums. +Native atom, bond and conformer views borrow their molecule. Graph edits, coordinate regeneration, owner moves and destruction are blocked while those views are used. `AtomRef`, `Bond` and `Conformer` are read views; `Atom` and `ConformerMut` hold exclusive borrows. Atom and conformer access validates indices, and graph edits also reject invalid atomic numbers, invalid bond enums, self-bonds, duplicate bonds and nonexistent bonds. Integer inputs are checked before conversion to narrower native fields or enums. Bond type, direction, stereo and atom hybridization use bridge-owned enums with explicit native enumerator mappings, independent of the native enum width. RDKit 2026.09 changed these native types to one byte; older supported packages use wider enums. Invalid input values and unsupported native values become translated exceptions. Atropisomer stereo values are mapped when the native headers expose them, using compile-time feature detection. `ROMol::clone`, `RWMol::clone`, ROMol-to-RWMol conversion and tautomer extraction use native copies with independently owned atom/bond/conformer data. RWMol-to-ROMol conversion transfers the existing owner through C++'s actual base-class conversion; the former Rust `transmute` is gone. No safe Rust function exposes a raw owning pointer or accepts a raw pointer argument. The scaffold shim's internal shared-pointer input vector owns copies and does not expose shared native mutation to Rust. @@ -20,7 +20,7 @@ All native callable declarations except the two infallible RWMol reference upcas Raw RDKit factory returns are immediately adopted by their matching C++ smart pointer. Chemistry-problem and substructure-result containers previously remained raw while potentially throwing reserve/push operations ran; they now acquire ownership immediately. Native destruction stays in C++ with the correct type. Sanitize-exception access checks nulls and uses a checked dynamic cast before requesting an atom-specific index. -Periodic-table ownership is separate from the RDKit singleton: owned handles are copies. Valence lists are copied into owned vectors instead of exposing a static reference tied to native singleton destruction order. Two methods missing from RDKit 2023.09 use small compatibility shims: they call the native methods when present, otherwise use the 118-element table and the same row boundaries. Regression tests check every supported atomic number and an invalid one. +Periodic-table ownership is separate from the RDKit singleton: owned handles are stateless shim objects whose const methods retrieve the singleton for each call. They neither retain a borrowed pointer nor destroy the singleton. This also supports RDKit 2026.09, which deletes the native copy constructor. Valence lists are copied into owned vectors instead of exposing a static reference tied to native singleton destruction order. Two methods missing from RDKit 2023.09 use small compatibility shims: they call the native methods when present, otherwise use the 118-element table and the same row boundaries. Regression tests check every supported atomic number and an invalid one. ## Threads @@ -36,13 +36,13 @@ Each row covers every declaration in that module, including repetitive parameter | --- | --- | --- | | `ro_mol` | Unique molecule/parser owners; exclusive atom mutation; shared atom reads; nullable SMILES result checked; all throwing calls translated; checked subtype access; deep copies | High-level atom/graph tests; sys atom/ROMol tests; safety and borrowing tests | | `rw_mol` | Native upcast replaces transmute; invalid SMARTS rejected; valid empty queries retained; checked graph edits and sanitization | Sys RWMol tests; graph/safety tests; borrow-failure fixtures | -| `bond` | Parent-borrowed read view; checked lookup/endpoints; no mutable alias; unknown returned enum representations remain representable | Graph/safety tests; bond edit borrow-failure fixture | +| `bond` | Parent-borrowed read view; checked lookup/endpoints; no mutable alias; explicit enum mappings independent of native ABI; unsupported native values return errors | Graph/safety tests; bond edit borrow-failure fixture | | `conformer` | Shared/exclusive parent borrows; checked atom positions and finite coordinate writes; 2D generation takes exclusive access | Safety tests; conformer regeneration borrow-failure fixture | | `descriptors` | Unique property collection; borrowed molecule; owned result vectors; native exceptions translated | High-level and sys descriptor tests; downstream descriptor workflows | | `fingerprint` | Unique native bit vectors; portable public-bit extraction; exact bit length; checked sizes; similarity edge cases | High-level and sys fingerprint tests; safety tests; downstream search workflows | | `mol_ops` | Unique parameter objects; exclusive setters; copied hydrogen-operation results; exclusive cleanup/hybridization | High-level and sys mol-ops tests; downstream processing workflows | | `mol_standardize` | Unique enumerator/result/cleanup/uncharger; native non-const uncharging requires mutation; owned yielded molecules; checked indices and decreasing iterator length | High-level graph and sys standardization tests; safety tests; downstream processing workflows | -| `periodic_table` | Copied table and valence-list ownership; translated invalid lookups; older-version row/max shims | High-level and sys periodic tests; exhaustive row and invalid-input regressions | +| `periodic_table` | Owned table facade and copied valence lists; translated invalid lookups; older-version row/max shims | High-level and sys periodic tests; exhaustive row and invalid-input regressions | | `scaffold_network` | Unique parameters/network; copied input molecules; owned Rust node/edge/count data; native exceptions translated | High-level and sys scaffold tests, including default versus empty rules and edge direction | | `substruct_match` | Unique parameters; exclusive setters; owned nested match vectors; immediate ownership of allocations | High-level and sys matching tests; downstream search workflows | | SDF readers and Rust iterators | Complete delimiter lines; preserve title/dollar characters; propagate stream/UTF-8 failures; fused iteration; checked remaining length | Existing parser tests; added malformed-stream, record-content and iterator regressions | @@ -55,7 +55,7 @@ The ASan/UBSan lane instruments the C++ bridge and inlined native header code. T Compatibility means the crate builds and its selected behavioral tests pass against the exact native/platform matrix in [building](building.md), and the tested downstream workflows retain their documented behavior. It does not mean binary ABI interchangeability, identical chemistry results across every RDKit version, or source compatibility for every previous low-level caller. The [migration guide](migration.md) lists deliberate signature changes. -The `Properties` collection exposes the descriptors registered by the selected native build; it does not claim all Python descriptors. Remaining gaps include dedicated ring-information APIs, additional named descriptors, 3D embedding and ensemble generation, ETKDG options, MMFF/UFF force fields, standalone Murcko helpers, reactions, drawing, databases and many advanced stereochemistry/query controls. Native Windows, macOS and arm64 are not in this PR's validated matrix. The current-upstream reference-package lane depends on a separately produced artifact. +The `Properties` collection exposes the descriptors registered by the selected native build; it does not claim all Python descriptors. RDKit 2026.09 corrects the registered `chi2n`/`chi2v` results, which return chi3 values in the older tested packages. Standalone native probes confirmed that the newer registry agrees with direct chi2 calculations; descriptor regressions accept the exact paired native results while checking the complete property set. Remaining gaps include dedicated ring-information APIs, additional named descriptors, 3D embedding and ensemble generation, ETKDG options, MMFF/UFF force fields, standalone Murcko helpers, reactions, drawing, databases and many advanced stereochemistry/query controls. Native Windows and macOS remain outside the matrix. The package and platform lanes, including the current-upstream reference artifact and arm64 scope, are listed in [building](building.md); only executed results in [validation](validation.md) count as validated. ## Contributor work diff --git a/docs/binding-inventory.md b/docs/binding-inventory.md index 546ab24..79a7286 100644 --- a/docs/binding-inventory.md +++ b/docs/binding-inventory.md @@ -19,6 +19,8 @@ Baseline commit: `79a26ead54b2dbec2bedfc82976136b6c19017a6`. Names below are cal ## bond +The bond enums are bridge-owned values, not aliases for the native C++ enums. Checked mappings support the differing native enum widths in RDKit 2023/2025 and 2026; atom hybridization follows the same contract in `ro_mol`. The callable names and counts are unchanged. + [Bridge](../rdkit-sys/src/bridge/bond.rs) · [C++ shim](../rdkit-sys/wrapper/src/bond.cc) Baseline reviewed: new module. @@ -61,6 +63,8 @@ Baseline reviewed: `tautomer_enumerator`, `tautomer_enumerate`, `tautomer_enumer ## periodic_table +The Rust `PeriodicTable` opaque type names the owned C++ `RustPeriodicTable` facade. Its methods query the native singleton without exposing or owning it; this avoids relying on a native copy constructor, which RDKit 2026.09 deletes. Public Rust callable signatures and counts are unchanged. + [Bridge](../rdkit-sys/src/bridge/periodic_table.rs) · [C++ shim](../rdkit-sys/wrapper/src/periodic_table.cc) Baseline reviewed: `get_periodic_table`, `getAtomicWeight`, `getAtomicNumber`, `getElementSymbol`, `getElementName`, `getRvdw`, `getRcovalent`, `getRb0`, `getDefaultValence`, `getValenceList`, `getNouterElecs`, `getMostCommonIsotope`, `getMostCommonIsotopeMass`, `getMassForIsotope`, `getMaxAtomicNumber`, `getAbundanceForIsotope`, `moreElectroNegative`, `getRow`. diff --git a/docs/migration.md b/docs/migration.md index c4b4c92..ee31b0f 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -36,7 +36,7 @@ Potentially throwing native calls return `Result` at the bridge. High-level `try `Uncharger::uncharge` and `try_uncharge` require `&mut self`, matching the native non-const method. Declare an uncharger binding mutable before calling them. Public raw owner fields have been hidden where they could invalidate the wrapper's invariants. -Periodic-table valence lists now return an owned `Vec` at the high level and an owned C++ vector at the bridge. Callers can keep using `.as_slice()`; code explicitly naming `&'static CxxVector` must change its type. This removes the assumption that RDKit's singleton storage outlives every Rust reference. +Periodic-table valence lists now return an owned `Vec` at the high level and an owned C++ vector at the bridge. Callers can keep using `.as_slice()`; code explicitly naming `&'static CxxVector` must change its type. This removes the assumption that RDKit's singleton storage outlives every Rust reference. The opaque low-level table handle owns a stateless C++ facade that queries the native singleton for each call; it does not copy or destroy that singleton. Existing Rust table methods retain their signatures. SDF iterators keep their existing item shapes. An I/O failure is returned once, followed by exhaustion. Invalid UTF-8 returns an error for that record; later delimiter-separated records can still be read. Records end at a complete `$$$$` line, and a missing final delimiter is accepted. Embedded dollar characters and an empty molecule title are preserved. @@ -58,4 +58,4 @@ Borrowed native outputs cannot outlive their inputs. Cloning a smart pointer to For native installation, prefix overrides and the supported platform matrix, see [building](building.md). The matching native libraries must be present at runtime; this branch uses dynamic linking. -Supported native releases can legitimately return different chemistry results. One canonicalization regression yields a valid, reparsable molecule on 2023.09 and a kekulization error on 2025.03. The carbon covalent-radius table entry is 0.68 in the older package and 0.76 in the newer ones. Tests explicitly cover those observed outcomes; the wrappers preserve the selected native library's behavior. +Supported native releases can legitimately return different chemistry results. One canonicalization regression yields a valid, reparsable molecule on 2023.09 and a kekulization error on 2025.03. The carbon covalent-radius table entry is 0.68 in the older package and 0.76 in the newer ones. The registered `chi2n`/`chi2v` descriptors also change in 2026.09: they agree with direct chi2 calculations, while the older tested registries return chi3 values under those names. Tests explicitly cover those observed outcomes; the wrappers preserve the selected native library's behavior. diff --git a/rdkit-sys/src/bridge/bond.rs b/rdkit-sys/src/bridge/bond.rs index 2093575..257b1ff 100644 --- a/rdkit-sys/src/bridge/bond.rs +++ b/rdkit-sys/src/bridge/bond.rs @@ -36,6 +36,8 @@ pub mod ffi { STEREOE, STEREOCIS, STEREOTRANS, + STEREOATROPCW, + STEREOATROPCCW, } #[repr(i32)] @@ -55,9 +57,6 @@ pub mod ffi { pub type ROMol = crate::ro_mol_ffi::ROMol; pub type Bond; - pub type BondType; - pub type BondStereo; - pub type BondDir; pub fn get_num_bonds(mol: &ROMol, only_heavy: bool) -> Result; pub fn get_bond_with_idx(mol: &ROMol, idx: u32) -> Result<&Bond>; diff --git a/rdkit-sys/src/bridge/periodic_table.rs b/rdkit-sys/src/bridge/periodic_table.rs index 56ccab7..6fb3e07 100644 --- a/rdkit-sys/src/bridge/periodic_table.rs +++ b/rdkit-sys/src/bridge/periodic_table.rs @@ -7,6 +7,7 @@ use ffi::PeriodicTable; #[cxx::bridge(namespace = "RDKit")] pub mod ffi { unsafe extern "C++" { + #[cxx_name = "RustPeriodicTable"] type PeriodicTable; include!("wrapper/include/periodic_table.h"); pub fn get_periodic_table() -> Result>; diff --git a/rdkit-sys/src/bridge/ro_mol.rs b/rdkit-sys/src/bridge/ro_mol.rs index 51e796d..4b429b1 100644 --- a/rdkit-sys/src/bridge/ro_mol.rs +++ b/rdkit-sys/src/bridge/ro_mol.rs @@ -21,7 +21,6 @@ pub mod ffi { pub type ExplicitBitVect = crate::fingerprint_ffi::ExplicitBitVect; pub type SmilesParserParams; pub type Atom; - pub type HybridizationType; pub type MolSanitizeException; pub type MolSanitizeExceptionUniquePtr; // = UniquePtr; diff --git a/rdkit-sys/tests/test_descriptors.rs b/rdkit-sys/tests/test_descriptors.rs index 1106be8..2320bdb 100644 --- a/rdkit-sys/tests/test_descriptors.rs +++ b/rdkit-sys/tests/test_descriptors.rs @@ -109,5 +109,14 @@ fn test_descriptors() { ]; assert_eq!(names, expected_names); - assert_eq!(computed, expected_computed); + let mut corrected = expected_computed.clone(); + for (index, name) in names.iter().enumerate() { + if matches!(name.as_str(), "chi2n" | "chi2v") { + corrected[index] = 1.9451495490163708; + } + } + assert!( + computed == expected_computed || computed == corrected, + "{computed:?}" + ); } diff --git a/rdkit-sys/wrapper/include/bond.h b/rdkit-sys/wrapper/include/bond.h index 9b22aee..dfe2d2e 100644 --- a/rdkit-sys/wrapper/include/bond.h +++ b/rdkit-sys/wrapper/include/bond.h @@ -2,12 +2,14 @@ #include "rust/cxx.h" #include +#include namespace RDKit { -using BondType = Bond::BondType; -using BondStereo = Bond::BondStereo; -using BondDir = Bond::BondDir; +enum class BondType : std::int32_t; +enum class BondStereo : std::int32_t; +enum class BondDir : std::int32_t; +Bond::BondType native_bond_type(int value); unsigned int get_num_bonds(const ROMol &mol, bool only_heavy); const Bond &get_bond_with_idx(const ROMol &mol, unsigned int idx); diff --git a/rdkit-sys/wrapper/include/periodic_table.h b/rdkit-sys/wrapper/include/periodic_table.h index bd616e8..a6e3fda 100644 --- a/rdkit-sys/wrapper/include/periodic_table.h +++ b/rdkit-sys/wrapper/include/periodic_table.h @@ -4,9 +4,44 @@ #include namespace RDKit { -unsigned int periodic_table_max_atomic_number(const PeriodicTable &table); -unsigned int periodic_table_row(const PeriodicTable &table, unsigned int atomic_number); -std::unique_ptr get_periodic_table(); +class RustPeriodicTable { +public: + double getAtomicWeight(unsigned int atomic_number) const { + return PeriodicTable::getTable()->getAtomicWeight(atomic_number); + } + int getAtomicNumber(const std::string &atom) const { return PeriodicTable::getTable()->getAtomicNumber(atom); } + double getRvdw(unsigned int atomic_number) const { return PeriodicTable::getTable()->getRvdw(atomic_number); } + double getRcovalent(unsigned int atomic_number) const { + return PeriodicTable::getTable()->getRcovalent(atomic_number); + } + double getRb0(unsigned int atomic_number) const { return PeriodicTable::getTable()->getRb0(atomic_number); } + int getDefaultValence(unsigned int atomic_number) const { + return PeriodicTable::getTable()->getDefaultValence(atomic_number); + } + int getNouterElecs(unsigned int atomic_number) const { + return PeriodicTable::getTable()->getNouterElecs(atomic_number); + } + int getMostCommonIsotope(unsigned int atomic_number) const { + return PeriodicTable::getTable()->getMostCommonIsotope(atomic_number); + } + double getMostCommonIsotopeMass(const std::string &atom) const { + return PeriodicTable::getTable()->getMostCommonIsotopeMass(atom); + } + double getMassForIsotope(unsigned int atomic_number, unsigned int isotope) const { + return PeriodicTable::getTable()->getMassForIsotope(atomic_number, isotope); + } + double getAbundanceForIsotope(unsigned int atomic_number, unsigned int isotope) const { + return PeriodicTable::getTable()->getAbundanceForIsotope(atomic_number, isotope); + } + bool moreElectroNegative(unsigned int atomic_number1, unsigned int atomic_number2) const { + return PeriodicTable::getTable()->moreElectroNegative(atomic_number1, atomic_number2); + } +}; +unsigned int native_periodic_table_max_atomic_number(); + +unsigned int periodic_table_max_atomic_number(const RustPeriodicTable &table); +unsigned int periodic_table_row(const RustPeriodicTable &table, unsigned int atomic_number); +std::unique_ptr get_periodic_table(); rust::String getElementSymbol(unsigned int atomic_number); rust::String getElementName(unsigned int atomic_number); std::unique_ptr> getValenceList(unsigned int atomic_number); diff --git a/rdkit-sys/wrapper/include/ro_mol.h b/rdkit-sys/wrapper/include/ro_mol.h index d9b79c6..f98611b 100644 --- a/rdkit-sys/wrapper/include/ro_mol.h +++ b/rdkit-sys/wrapper/include/ro_mol.h @@ -8,6 +8,7 @@ #include #include #include +#include namespace RDKit { std::unique_ptr copy_mol(const ROMol &mol); @@ -38,7 +39,7 @@ void set_formal_charge(Atom &atom, int what); void set_num_explicit_hs(Atom &atom, int what); void atom_update_property_cache(Atom &atom, bool strict); -using HybridizationType = Atom::HybridizationType; +enum class HybridizationType : std::int32_t; void atom_set_hybridization(Atom &atom, int what); HybridizationType atom_get_hybridization(const Atom &atom); diff --git a/rdkit-sys/wrapper/src/bond.cc b/rdkit-sys/wrapper/src/bond.cc index e9c5cc7..9a37b38 100644 --- a/rdkit-sys/wrapper/src/bond.cc +++ b/rdkit-sys/wrapper/src/bond.cc @@ -1,11 +1,37 @@ -#include "rust/cxx.h" +#include "wrapper/include/bond.h" +#include "rdkit-sys/src/bridge/bond.rs.h" #include +#include namespace RDKit { -using BondType = Bond::BondType; -using BondStereo = Bond::BondStereo; -using BondDir = Bond::BondDir; +Bond::BondType native_bond_type(int value) { + switch (value) { + case static_cast(BondType::UNSPECIFIED): return Bond::UNSPECIFIED; + case static_cast(BondType::SINGLE): return Bond::SINGLE; + case static_cast(BondType::DOUBLE): return Bond::DOUBLE; + case static_cast(BondType::TRIPLE): return Bond::TRIPLE; + case static_cast(BondType::QUADRUPLE): return Bond::QUADRUPLE; + case static_cast(BondType::QUINTUPLE): return Bond::QUINTUPLE; + case static_cast(BondType::HEXTUPLE): return Bond::HEXTUPLE; + case static_cast(BondType::ONEANDAHALF): return Bond::ONEANDAHALF; + case static_cast(BondType::TWOANDAHALF): return Bond::TWOANDAHALF; + case static_cast(BondType::THREEANDAHALF): return Bond::THREEANDAHALF; + case static_cast(BondType::FOURANDAHALF): return Bond::FOURANDAHALF; + case static_cast(BondType::FIVEANDAHALF): return Bond::FIVEANDAHALF; + case static_cast(BondType::AROMATIC): return Bond::AROMATIC; + case static_cast(BondType::IONIC): return Bond::IONIC; + case static_cast(BondType::HYDROGEN): return Bond::HYDROGEN; + case static_cast(BondType::THREECENTER): return Bond::THREECENTER; + case static_cast(BondType::DATIVEONE): return Bond::DATIVEONE; + case static_cast(BondType::DATIVE): return Bond::DATIVE; + case static_cast(BondType::DATIVEL): return Bond::DATIVEL; + case static_cast(BondType::DATIVER): return Bond::DATIVER; + case static_cast(BondType::OTHER): return Bond::OTHER; + case static_cast(BondType::ZERO): return Bond::ZERO; + default: throw std::invalid_argument("invalid bond type"); + } +} unsigned int get_num_bonds(const ROMol &mol, bool only_heavy) { return mol.getNumBonds(only_heavy); } @@ -21,7 +47,33 @@ int get_bond_idx_between_atoms(const ROMol &mol, unsigned int begin_idx, unsigne return static_cast(bond->getIdx()); } -BondType bond_get_bond_type(const Bond &bond) { return bond.getBondType(); } +BondType bond_get_bond_type(const Bond &bond) { + switch (bond.getBondType()) { + case Bond::UNSPECIFIED: return BondType::UNSPECIFIED; + case Bond::SINGLE: return BondType::SINGLE; + case Bond::DOUBLE: return BondType::DOUBLE; + case Bond::TRIPLE: return BondType::TRIPLE; + case Bond::QUADRUPLE: return BondType::QUADRUPLE; + case Bond::QUINTUPLE: return BondType::QUINTUPLE; + case Bond::HEXTUPLE: return BondType::HEXTUPLE; + case Bond::ONEANDAHALF: return BondType::ONEANDAHALF; + case Bond::TWOANDAHALF: return BondType::TWOANDAHALF; + case Bond::THREEANDAHALF: return BondType::THREEANDAHALF; + case Bond::FOURANDAHALF: return BondType::FOURANDAHALF; + case Bond::FIVEANDAHALF: return BondType::FIVEANDAHALF; + case Bond::AROMATIC: return BondType::AROMATIC; + case Bond::IONIC: return BondType::IONIC; + case Bond::HYDROGEN: return BondType::HYDROGEN; + case Bond::THREECENTER: return BondType::THREECENTER; + case Bond::DATIVEONE: return BondType::DATIVEONE; + case Bond::DATIVE: return BondType::DATIVE; + case Bond::DATIVEL: return BondType::DATIVEL; + case Bond::DATIVER: return BondType::DATIVER; + case Bond::OTHER: return BondType::OTHER; + case Bond::ZERO: return BondType::ZERO; + default: throw std::invalid_argument("unsupported native bond enum"); + } +} double bond_get_bond_type_as_double(const Bond &bond) { return bond.getBondTypeAsDouble(); } @@ -35,9 +87,39 @@ bool bond_get_is_aromatic(const Bond &bond) { return bond.getIsAromatic(); } bool bond_get_is_conjugated(const Bond &bond) { return bond.getIsConjugated(); } -BondStereo bond_get_stereo(const Bond &bond) { return bond.getStereo(); } +template BondStereo native_bond_stereo(const NativeBond &bond) { + if constexpr (requires { + NativeBond::STEREOATROPCW; + NativeBond::STEREOATROPCCW; + }) { + if (bond.getStereo() == NativeBond::STEREOATROPCW) { return BondStereo::STEREOATROPCW; } + if (bond.getStereo() == NativeBond::STEREOATROPCCW) { return BondStereo::STEREOATROPCCW; } + } + switch (bond.getStereo()) { + case NativeBond::STEREONONE: return BondStereo::STEREONONE; + case NativeBond::STEREOANY: return BondStereo::STEREOANY; + case NativeBond::STEREOZ: return BondStereo::STEREOZ; + case NativeBond::STEREOE: return BondStereo::STEREOE; + case NativeBond::STEREOCIS: return BondStereo::STEREOCIS; + case NativeBond::STEREOTRANS: return BondStereo::STEREOTRANS; + default: throw std::invalid_argument("unsupported native bond stereo"); + } +} -BondDir bond_get_bond_dir(const Bond &bond) { return bond.getBondDir(); } +BondStereo bond_get_stereo(const Bond &bond) { return native_bond_stereo(bond); } + +BondDir bond_get_bond_dir(const Bond &bond) { + switch (bond.getBondDir()) { + case Bond::NONE: return BondDir::NONE; + case Bond::BEGINWEDGE: return BondDir::BEGINWEDGE; + case Bond::BEGINDASH: return BondDir::BEGINDASH; + case Bond::ENDDOWNRIGHT: return BondDir::ENDDOWNRIGHT; + case Bond::ENDUPRIGHT: return BondDir::ENDUPRIGHT; + case Bond::EITHERDOUBLE: return BondDir::EITHERDOUBLE; + case Bond::UNKNOWN: return BondDir::UNKNOWN; + default: throw std::invalid_argument("unsupported native bond enum"); + } +} unsigned int bond_get_idx(const Bond &bond) { return bond.getIdx(); } diff --git a/rdkit-sys/wrapper/src/periodic_table.cc b/rdkit-sys/wrapper/src/periodic_table.cc index d64660d..0bc0e52 100644 --- a/rdkit-sys/wrapper/src/periodic_table.cc +++ b/rdkit-sys/wrapper/src/periodic_table.cc @@ -1,4 +1,4 @@ -#include "rust/cxx.h" +#include "wrapper/include/periodic_table.h" #include #include #include @@ -23,17 +23,15 @@ template unsigned int table_row(const Table &table, unsigned int } } -unsigned int periodic_table_max_atomic_number(const PeriodicTable &table) { return table_max_atomic_number(table); } -unsigned int periodic_table_row(const PeriodicTable &table, unsigned int atomic_number) { - return table_row(table, atomic_number); +unsigned int native_periodic_table_max_atomic_number() { return table_max_atomic_number(*PeriodicTable::getTable()); } +unsigned int periodic_table_max_atomic_number(const RustPeriodicTable &) { + return native_periodic_table_max_atomic_number(); } - -std::unique_ptr get_periodic_table() { - // in rdkit we have the following: - // PeriodicTable::getTable() return : const PeriodicTable* - // so we need to take into account that it is a const pointer - return std::make_unique(*PeriodicTable::getTable()); +unsigned int periodic_table_row(const RustPeriodicTable &, unsigned int atomic_number) { + return table_row(*PeriodicTable::getTable(), atomic_number); } + +std::unique_ptr get_periodic_table() { return std::make_unique(); } rust::String getElementSymbol(unsigned int atomic_number) { PeriodicTable *pt = RDKit::PeriodicTable::getTable(); return pt->getElementSymbol(atomic_number); diff --git a/rdkit-sys/wrapper/src/ro_mol.cc b/rdkit-sys/wrapper/src/ro_mol.cc index 79a532e..f6db8ba 100644 --- a/rdkit-sys/wrapper/src/ro_mol.cc +++ b/rdkit-sys/wrapper/src/ro_mol.cc @@ -1,3 +1,4 @@ +#include "rdkit-sys/src/bridge/ro_mol.rs.h" #include "rust/cxx.h" #include "wrapper/include/owned.h" #include @@ -79,12 +80,34 @@ void set_num_explicit_hs(Atom &atom, int what) { } void atom_update_property_cache(Atom &atom, bool strict) { atom.updatePropertyCache(strict); } -using HybridizationType = Atom::HybridizationType; void atom_set_hybridization(Atom &atom, int what) { - if (what < Atom::UNSPECIFIED || what > Atom::OTHER) { throw std::invalid_argument("invalid hybridization"); } - atom.setHybridization(static_cast(what)); + switch (what) { + case static_cast(HybridizationType::UNSPECIFIED): atom.setHybridization(Atom::UNSPECIFIED); return; + case static_cast(HybridizationType::S): atom.setHybridization(Atom::S); return; + case static_cast(HybridizationType::SP): atom.setHybridization(Atom::SP); return; + case static_cast(HybridizationType::SP2): atom.setHybridization(Atom::SP2); return; + case static_cast(HybridizationType::SP3): atom.setHybridization(Atom::SP3); return; + case static_cast(HybridizationType::SP2D): atom.setHybridization(Atom::SP2D); return; + case static_cast(HybridizationType::SP3D): atom.setHybridization(Atom::SP3D); return; + case static_cast(HybridizationType::SP3D2): atom.setHybridization(Atom::SP3D2); return; + case static_cast(HybridizationType::OTHER): atom.setHybridization(Atom::OTHER); return; + default: throw std::invalid_argument("invalid hybridization"); + } +} +HybridizationType atom_get_hybridization(const Atom &atom) { + switch (atom.getHybridization()) { + case Atom::UNSPECIFIED: return HybridizationType::UNSPECIFIED; + case Atom::S: return HybridizationType::S; + case Atom::SP: return HybridizationType::SP; + case Atom::SP2: return HybridizationType::SP2; + case Atom::SP3: return HybridizationType::SP3; + case Atom::SP2D: return HybridizationType::SP2D; + case Atom::SP3D: return HybridizationType::SP3D; + case Atom::SP3D2: return HybridizationType::SP3D2; + case Atom::OTHER: return HybridizationType::OTHER; + default: throw std::invalid_argument("unsupported native hybridization"); + } } -HybridizationType atom_get_hybridization(const Atom &atom) { return atom.getHybridization(); } void ro_mol_update_property_cache(ROMol &mol, bool strict) { mol.updatePropertyCache(strict); } diff --git a/rdkit-sys/wrapper/src/rw_mol.cc b/rdkit-sys/wrapper/src/rw_mol.cc index 2d1abda..9f6c5f4 100644 --- a/rdkit-sys/wrapper/src/rw_mol.cc +++ b/rdkit-sys/wrapper/src/rw_mol.cc @@ -1,4 +1,5 @@ #include "rust/cxx.h" +#include "wrapper/include/bond.h" #include "wrapper/include/owned.h" #include "wrapper/include/periodic_table.h" #include @@ -38,7 +39,7 @@ std::unique_ptr smarts_to_mol(const std::string &smarts) { std::unique_ptr new_rw_mol() { return std::make_unique(); } ROMol &rw_mol_as_ro_mol_mut(RWMol &mol) { return mol; } unsigned int rw_mol_add_atom(RWMol &mol, unsigned int atomic_num) { - if (atomic_num > periodic_table_max_atomic_number(*PeriodicTable::getTable())) { + if (atomic_num > native_periodic_table_max_atomic_number()) { throw std::invalid_argument("atomic number out of range"); } Atom atom(atomic_num); @@ -48,8 +49,7 @@ unsigned int rw_mol_add_bond(RWMol &mol, unsigned int begin, unsigned int end, i if (begin >= mol.getNumAtoms() || end >= mol.getNumAtoms()) { throw std::out_of_range("bond atom index"); } if (begin == end) { throw std::invalid_argument("self bond"); } if (mol.getBondBetweenAtoms(begin, end)) { throw std::invalid_argument("bond already exists"); } - if (order < Bond::UNSPECIFIED || order > Bond::ZERO) { throw std::invalid_argument("invalid bond type"); } - mol.addBond(begin, end, static_cast(order)); + mol.addBond(begin, end, native_bond_type(order)); return mol.getNumBonds() - 1; } void rw_mol_remove_atom(RWMol &mol, unsigned int idx) { diff --git a/tests/test_descriptors.rs b/tests/test_descriptors.rs index e9aac07..f86068e 100644 --- a/tests/test_descriptors.rs +++ b/tests/test_descriptors.rs @@ -77,5 +77,16 @@ fn test_computing_properties() { expected.sort_by(|(k1, _), (k2, _)| k1.cmp(k2)); computed.sort_by(|(k1, _), (k2, _)| k1.cmp(k2)); - assert_eq!(expected, computed); + let mut corrected = expected.clone(); + for (name, value) in &mut corrected { + match name.as_str() { + "chi2n" => *value = "10.499".into(), + "chi2v" => *value = "10.936".into(), + _ => {} + } + } + assert!( + computed == expected || computed == corrected, + "{computed:?}" + ); } diff --git a/tests/test_safety.rs b/tests/test_safety.rs index 7e2c0bf..7addae0 100644 --- a/tests/test_safety.rs +++ b/tests/test_safety.rs @@ -306,13 +306,97 @@ fn low_level_smiles_null_remains_explicitly_checkable() { #[test] fn periodic_valence_lists_own_their_storage() { use rdkit_sys::PeriodicTableOps; + let surviving_table = rdkit_sys::periodic_table_ffi::get_periodic_table().unwrap(); let list = { let table = rdkit_sys::periodic_table_ffi::get_periodic_table().unwrap(); + assert_eq!(table.getDefaultValence(6).unwrap(), 4); table.getValenceList(6).unwrap() }; assert_eq!(list.as_slice(), &[4]); + assert_eq!(surviving_table.getDefaultValence(6).unwrap(), 4); + drop(surviving_table); + assert_eq!(PeriodicTable::get_default_valence(6), 4); let mut first = PeriodicTable::get_valence_list(6); let second = PeriodicTable::get_valence_list(6); first.push(99); assert_eq!(second, vec![4]); } + +#[test] +fn bond_types_round_trip_through_native_graph_edits() { + for kind in [ + BondType::UNSPECIFIED, + BondType::SINGLE, + BondType::DOUBLE, + BondType::TRIPLE, + BondType::QUADRUPLE, + BondType::QUINTUPLE, + BondType::HEXTUPLE, + BondType::ONEANDAHALF, + BondType::TWOANDAHALF, + BondType::THREEANDAHALF, + BondType::FOURANDAHALF, + BondType::FIVEANDAHALF, + BondType::AROMATIC, + BondType::IONIC, + BondType::HYDROGEN, + BondType::THREECENTER, + BondType::DATIVEONE, + BondType::DATIVE, + BondType::DATIVEL, + BondType::DATIVER, + BondType::OTHER, + BondType::ZERO, + ] { + let mut mol = RWMol::new(); + mol.add_atom(6).unwrap(); + mol.add_atom(6).unwrap(); + let idx = mol.add_bond(0, 1, kind).unwrap(); + assert_eq!(mol.bond(idx).unwrap().bond_type(), kind); + } + for invalid in [-1, 22, 256, i32::MAX] { + let mut mol = RWMol::new(); + mol.add_atom(6).unwrap(); + mol.add_atom(6).unwrap(); + assert!(mol.add_bond(0, 1, BondType { repr: invalid }).is_err()); + assert_eq!(mol.num_bonds(), 0); + } +} + +#[test] +fn hybridization_round_trips_without_native_enum_layout_assumptions() { + let mut mol = ROMol::from_smiles("C").unwrap(); + let mut atom = mol.atom_with_idx(0); + for hybridization in [ + HybridizationType::UNSPECIFIED, + HybridizationType::S, + HybridizationType::SP, + HybridizationType::SP2, + HybridizationType::SP3, + HybridizationType::SP2D, + HybridizationType::SP3D, + HybridizationType::SP3D2, + HybridizationType::OTHER, + ] { + atom.try_set_hybridization_type(hybridization).unwrap(); + assert_eq!(atom.try_get_hybridization_type().unwrap(), hybridization); + } + for invalid in [-1, 9, 256, i32::MAX] { + assert!(atom + .try_set_hybridization_type(HybridizationType { repr: invalid }) + .is_err()); + assert_eq!(atom.get_hybridization_type(), HybridizationType::OTHER); + } +} + +#[test] +fn parsed_bond_stereo_and_directions_cross_native_enum_layouts() { + let trans = ROMol::from_smiles("F/C=C/F").unwrap(); + let cis = ROMol::from_smiles("F/C=C\\F").unwrap(); + assert_eq!(trans.bond(1).unwrap().stereo(), BondStereo::STEREOE); + assert_eq!(cis.bond(1).unwrap().stereo(), BondStereo::STEREOZ); + assert_eq!(trans.bond(0).unwrap().bond_dir(), BondDir::ENDUPRIGHT); + assert_eq!(cis.bond(2).unwrap().bond_dir(), BondDir::ENDDOWNRIGHT); + assert_eq!(trans.bond(0).unwrap().stereo(), BondStereo::STEREONONE); + assert_eq!(trans.bond(1).unwrap().bond_dir(), BondDir::NONE); +} From 3435d3d1c92d68cd88cd909d919576e4613ff11d Mon Sep 17 00:00:00 2001 From: Xavier Lange Date: Fri, 9 Oct 2026 21:31:25 +0000 Subject: [PATCH 7/8] Validate pinned RDKit 2026 reference packages on native Ubuntu runners --- .github/workflows/test_suite.yml | 36 +++++++++++++++++++++++++++----- README.md | 2 ++ ci/install-reference-deps.sh | 33 +++++++++++++++++++++++++++++ docs/building.md | 31 ++++++++++++++++++++++++--- docs/validation.md | 35 ++++++++++++++++++++++--------- 5 files changed, 119 insertions(+), 18 deletions(-) create mode 100644 ci/install-reference-deps.sh diff --git a/.github/workflows/test_suite.yml b/.github/workflows/test_suite.yml index 31ed285..15a7332 100644 --- a/.github/workflows/test_suite.yml +++ b/.github/workflows/test_suite.yml @@ -9,18 +9,36 @@ permissions: jobs: test: - name: Ubuntu ${{ matrix.ubuntu }} / RDKit ${{ matrix.rdkit }} - runs-on: ubuntu-24.04 + name: Ubuntu ${{ matrix.ubuntu }} / RDKit ${{ matrix.rdkit }} / ${{ matrix.arch }} + runs-on: ${{ matrix.runner }} strategy: fail-fast: false matrix: include: - ubuntu: '26.04' rdkit: '2025.03.6' + arch: amd64 + runner: ubuntu-24.04 + install: install-deps.sh image: ubuntu:26.04@sha256:f144425ff09be612d6d9ad965196e9cdc23dae1f42110a8a11a3e9a8198759f7 - ubuntu: '24.04' rdkit: '2023.09.3' + arch: amd64 + runner: ubuntu-24.04 + install: install-deps.sh image: ubuntu:24.04@sha256:534baea6a22c03a63003dbc8dbe78fe34bc0d7e595d9a9dc9834884ff530eb55 + - ubuntu: '26.04' + rdkit: '2026.09.1 reference' + arch: amd64 + runner: ubuntu-24.04 + install: install-reference-deps.sh + image: ubuntu:26.04@sha256:f144425ff09be612d6d9ad965196e9cdc23dae1f42110a8a11a3e9a8198759f7 + - ubuntu: '26.04' + rdkit: '2026.09.1 reference' + arch: arm64 + runner: ubuntu-24.04-arm + install: install-reference-deps.sh + image: ubuntu:26.04@sha256:f144425ff09be612d6d9ad965196e9cdc23dae1f42110a8a11a3e9a8198759f7 container: image: ${{ matrix.image }} defaults: @@ -28,7 +46,7 @@ jobs: shell: bash steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - - run: bash ci/install-deps.sh + - run: bash ci/${{ matrix.install }} - uses: dtolnay/rust-toolchain@e2a55d2ffb04f378e9626c28d38b36d230d1e12f with: toolchain: '1.99.0' @@ -44,8 +62,16 @@ jobs: CONDA_PREFIX: /usr sanitizers: - name: C++ ASan and UBSan / Ubuntu 26.04 + name: C++ ASan and UBSan / Ubuntu 26.04 / ${{ matrix.rdkit }} runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + include: + - rdkit: '2025.03.6' + install: install-deps.sh + - rdkit: '2026.09.1 reference' + install: install-reference-deps.sh container: image: ubuntu:26.04@sha256:f144425ff09be612d6d9ad965196e9cdc23dae1f42110a8a11a3e9a8198759f7 defaults: @@ -53,7 +79,7 @@ jobs: shell: bash steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - - run: bash ci/install-deps.sh + - run: bash ci/${{ matrix.install }} - uses: dtolnay/rust-toolchain@e2a55d2ffb04f378e9626c28d38b36d230d1e12f with: toolchain: '1.99.0' diff --git a/README.md b/README.md index b72804a..779d8e4 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,8 @@ cargo test --workspace --locked The checkout pins Rust 1.99.0 and commits `Cargo.lock` for repeatable validation. See [building](docs/building.md) for exact package versions, containers, custom installations, Conda, and the target matrix. +Current-upstream RDKit 2026.09.1 also has a separate Ubuntu 26.04 reference-package lane on amd64 and arm64. Its [installer](ci/install-reference-deps.sh) verifies the GitHub release bundle before installing it; this does not require the project's APT repository. Use a fresh environment because its development headers conflict with Ubuntu's RDKit development package. + Use the crate named `rdkit`, with `use rdkit::ROMol`. The unrelated `rdkit-rs` crate is not this workspace. ```rust diff --git a/ci/install-reference-deps.sh b/ci/install-reference-deps.sh new file mode 100644 index 0000000..0c34180 --- /dev/null +++ b/ci/install-reference-deps.sh @@ -0,0 +1,33 @@ +set -euo pipefail +. /etc/os-release +if [ "$ID:$VERSION_ID" != ubuntu:26.04 ]; then + printf 'The reference package requires Ubuntu 26.04.\n' >&2 + exit 1 +fi +rdkit_arch=$(dpkg --print-architecture) +case "$rdkit_arch" in + amd64) rdkit_bundle_sha256=70899595de95f2e094c4398fe0e7ff41980d6d8fb3ede9936b643fadb3235783 ;; + arm64) rdkit_bundle_sha256=3e4c8a47f3fd73ffc24ec380d24d8ccdc60081fb0bcbd8be1259de4c4eebd740 ;; + *) printf 'Unsupported reference architecture: %s\n' "$rdkit_arch" >&2; exit 1 ;; +esac +rdkit_release_url=https://github.com/rdkit-rs/rdkit-debian/releases/download/ubuntu-26.04-rdkit-2026.09.1-1 +rdkit_bundle="rdkit-2026.09.1-ubuntu26.04-$rdkit_arch.tar.xz" +rdkit_download_dir=$(mktemp -d) +trap 'rm -rf "$rdkit_download_dir"' EXIT +apt-get update +DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ + build-essential ca-certificates curl git pkg-config xz-utils +curl --fail --silent --show-error --location --retry 3 "$rdkit_release_url/SHA256SUMS" --output "$rdkit_download_dir/SHA256SUMS" +curl --fail --silent --show-error --location --retry 3 "$rdkit_release_url/$rdkit_bundle" --output "$rdkit_download_dir/$rdkit_bundle" +( + cd "$rdkit_download_dir" + printf '%s %s\n' 1f3e0c00d63638a829a54e17dbb5561fb4cbc3381f2193098260692c241b9f57 SHA256SUMS "$rdkit_bundle_sha256" "$rdkit_bundle" | sha256sum --check + sha256sum --check --ignore-missing SHA256SUMS + mkdir bundle + tar -xJf "$rdkit_bundle" -C bundle + cd bundle + sha256sum --check SHA256SUMS +) +DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "$rdkit_download_dir"/bundle/*.deb +dpkg-query -W librdkit-rs-dev librdkit-rs202609 rdkit-rs-data libboost-dev libeigen3-dev +test "$(pkg-config --modversion rdkit)" = 2026.09.1 diff --git a/docs/building.md b/docs/building.md index 34c6424..f74de05 100644 --- a/docs/building.md +++ b/docs/building.md @@ -14,14 +14,14 @@ | Ubuntu 22.04 LTS | 2021.09.2 / `202109.2-1build1` | Too old for this binding surface | | Ubuntu 25.10 | 2025.03.1 / `202503.1-4` | Interim release; not a CI target | | Ubuntu 26.10 prerelease | 2025.03.6 / `202503.6-4` | No advantage over released 26.04 for this work | -| Upstream 2026.09.1 | Separate Ubuntu 26.04 reference package | Additional compatibility lane pending the package artifact | -| macOS, Windows, Linux arm64 | Varies | Not validated by this PR | +| Ubuntu 26.04 LTS amd64 and arm64 | Upstream 2026.09.1 / `2026.09.1+ds1-1~ubuntu26.04` | Additional reference-package CI targets | +| macOS, Windows | Varies | Not validated by this PR | Sources: [Ubuntu package versions](https://packages.ubuntu.com/librdkit-dev), [26.04 package](https://packages.ubuntu.com/resolute/librdkit-dev), [Debian 13 package](https://packages.debian.org/trixie/librdkit-dev). Both Ubuntu package pins were also checked against their actual apt repositories in clean containers. The LTS package supplies a matched native RDKit, Boost dependency set, and development headers through ordinary package management. The baseline can be installed without a custom binary distribution. Selecting it does not imply that it contains every fix or feature from newer upstream releases, or that Ubuntu Universe has the same support guarantees as Ubuntu Main. -The project's [Debian packaging tutorial](https://github.com/rdkit-rs/rdkit-rs.github.io/blob/1d3778e/content/tutorials/forking-a-debian-package.md) explains the earlier need for newer upstream packages, isolated native builds and CI-produced artifacts. A separate reference-package effort carries that goal forward for current upstream on Ubuntu 26.04. Its artifact should be tested as an additional lane with an exact version and checksum, while keeping the distro installation path working. +The project's [Debian packaging tutorial](https://github.com/rdkit-rs/rdkit-rs.github.io/blob/1d3778e/content/tutorials/forking-a-debian-package.md) explains the earlier need for newer upstream packages, isolated native builds and CI-produced artifacts. The separate reference package below carries that goal forward for current upstream on Ubuntu 26.04. The distro installation path remains the default. ## Native installation @@ -38,6 +38,31 @@ The Ubuntu CI jobs run on a Linux x86_64 host inside digest-pinned Ubuntu contai Install `clang-format-18` for C++ formatting. Standard Rust formatting works without nightly. +## Current-upstream reference package + +The [Ubuntu 26.04 reference release](https://github.com/rdkit-rs/rdkit-debian/releases/tag/ubuntu-26.04-rdkit-2026.09.1-1) contains runtime, development and data packages at `2026.09.1+ds1-1~ubuntu26.04`. It was built from packaging commit `0656aade78d3709900552193cee0506c19f96223` and upstream commit `fece8caa860bdf6c9c82bdb9253f22a0cf87150c` (`Release_2026_09_1`). The `+ds1` source repack excludes the optional Amadeus font; the bundle includes source, packaging patches, provenance and license notices. + +On a fresh Ubuntu 26.04 amd64 or arm64 environment: + +```sh +sudo bash ci/install-reference-deps.sh +cargo test --workspace --locked +``` + +The installer downloads the architecture's complete release bundle, verifies the pinned hash, the published `SHA256SUMS`, and all internal checksums, then installs the local `.deb` files using `apt-get install`. This resolves their Ubuntu dependencies. It tests installation from GitHub release artifacts; it does not add or validate the project's S3 APT repository. The development package conflicts with Ubuntu's `librdkit-dev`, so use a separate environment when retaining the distro baseline. + +| Artifact | SHA-256 | +| --- | --- | +| Published `SHA256SUMS` | `1f3e0c00d63638a829a54e17dbb5561fb4cbc3381f2193098260692c241b9f57` | +| `rdkit-2026.09.1-ubuntu26.04-amd64.tar.xz` | `70899595de95f2e094c4398fe0e7ff41980d6d8fb3ede9936b643fadb3235783` | +| `rdkit-2026.09.1-ubuntu26.04-arm64.tar.xz` | `3e4c8a47f3fd73ffc24ec380d24d8ccdc60081fb0bcbd8be1259de4c4eebd740` | + +The bundles preserve the original Debian filenames containing `~`; GitHub's individual `.deb` asset names use `.` in its place. CI uses the bundles directly. Headers and linker symlinks install under `/usr`; the runtime SONAME is `.so.2026.09`. `pkg-config --modversion rdkit` reports `2026.09.1`. No prefix or loader override is needed. This project's tests use built-in chemistry defaults and repository fixtures; consumers needing the packaged data can set `RDBASE` using `pkg-config --variable=rdbase rdkit`. + +Reference-package jobs use native amd64 and arm64 runners, with the same pinned Ubuntu 26.04 container as the distro job. C++ ASan/UBSan jobs cover both the distro and reference packages on amd64. The reference packages' own [native build/install checks](https://github.com/rdkit-rs/rdkit-debian/actions/runs/37990535727) are separate from this workspace's binding tests. Neither project claims byte-for-byte package reproducibility; Ubuntu dependency versions are not snapshot-pinned. + +The packaging project's later [APT publication verification](https://github.com/rdkit-rs/rdkit-debian/actions/runs/37992678461) passed clean installs and native smoke tests on both architectures. That is separate evidence for its APT repository, not the installation method used by this workspace's release-artifact CI. + ## Prefixes and runtime linking By default, Linux uses `/usr`, Apple Silicon macOS uses `/opt/homebrew`, and Intel macOS uses `/usr/local`. These macOS paths are supported discovery conventions, not macOS validation evidence. Override them explicitly: diff --git a/docs/validation.md b/docs/validation.md index ca5a853..6d6314c 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -4,26 +4,31 @@ Recorded 2026-10-09 for this modernization. The PR's GitHub checks identify the ## Executed local checks +The original package matrix passed at `18ed53359fbbd21df813b23868d9f5a02261cc4c`. The current-upstream follow-up adds three regression tests; the rows below distinguish the original full runs from the later compatibility checks. The PR's final-head CI runs the complete suite on every configured platform. + | Environment / check | Result | | --- | --- | -| Ubuntu 26.04 amd64, RDKit `202503.6-4`, GCC 15 | 107 workspace tests passed, including the compile-fail harness | -| Ubuntu 24.04 amd64, RDKit `202309.3-3build2`, GCC 13 | 107 workspace tests passed, including the compile-fail harness | +| Ubuntu 26.04 amd64, RDKit `202503.6-4`, GCC 15 | Original 107 workspace tests passed; later 20 safety and three descriptor tests passed with the 2026 compatibility changes | +| Ubuntu 24.04 amd64, RDKit `202309.3-3build2`, GCC 13 | Original 107 workspace tests passed; later 20 safety and three descriptor tests passed with the 2026 compatibility changes | | Saved Debian 13 amd64, RDKit `202503.1-4`, GCC 14 | 107 tests passed with `--workspace --all-targets`; examples compiled and stable benchmark smoke ran | +| Ubuntu 26.04 amd64, reference RDKit `2026.09.1+ds1-1~ubuntu26.04`, GCC 15 | 110 tests passed with `--workspace --all-targets`; examples and benchmark targets also passed | | Borrow checking | All six expected compile failures matched their checked-in diagnostics | -| Focused regressions | 17 safety/correctness tests passed on both Ubuntu versions and the saved environment | -| Ubuntu 26.04 C++ ASan + UBSan | 78 targeted high-level and sys tests passed; leak detection enabled; no reported findings | -| Actual downstream application in an isolated checkout | All 50 existing tests passed with both crates patched to this branch | +| Focused regressions | 20 safety/correctness tests passed on RDKit 2023.09, 2025.03 and 2026.09; the original 17 also passed in the saved environment | +| Ubuntu 26.04 C++ ASan + UBSan | Original 78 tests passed with distro RDKit; 81 passed with reference RDKit 2026.09.1; leak detection enabled and no reported findings | +| Actual downstream application in isolated checkouts | All 50 existing tests passed in the saved environment and again with reference RDKit 2026.09.1 on Ubuntu 26.04 | | Rust formatting | `cargo fmt --all --check` passed on pinned Rust 1.99.0 | | C++ formatting | clang-format 18 dry run with warnings as errors passed | -| Clippy | All-targets workspace checking with warnings denied passed in the saved environment and both Ubuntu versions | -| Rustdoc | Workspace documentation with warnings denied passed on both Ubuntu versions | -| Conda feature forwarding | All-features workspace check passed with the distro prefix on Ubuntu 26.04; this is not a Conda package solve | +| Clippy | All-targets workspace checking with warnings denied passed in the saved environment, both Ubuntu distro packages, and reference RDKit 2026.09.1 | +| Rustdoc | Workspace documentation with warnings denied passed on both Ubuntu versions and reference RDKit 2026.09.1 | +| Conda feature forwarding | All-features workspace check passed with distro and reference prefixes on Ubuntu 26.04; this is not a Conda package solve | | Whitespace | `git diff --check` passed | -The 107 count includes one Rust harness test that runs six compile-fail fixtures; it does not count those fixtures as six additional runtime tests. Tests are behavioral samples, not exhaustive input or instruction coverage. Empty test/example/doc-test harnesses are not added to the count. The native declaration inventory is separate from the test count. +The 107 and 110 counts each include one Rust harness test that runs six compile-fail fixtures; they do not count those fixtures as six additional runtime tests. Tests are behavioral samples, not exhaustive input or instruction coverage. Empty test/example/doc-test harnesses are not added to the count. The native declaration inventory is separate from the test count. The isolated downstream validation exercised existing parsing, processing, descriptor/fingerprint, indexing/search and API workflows. Only dependency path overrides, necessary lockfile resolution and local build-output discovery were changed in the isolated checkout. No downstream application source or tests were changed or pushed. A public error-display regression found by that suite was fixed in the bindings while preserving native detail in the error payload. Private downstream implementation/data are intentionally not reproduced here. +The Ubuntu 26.04 downstream run reused a separately installed native dependency from the saved environment after that dependency's fresh binary download was blocked by the executor. It was isolated from the RDKit library path. All chemistry libraries came from the verified 2026.09.1 reference packages; no downstream tests were changed or skipped. + ## Reproduce Install the pinned native package as described in [building](building.md), then run: @@ -41,14 +46,24 @@ The last command is the Linux x86_64 GCC sanitizer lane. It instruments the C++ The all-features command checks feature forwarding/prefix discovery against the installed distro package. It does not validate a real Conda solve. Use a separate target directory for sanitizer builds when overriding `CARGO_TARGET_DIR`. +## Reference-package provenance + +The amd64 release bundle, published checksum file and every internal file matched their SHA-256 values. [Building](building.md#current-upstream-reference-package) records the release, source commits, package version and pinned amd64/arm64 bundle hashes. The runtime, development and data packages were installed together in a fresh Ubuntu 26.04 container; `pkg-config` reported `2026.09.1`, and runtime inspection confirmed the test executable loaded `.so.2026.09` libraries. + +This is GitHub release-artifact installation using `apt-get install ./package.deb` for dependency resolution. The packaging project's [separate APT verification run](https://github.com/rdkit-rs/rdkit-debian/actions/runs/37992678461) passed clean repository installs and native smoke tests on both architectures. Its results do not substitute for the full binding suite. This workspace's reference CI repeats the verified bundle installation on native amd64 and arm64, alongside the two distro-package jobs. + ## Failures investigated and corrected The first Ubuntu 24.04 build exposed header organization and periodic-table methods that differ in RDKit 2023.09. The bridge now includes the common parser header and uses small checked compatibility shims for row/max-atomic-number lookup. Every atomic number from 0 through 118 is tested for row lookup. Two existing tests assumed newer native chemistry data or behavior: a tautomer canonicalization case and carbon's covalent radius. The tests now assert the specific observed results of the supported native versions. The canonicalization success case also requires no chemistry problems and a successful sanitized reparse; failures must match the expected native exception. The binding does not substitute one release's chemistry behavior for another's. +The initial build of `18ed533` against RDKit 2026.09.1 failed CXX size assertions: native bond and atom hybridization enums changed from wider storage to one byte. The bridge now maps named native enumerators to stable bridge-owned values, with errors for unsupported values. RDKit 2026 also deletes the periodic-table copy constructor; owned stateless handles now query the singleton per call and never retain or destroy it. Regressions cover all 22 exposed bond types, all nine hybridizations, invalid enum inputs, parsed E/Z and directional bonds, and independent table-handle destruction. + +RDKit 2026 corrects the registered `chi2n`/`chi2v` descriptors, which returned third-order values for both fixtures in the older tested releases. Native probes compared the registry with direct second- and third-order calls. Both descriptor fixtures now assert the complete output against the specific old or corrected expected vector; no descriptor fields are skipped. The wrappers preserve the native values. + Initial development runs also exposed the old nightly-only benchmark, missing compile-fail snapshots, and Clippy failures. The benchmark now uses stable timing/black-box operations, the six diagnostics are checked in, and the lint failures were corrected. Final results above supersede those development failures. ## Not run or not established -Current-upstream RDKit 2026.09.1 validation awaits the separate Ubuntu 26.04 reference-package artifact and its checksum/install contract. It must be added as its own compatibility lane without removing the distro matrix. macOS, Windows, Linux arm64, a real Conda environment, Miri, and sanitizer-instrumented RDKit/Rust builds were not run. Miri alone cannot validate these native C++ algorithms. No fuzzing campaign, whole-upstream API coverage or general memory-safety proof is claimed. +macOS, Windows, a real Conda environment, Miri, and sanitizer-instrumented RDKit/Rust builds were not run. Arm64 coverage is limited to the reference-package CI job; local checks and sanitizer jobs run on amd64. Miri alone cannot validate these native C++ algorithms. No fuzzing campaign, whole-upstream API coverage or general memory-safety proof is claimed. From 0ae060c9cfc14626172070989fee890b16454373 Mon Sep 17 00:00:00 2001 From: Xavier Lange Date: Fri, 9 Oct 2026 21:34:10 +0000 Subject: [PATCH 8/8] Use the pinned Ubuntu public mirror for CI image pulls --- .github/workflows/test_suite.yml | 10 +++++----- docs/building.md | 2 +- docs/validation.md | 2 ++ 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/.github/workflows/test_suite.yml b/.github/workflows/test_suite.yml index 15a7332..f35ea2b 100644 --- a/.github/workflows/test_suite.yml +++ b/.github/workflows/test_suite.yml @@ -20,25 +20,25 @@ jobs: arch: amd64 runner: ubuntu-24.04 install: install-deps.sh - image: ubuntu:26.04@sha256:f144425ff09be612d6d9ad965196e9cdc23dae1f42110a8a11a3e9a8198759f7 + image: public.ecr.aws/docker/library/ubuntu@sha256:f144425ff09be612d6d9ad965196e9cdc23dae1f42110a8a11a3e9a8198759f7 - ubuntu: '24.04' rdkit: '2023.09.3' arch: amd64 runner: ubuntu-24.04 install: install-deps.sh - image: ubuntu:24.04@sha256:534baea6a22c03a63003dbc8dbe78fe34bc0d7e595d9a9dc9834884ff530eb55 + image: public.ecr.aws/docker/library/ubuntu@sha256:534baea6a22c03a63003dbc8dbe78fe34bc0d7e595d9a9dc9834884ff530eb55 - ubuntu: '26.04' rdkit: '2026.09.1 reference' arch: amd64 runner: ubuntu-24.04 install: install-reference-deps.sh - image: ubuntu:26.04@sha256:f144425ff09be612d6d9ad965196e9cdc23dae1f42110a8a11a3e9a8198759f7 + image: public.ecr.aws/docker/library/ubuntu@sha256:f144425ff09be612d6d9ad965196e9cdc23dae1f42110a8a11a3e9a8198759f7 - ubuntu: '26.04' rdkit: '2026.09.1 reference' arch: arm64 runner: ubuntu-24.04-arm install: install-reference-deps.sh - image: ubuntu:26.04@sha256:f144425ff09be612d6d9ad965196e9cdc23dae1f42110a8a11a3e9a8198759f7 + image: public.ecr.aws/docker/library/ubuntu@sha256:f144425ff09be612d6d9ad965196e9cdc23dae1f42110a8a11a3e9a8198759f7 container: image: ${{ matrix.image }} defaults: @@ -73,7 +73,7 @@ jobs: - rdkit: '2026.09.1 reference' install: install-reference-deps.sh container: - image: ubuntu:26.04@sha256:f144425ff09be612d6d9ad965196e9cdc23dae1f42110a8a11a3e9a8198759f7 + image: public.ecr.aws/docker/library/ubuntu@sha256:f144425ff09be612d6d9ad965196e9cdc23dae1f42110a8a11a3e9a8198759f7 defaults: run: shell: bash diff --git a/docs/building.md b/docs/building.md index f74de05..cb5b43c 100644 --- a/docs/building.md +++ b/docs/building.md @@ -34,7 +34,7 @@ cargo test --workspace --locked The script installs the exact RDKit package above plus a C++ compiler, Boost development headers and serialization library, and Eigen headers. Rustup honors the pinned Rust 1.99.0 toolchain in `rust-toolchain.toml`. CI uses the committed Cargo lockfile. These are tested toolchain versions, not a claim that all older Rust compilers fail. -The Ubuntu CI jobs run on a Linux x86_64 host inside digest-pinned Ubuntu containers. Package versions are explicit; other apt dependencies receive the distribution's current updates. This reproduces the RDKit/API baseline, not a bit-for-bit frozen operating system. If a pinned package leaves the active archive, use the corresponding Ubuntu snapshot and record that change rather than silently taking a different RDKit release. +The Ubuntu distro CI jobs run on a Linux x86_64 host inside digest-pinned Ubuntu containers. CI pulls Docker's official Ubuntu images through its public ECR mirror using the same image digests, avoiding Docker Hub's unauthenticated pull limits. Package versions are explicit; other apt dependencies receive the distribution's current updates. This reproduces the RDKit/API baseline, not a bit-for-bit frozen operating system. If a pinned package leaves the active archive, use the corresponding Ubuntu snapshot and record that change rather than silently taking a different RDKit release. Install `clang-format-18` for C++ formatting. Standard Rust formatting works without nightly. diff --git a/docs/validation.md b/docs/validation.md index 6d6314c..7b7189e 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -64,6 +64,8 @@ RDKit 2026 corrects the registered `chi2n`/`chi2v` descriptors, which returned t Initial development runs also exposed the old nightly-only benchmark, missing compile-fail snapshots, and Clippy failures. The benchmark now uses stable timing/black-box operations, the six diagnostics are checked in, and the lint failures were corrected. Final results above supersede those development failures. +The first expanded CI run failed before compilation because Docker Hub returned rate-limit errors and authentication timeouts. CI now pulls the identical pinned Ubuntu images through Docker's public ECR mirror. + ## Not run or not established macOS, Windows, a real Conda environment, Miri, and sanitizer-instrumented RDKit/Rust builds were not run. Arm64 coverage is limited to the reference-package CI job; local checks and sanitizer jobs run on amd64. Miri alone cannot validate these native C++ algorithms. No fuzzing campaign, whole-upstream API coverage or general memory-safety proof is claimed.