diff --git a/.cargo/audit.toml b/.cargo/audit.toml index 32fc0923..7dc4bbc2 100644 --- a/.cargo/audit.toml +++ b/.cargo/audit.toml @@ -2,8 +2,4 @@ # https://github.com/rustsec/rustsec/tree/main/cargo-audit [advisories] -# custom_derive v0.1.7 — unmaintained crate pulled in transitively by -# rust-htslib v1.0.0. There is no newer rust-htslib release that drops it, -# and this is an "unmaintained" notice, not a vulnerability. -# Re-evaluate when rust-htslib releases a version without custom_derive. -ignore = ["RUSTSEC-2025-0058"] +ignore = [] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 270c738c..8451ff37 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,6 +10,7 @@ permissions: env: CARGO_TERM_COLOR: always + CXX: g++ jobs: test: @@ -40,12 +41,11 @@ jobs: if: runner.os == 'Linux' run: | sudo apt-get update - sudo apt-get install -y cmake zlib1g-dev libbz2-dev liblzma-dev \ - libcurl4-openssl-dev libssl-dev libfontconfig1-dev pkg-config clang + sudo apt-get install -y g++ libfontconfig1-dev pkg-config - name: Install macOS build deps if: runner.os == 'macOS' - run: brew install bzip2 xz + run: brew install fontconfig - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 @@ -97,8 +97,7 @@ jobs: - name: Install Linux build deps run: | sudo apt-get update - sudo apt-get install -y cmake zlib1g-dev libbz2-dev liblzma-dev \ - libcurl4-openssl-dev libssl-dev libfontconfig1-dev pkg-config clang + sudo apt-get install -y g++ libfontconfig1-dev pkg-config - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 @@ -115,13 +114,12 @@ jobs: - name: Install Rust MSRV toolchain uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # v1 with: - toolchain: "1.88" + toolchain: "1.89" - name: Install Linux build deps run: | sudo apt-get update - sudo apt-get install -y cmake zlib1g-dev libbz2-dev liblzma-dev \ - libcurl4-openssl-dev libssl-dev libfontconfig1-dev pkg-config clang + sudo apt-get install -y g++ libfontconfig1-dev pkg-config - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3313bffa..caf5fca2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,6 +12,7 @@ permissions: env: CARGO_TERM_COLOR: always + CXX: g++ IMAGE_NAME: ${{ github.repository }} jobs: @@ -134,13 +135,12 @@ jobs: if: runner.os == 'Linux' run: | sudo apt-get update - sudo apt-get install -y cmake zlib1g-dev libbz2-dev liblzma-dev \ - libcurl4-openssl-dev libssl-dev libfontconfig1-dev pkg-config clang + sudo apt-get install -y g++ libfontconfig1-dev pkg-config # macOS build dependencies - name: Install macOS build deps if: runner.os == 'macOS' - run: brew install bzip2 xz + run: brew install fontconfig - name: Build run: > diff --git a/AGENTS.md b/AGENTS.md index c9871c94..5ce17e3f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -245,7 +245,7 @@ To prepare a release: | Crate | Purpose | | ---------------------- | ------------------------------------- | | `clap` v4 | CLI argument parsing (derive) | -| `rust-htslib` | BAM file I/O (statically linked) | +| `noodles` | BAM/SAM/CRAM file I/O (pure Rust) | | `plotters` | Chart generation (PNG + SVG) | | `serde` | YAML config deserialization | | `anyhow` | Error handling | @@ -283,7 +283,7 @@ forwarded to `count_reads()` as the `skip_dup_check: bool` parameter). - Test data is generated by `tests/create_test_data.R` — do not modify `tests/expected/` by hand. - Float output formatting must match R's behavior (15 significant digits, "NA" for NaN, trailing-zero trimming). - The pipeline processes BAM files which can be very large — performance matters. -- System dependencies needed for building: cmake, zlib, bz2, lzma, curl, ssl, clang (for `rust-htslib`). +- System dependencies needed for building: a C++ compiler (for the preseq RNG FFI shim), libfontconfig (for plot rendering). noodles handles BAM/SAM/CRAM I/O in pure Rust with no htslib/cmake dependency. - Benchmark results are produced by the [RustQC-benchmarks](https://github.com/seqeralabs/RustQC-benchmarks) Nextflow pipeline. When benchmarks are re-run, verify that all results referenced in the docs and the top-level `README.md` are updated to reflect the new numbers. diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b67cce4..b2c35525 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # RustQC Changelog +## [Unreleased] + +### Other changes + +- Migrate BAM/SAM/CRAM I/O from rust-htslib to pure-Rust [noodles](https://crates.io/crates/noodles) (#113) +- Simplify build requirements: no cmake or htslib system libraries needed +- Bump MSRV to Rust 1.89 (required by noodles 0.111) + ## [Version 0.2.1](https://github.com/seqeralabs/RustQC/releases/tag/v0.2.1) - 2026-04-09 ### Bug fixes diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cedc565e..7e5cac7f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,24 +6,18 @@ Thanks for your interest in contributing to RustQC! This document covers how to ### Prerequisites -You need a working Rust toolchain (stable) and the following system libraries for building `rust-htslib`: - -- cmake, clang -- zlib, libbz2, liblzma -- libcurl, libssl -- libfontconfig (for plot rendering) +You need a working Rust toolchain (stable), a C++ compiler (for the preseq RNG FFI shim), and libfontconfig (for plot rendering). BAM/SAM/CRAM I/O is handled by the pure-Rust [noodles](https://crates.io/crates/noodles) crate — no htslib or cmake required. On Ubuntu/Debian: ```bash -sudo apt-get install cmake clang zlib1g-dev libbz2-dev liblzma-dev \ - libcurl4-openssl-dev libssl-dev libfontconfig1-dev +sudo apt-get install g++ libfontconfig1-dev ``` On macOS (with Homebrew): ```bash -brew install cmake xz +brew install fontconfig ``` ### Building diff --git a/Cargo.lock b/Cargo.lock index a99a2dd1..4f747306 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "aliasable" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "250f629c0161ad8107cf89319e990051fae62832fd343083bea452d93e2205fd" + [[package]] name = "android_system_properties" version = "0.1.6" @@ -89,34 +95,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] -name = "bindgen" -version = "0.72.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" -dependencies = [ - "bitflags 2.13.2", - "cexpr", - "clang-sys", - "itertools", - "proc-macro2", - "quote", - "regex", - "rustc-hash", - "shlex 1.3.0", - "syn 2.0.119", -] - -[[package]] -name = "bio-types" -version = "1.0.4" +name = "bit-vec" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4dcf54f8b7f51450207d54780bab09c05f30b8b0caa991545082842e466ad7e" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" dependencies = [ - "derive-new 0.6.0", - "lazy_static", - "regex", - "strum_macros", - "thiserror 1.0.69", + "serde", ] [[package]] @@ -131,6 +115,25 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bstr" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a680398c10c7bc0488067c4612226ea905a85f607134b69f3068d505d58c4214" +dependencies = [ + "memchr", + "serde_core", +] + [[package]] name = "bumpalo" version = "3.20.4" @@ -150,13 +153,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] -name = "bzip2-sys" -version = "0.1.13+1.0.8" +name = "bytes" +version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "bzip2" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c" dependencies = [ - "cc", - "pkg-config", + "libbz2-rs-sys", ] [[package]] @@ -166,18 +174,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" dependencies = [ "find-msvc-tools", - "jobserver", - "libc", - "shlex 2.0.1", -] - -[[package]] -name = "cexpr" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" -dependencies = [ - "nom", + "shlex", ] [[package]] @@ -210,17 +207,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "clang-sys" -version = "1.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" -dependencies = [ - "glob", - "libc", - "libloading", -] - [[package]] name = "clap" version = "4.6.10" @@ -249,7 +235,7 @@ version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" dependencies = [ - "heck", + "heck 0.5.0", "proc-macro2", "quote", "syn 3.0.10", @@ -261,15 +247,6 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" -[[package]] -name = "cmake" -version = "0.1.58" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" -dependencies = [ - "cc", -] - [[package]] name = "coitrees" version = "0.4.0" @@ -300,6 +277,12 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "core-foundation" version = "0.9.4" @@ -370,6 +353,15 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-deque" version = "0.8.8" @@ -396,46 +388,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" [[package]] -name = "curl-sys" -version = "0.4.91+curl-8.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd39579123e45bf762716bb893d43886ed1cabe6289455be29a4f1d4e37afb06" -dependencies = [ - "cc", - "libc", - "libz-sys", - "openssl-sys", - "pkg-config", - "vcpkg", - "windows-sys", -] - -[[package]] -name = "custom_derive" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef8ae57c4978a2acd8b869ce6b9ca1dfe817bff704c220209fdef2c0b75a01b9" - -[[package]] -name = "derive-new" -version = "0.6.0" +name = "crypto-common" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d150dea618e920167e5973d70ae6ece4385b7164e0d799fe7c122dd0a5d912ad" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", + "hybrid-array", ] [[package]] -name = "derive-new" -version = "0.7.0" +name = "digest" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cdc8d50f426189eef89dac62fabfa0abb27d5cc008f25bf4156a0203325becc" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", + "block-buffer", + "const-oid", + "crypto-common", ] [[package]] @@ -468,17 +437,6 @@ dependencies = [ "windows-sys", ] -[[package]] -name = "displaydoc" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - [[package]] name = "dlib" version = "0.5.3" @@ -625,15 +583,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" -[[package]] -name = "form_urlencoded" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" -dependencies = [ - "percent-encoding", -] - [[package]] name = "freetype-sys" version = "0.20.1" @@ -645,15 +594,6 @@ dependencies = [ "pkg-config", ] -[[package]] -name = "fs-utils" -version = "1.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fc7a9dc005c944c98a935e7fd626faf5bf7e5a609f94bc13e42fc4a02e52593" -dependencies = [ - "quick-error", -] - [[package]] name = "futures-core" version = "0.3.34" @@ -700,18 +640,18 @@ dependencies = [ "weezl", ] -[[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.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + [[package]] name = "heck" version = "0.5.0" @@ -719,20 +659,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] -name = "hts-sys" -version = "2.2.1" +name = "hybrid-array" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc7e68eb880b02c80cfb41e8dc7904062a3ea7e27b7c4556e88d648dd2f038da" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" dependencies = [ - "bindgen", - "bzip2-sys", - "cc", - "curl-sys", - "fs-utils", - "glob", - "libz-sys", - "lzma-sys", - "openssl-sys", + "typenum", ] [[package]] @@ -759,116 +691,6 @@ dependencies = [ "cc", ] -[[package]] -name = "icu_collections" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" -dependencies = [ - "displaydoc", - "potential_utf", - "utf8_iter", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locale_core" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" -dependencies = [ - "displaydoc", - "litemap", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_normalizer" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" -dependencies = [ - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" - -[[package]] -name = "icu_properties" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" -dependencies = [ - "displaydoc", - "icu_collections", - "icu_locale_core", - "icu_properties_data", - "icu_provider", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" - -[[package]] -name = "icu_provider" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" -dependencies = [ - "displaydoc", - "icu_locale_core", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", -] - -[[package]] -name = "idna" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" -dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", -] - -[[package]] -name = "idna_adapter" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" -dependencies = [ - "icu_normalizer", - "icu_properties", -] - -[[package]] -name = "ieee754" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9007da9cacbd3e6343da136e98b0d2df013f553d35bdec8b518f07bea768e19c" - [[package]] name = "image" version = "0.24.9" @@ -912,15 +734,6 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" -[[package]] -name = "itertools" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" -dependencies = [ - "either", -] - [[package]] name = "itoa" version = "1.0.19" @@ -962,16 +775,6 @@ dependencies = [ "syn 3.0.10", ] -[[package]] -name = "jobserver" -version = "0.1.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" -dependencies = [ - "getrandom", - "libc", -] - [[package]] name = "jpeg-decoder" version = "0.3.2" @@ -995,6 +798,69 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +[[package]] +name = "lexical-core" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d8d125a277f807e55a77304455eb7b1cb52f2b18c143b60e766c120bd64a594" +dependencies = [ + "lexical-parse-float", + "lexical-parse-integer", + "lexical-util", + "lexical-write-float", + "lexical-write-integer", +] + +[[package]] +name = "lexical-parse-float" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52a9f232fbd6f550bc0137dcb5f99ab674071ac2d690ac69704593cb4abbea56" +dependencies = [ + "lexical-parse-integer", + "lexical-util", +] + +[[package]] +name = "lexical-parse-integer" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a7a039f8fb9c19c996cd7b2fcce303c1b2874fe1aca544edc85c4a5f8489b34" +dependencies = [ + "lexical-util", +] + +[[package]] +name = "lexical-util" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2604dd126bb14f13fb5d1bd6a66155079cb9fa655b37f875b3a742c705dbed17" + +[[package]] +name = "lexical-write-float" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50c438c87c013188d415fbabbb1dceb44249ab81664efbd31b14ae55dabb6361" +dependencies = [ + "lexical-util", + "lexical-write-integer", +] + +[[package]] +name = "lexical-write-integer" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "409851a618475d2d5796377cad353802345cba92c867d9fbcde9cf4eac4e14df" +dependencies = [ + "lexical-util", +] + +[[package]] +name = "libbz2-rs-sys" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5314d1d545fce0307c770d791adf20d997e0b63b64e1ffeed8a920e290eabe4" + [[package]] name = "libc" version = "0.2.191" @@ -1020,31 +886,6 @@ dependencies = [ "libc", ] -[[package]] -name = "libz-sys" -version = "1.1.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fee3f59f4321dab0c78d828942e7aa09d0bd8ad6e78a501977e6bf3d02938045" -dependencies = [ - "cc", - "cmake", - "libc", - "pkg-config", - "vcpkg", -] - -[[package]] -name = "linear-map" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfae20f6b19ad527b550c223fddc3077a547fc70cda94b9b566575423fd303ee" - -[[package]] -name = "litemap" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" - [[package]] name = "log" version = "0.4.35" @@ -1052,27 +893,29 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] -name = "lzma-sys" -version = "0.1.20" +name = "lzma-rust2" +version = "0.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fda04ab3764e6cde78b9974eec4f779acaba7c4e84b36eca3cf77c581b85d27" +checksum = "ca93e534d1142d1d0dcca6d25fe302508a5dfb40b302802904577725ea0b695b" dependencies = [ - "cc", - "libc", - "pkg-config", + "sha2", ] [[package]] -name = "memchr" -version = "2.8.3" +name = "md-5" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest", +] [[package]] -name = "minimal-lexical" -version = "0.2.1" +name = "memchr" +version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "miniz_oxide" @@ -1095,22 +938,114 @@ dependencies = [ ] [[package]] -name = "newtype_derive" -version = "0.1.6" +name = "noodles" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac8cd24d9f185bb7223958d8c1ff7a961b74b1953fd05dba7cc568a63b3861ec" +checksum = "78906b00d2b2d144c920567724ab0dc68ef8da7fc258ef18da86bbbec572000e" dependencies = [ - "rustc_version 0.1.7", + "noodles-bam", + "noodles-bgzf", + "noodles-core", + "noodles-cram", + "noodles-csi", + "noodles-fasta", + "noodles-sam", ] [[package]] -name = "nom" -version = "7.1.3" +name = "noodles-bam" +version = "0.90.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d319ea3e4414172455eec82f0283ae3fc6a5a8e9b23bdc16ee426986a615094" +dependencies = [ + "bstr", + "indexmap", + "memchr", + "noodles-bgzf", + "noodles-core", + "noodles-csi", + "noodles-sam", +] + +[[package]] +name = "noodles-bgzf" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d22589ec50582fa0c3e629d27e5263fc5ff5d436955648ba601b7ac4155fbf2" +dependencies = [ + "bytes", + "crossbeam-channel", + "zlib-rs", +] + +[[package]] +name = "noodles-core" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +checksum = "c8dbac7c5f9a7de9fe45590f198a09697df631cd13d2060b4742cc48144555b0" dependencies = [ + "bstr", +] + +[[package]] +name = "noodles-cram" +version = "0.94.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "267b2934c706c2372af2eefde6c936cc5fbf26a899f5844cc48d62ea51cbd933" +dependencies = [ + "bitflags 2.13.2", + "bstr", + "bzip2", + "flate2", + "indexmap", + "lexical-core", + "lzma-rust2", + "md-5", + "noodles-bam", + "noodles-core", + "noodles-fasta", + "noodles-sam", +] + +[[package]] +name = "noodles-csi" +version = "0.56.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6832254d731cb022d46927ce64403221b280b17140516cafa21e43ee4140d633" +dependencies = [ + "bit-vec", + "bstr", + "indexmap", + "noodles-bgzf", + "noodles-core", +] + +[[package]] +name = "noodles-fasta" +version = "0.62.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c36aecf3899ba8ca698bddee3c7264d6e70afca6620524ece230d2c34b93021b" +dependencies = [ + "bstr", + "memchr", + "noodles-bgzf", + "noodles-core", +] + +[[package]] +name = "noodles-sam" +version = "0.85.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbaf538bea4f886de8b3fb611784a13f82c9f8e08e942849e88ec44234674512" +dependencies = [ + "bitflags 2.13.2", + "bstr", + "indexmap", + "lexical-core", "memchr", - "minimal-lexical", + "noodles-bgzf", + "noodles-core", + "noodles-csi", ] [[package]] @@ -1141,32 +1076,34 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" [[package]] -name = "openssl-src" -version = "300.6.1+3.6.3" +name = "option-ext" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846" -dependencies = [ - "cc", -] +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" [[package]] -name = "openssl-sys" -version = "0.9.118" +name = "ouroboros" +version = "0.18.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19c413d6ec9ebaf5e1c829d355cb3e9f783778d700f135be0921d52fce3c60ae" +checksum = "1e0f050db9c44b97a94723127e6be766ac5c340c48f2c4bb3ffa11713744be59" dependencies = [ - "cc", - "libc", - "openssl-src", - "pkg-config", - "vcpkg", + "aliasable", + "ouroboros_macro", + "static_assertions", ] [[package]] -name = "option-ext" -version = "0.2.0" +name = "ouroboros_macro" +version = "0.18.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +checksum = "3c7028bdd3d43083f6d8d4d5187680d0d3560d54df4cc9d752005268b41e64d0" +dependencies = [ + "heck 0.4.1", + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "syn 2.0.119", +] [[package]] name = "pathfinder_geometry" @@ -1184,15 +1121,9 @@ version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "866282e66a5609f51217181eecb81cf4f2bf78c79d41b662f9cf711e0fcb60ff" dependencies = [ - "rustc_version 0.4.1", + "rustc_version", ] -[[package]] -name = "percent-encoding" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" - [[package]] name = "pin-project-lite" version = "0.2.18" @@ -1279,15 +1210,6 @@ dependencies = [ "portable-atomic", ] -[[package]] -name = "potential_utf" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" -dependencies = [ - "zerovec", -] - [[package]] name = "ppv-lite86" version = "0.2.21" @@ -1307,10 +1229,17 @@ dependencies = [ ] [[package]] -name = "quick-error" -version = "1.2.3" +name = "proc-macro2-diagnostics" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" +checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "version_check", + "yansi", +] [[package]] name = "quote" @@ -1381,7 +1310,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" dependencies = [ "libredox", - "thiserror 2.0.21", + "thiserror", ] [[package]] @@ -1413,50 +1342,13 @@ version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" -[[package]] -name = "rust-htslib" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc6fe95f931db6155c90987476030375adfaa91e0990aec8d6634829c0cee390" -dependencies = [ - "bio-types", - "byteorder", - "custom_derive", - "derive-new 0.7.0", - "hts-sys", - "ieee754", - "lazy_static", - "libc", - "libz-sys", - "linear-map", - "newtype_derive", - "regex", - "thiserror 2.0.21", - "url", -] - -[[package]] -name = "rustc-hash" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" - -[[package]] -name = "rustc_version" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5f5376ea5e30ce23c03eb77cbe4962b988deead10910c372b226388b594c084" -dependencies = [ - "semver 0.1.20", -] - [[package]] name = "rustc_version" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" dependencies = [ - "semver 1.0.28", + "semver", ] [[package]] @@ -1475,14 +1367,15 @@ dependencies = [ "indexmap", "indicatif", "log", + "noodles", "number_prefix", + "ouroboros", "plotters", "plotters-backend", "plotters-svg", "rand", "rand_chacha", "rayon", - "rust-htslib", "serde", "serde_json", "serde_yaml_ng", @@ -1509,12 +1402,6 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "semver" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4f410fedcf71af0345d7607d246e7ad15faaadd49d240ee3b24e5dc21a820ac" - [[package]] name = "semver" version = "1.0.28" @@ -1578,10 +1465,15 @@ dependencies = [ ] [[package]] -name = "shlex" -version = "1.3.0" +name = "sha2" +version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" +checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] [[package]] name = "shlex" @@ -1602,16 +1494,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] -name = "smallvec" -version = "1.16.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" - -[[package]] -name = "stable_deref_trait" -version = "1.2.1" +name = "static_assertions" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "strsim" @@ -1619,19 +1505,6 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" -[[package]] -name = "strum_macros" -version = "0.26.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "rustversion", - "syn 2.0.119", -] - [[package]] name = "syn" version = "2.0.119" @@ -1654,44 +1527,13 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "synstructure" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "thiserror" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" -dependencies = [ - "thiserror-impl 1.0.69", -] - [[package]] name = "thiserror" version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl 2.0.21", -] - -[[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", + "thiserror-impl", ] [[package]] @@ -1705,22 +1547,18 @@ dependencies = [ "syn 3.0.10", ] -[[package]] -name = "tinystr" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" -dependencies = [ - "displaydoc", - "zerovec", -] - [[package]] name = "ttf-parser" version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "17f77d76d837a7830fe1d4f12b7b4ba4192c1888001c7164257e4bc6d21d96b4" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-ident" version = "1.0.27" @@ -1745,27 +1583,6 @@ version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" -[[package]] -name = "url" -version = "2.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", -] - -[[package]] -name = "utf8_iter" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" -dependencies = [ - "utf_types", -] - [[package]] name = "utf8parse" version = "0.2.2" @@ -1773,16 +1590,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] -name = "utf_types" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" - -[[package]] -name = "vcpkg" -version = "0.2.15" +name = "version_check" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "walkdir" @@ -1973,10 +1784,10 @@ dependencies = [ ] [[package]] -name = "writeable" -version = "0.6.4" +name = "yansi" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" [[package]] name = "yeslogic-fontconfig-sys" @@ -1989,29 +1800,6 @@ dependencies = [ "pkg-config", ] -[[package]] -name = "yoke" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" -dependencies = [ - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", - "synstructure", -] - [[package]] name = "zerocopy" version = "0.8.66" @@ -2032,60 +1820,6 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "zerofrom" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", - "synstructure", -] - -[[package]] -name = "zerotrie" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", -] - -[[package]] -name = "zerovec" -version = "0.11.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" -dependencies = [ - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.11.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - [[package]] name = "zlib-rs" version = "0.6.9" diff --git a/Cargo.toml b/Cargo.toml index 6f50be96..79f224bc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ name = "rustqc" version = "0.2.1" edition = "2021" -rust-version = "1.88" +rust-version = "1.89" authors = ["Phil Ewels ", "Jon Manning "] description = "Fast RNA-seq QC in a single pass: dupRadar, featureCounts, 9 RSeQC tools, preseq, samtools stats, and Qualimap — reimplemented in Rust" license = "GPL-3.0-or-later" @@ -25,8 +25,13 @@ path = "src/main.rs" # CLI argument parsing clap = { version = "4", features = ["derive", "env"] } -# BAM file reading -rust-htslib = { version = "1", features = ["static"] } +# BAM file reading (pure Rust, replaces rust-htslib) +noodles = { version = "0.111", features = ["bam", "sam", "cram", "csi", "bgzf", "core", "fasta"] } + +# Self-referential structs: lets the CRAM backends hold a noodles streaming +# iterator alongside the reader it borrows, so CRAM reads stream one container +# at a time instead of buffering every record up front. +ouroboros = "0.18" # Plotting plotters = { version = "0.3", features = ["fontconfig-dlopen"] } diff --git a/Dockerfile b/Dockerfile index 7a9f05b6..29594c48 100644 --- a/Dockerfile +++ b/Dockerfile @@ -2,17 +2,13 @@ FROM rust:1-bookworm AS builder RUN apt-get update && apt-get install -y --no-install-recommends \ - cmake \ - zlib1g-dev \ - libbz2-dev \ - liblzma-dev \ - libcurl4-openssl-dev \ - libssl-dev \ + g++ \ libfontconfig1-dev \ pkg-config \ - clang \ && rm -rf /var/lib/apt/lists/* +ENV CXX=g++ + ARG GIT_SHORT_HASH=unknown ARG CPU_TARGET="" diff --git a/docs/src/content/docs/about/contributing.md b/docs/src/content/docs/about/contributing.md index 39346a6b..e3efbb89 100644 --- a/docs/src/content/docs/about/contributing.md +++ b/docs/src/content/docs/about/contributing.md @@ -20,7 +20,7 @@ cargo build --release ``` See the [Installation](../getting-started/installation/) page for system -dependency requirements (cmake, zlib, bz2, lzma, curl, ssl, clang). +dependency requirements (C++ compiler and libfontconfig). ## Running tests diff --git a/docs/src/content/docs/about/credits.mdx b/docs/src/content/docs/about/credits.mdx index 171086ee..a5a06c94 100644 --- a/docs/src/content/docs/about/credits.mdx +++ b/docs/src/content/docs/about/credits.mdx @@ -104,7 +104,7 @@ RustQC is built with the following open-source Rust libraries: | Library | Purpose | |---------|---------| -| [rust-htslib](https://github.com/rust-bio/rust-htslib) | SAM/BAM/CRAM file I/O via htslib bindings | +| [noodles](https://crates.io/crates/noodles) | SAM/BAM/CRAM file I/O (pure Rust) | | [plotters](https://github.com/plotters-rs/plotters) | Plot generation (PNG and SVG) | | [clap](https://github.com/clap-rs/clap) | Command-line argument parsing | | [anyhow](https://github.com/dtolnay/anyhow) | Error handling | diff --git a/docs/src/content/docs/getting-started/installation.mdx b/docs/src/content/docs/getting-started/installation.mdx index 1acfd860..e3cc1ee6 100644 --- a/docs/src/content/docs/getting-started/installation.mdx +++ b/docs/src/content/docs/getting-started/installation.mdx @@ -91,7 +91,12 @@ docker run -v $(pwd):/data ghcr.io/seqeralabs/rustqc:latest-sve \ ## Build from source -Building from source requires the Rust toolchain, a C++ compiler, and a few system libraries needed by [rust-htslib](https://github.com/rust-bio/rust-htslib) for SAM/BAM/CRAM I/O. The C++ compiler is used both by rust-htslib and by RustQC's preseq FFI shim (a small C++ wrapper that links against the host's `std::mt19937` and `std::binomial_distribution` for exact bootstrap compatibility with upstream preseq). +Building from source requires the Rust toolchain, a C++ compiler, and +libfontconfig (for plot rendering). SAM/BAM/CRAM I/O is handled by the pure-Rust +[noodles](https://crates.io/crates/noodles) crate — no htslib or cmake required. +The C++ compiler is used by RustQC's preseq FFI shim (a small C++ wrapper that +links against the host's `std::mt19937` and `std::binomial_distribution` for exact +bootstrap compatibility with upstream preseq). ### Install from crates.io @@ -109,7 +114,7 @@ Select your operating system for build instructions: ```bash # Install system dependencies - brew install cmake zlib bzip2 xz curl openssl + brew install fontconfig # Install Rust (if not already installed) curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh @@ -127,8 +132,7 @@ Select your operating system for build instructions: ```bash # Install system dependencies - sudo apt install cmake zlib1g-dev libbz2-dev liblzma-dev \ - libcurl4-openssl-dev libssl-dev clang + sudo apt install g++ libfontconfig1-dev pkg-config # Install Rust (if not already installed) curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh @@ -144,8 +148,7 @@ Select your operating system for build instructions: ```bash # Install system dependencies - sudo dnf install cmake zlib-devel bzip2-devel xz-devel \ - libcurl-devel openssl-devel clang + sudo dnf install gcc-c++ fontconfig-devel pkg-config # Install Rust (if not already installed) curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh @@ -162,7 +165,7 @@ Select your operating system for build instructions: The compiled binary is at `target/release/rustqc`. You can copy it to a directory on your `PATH` for convenient access. Release builds use link-time optimization (LTO) and symbol stripping for better performance and a smaller binary. -The system dependencies are: cmake, zlib, bz2, lzma, curl, ssl, and a C++ compiler (clang or g++). +The system dependencies are: a C++ compiler (`g++` or `clang++`) and libfontconfig. ### Extra performance diff --git a/docs/src/content/docs/usage/library.mdx b/docs/src/content/docs/usage/library.mdx index 22215be7..ac630da4 100644 --- a/docs/src/content/docs/usage/library.mdx +++ b/docs/src/content/docs/usage/library.mdx @@ -19,10 +19,11 @@ Full API reference: **[docs.rs/rustqc](https://docs.rs/rustqc)**. rustqc = "0.2.1" # Or whatever the latest release is ``` -`rust-htslib` is linked statically and a small C++ component (used by the preseq -tool) is built from source, so a working C/C++ toolchain (`cc`, `c++`) is -required when building. No runtime dependencies are added beyond what the binary -already needs. +SAM/BAM/CRAM I/O is handled by the pure-Rust [noodles](https://crates.io/crates/noodles) +crate. A small C++ component (used by the preseq tool) is built from source, so a +working C++ compiler (`g++` or `clang++`) is required when building. No htslib or +cmake dependencies are needed. No runtime dependencies are added beyond what the +binary already needs. ## What's in the library diff --git a/src/lib.rs b/src/lib.rs index 150b962d..4d874e75 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,9 +12,8 @@ //! rustqc = "0.2" //! ``` //! -//! The library pulls in `rust-htslib` (linked statically), `plotters`, and -//! a small C++ component used by the preseq tool (built via `build.rs`), -//! so a working C/C++ toolchain is required at build time. +//! The library uses [noodles](https://crates.io/crates/noodles) for BAM/SAM/CRAM I/O +//! (pure Rust, no htslib dependency) and a small C++ component used by the preseq tool //! //! # Modules //! diff --git a/src/main.rs b/src/main.rs index 7652847a..98938715 100644 --- a/src/main.rs +++ b/src/main.rs @@ -27,8 +27,6 @@ use rustqc::{config, cpu, gtf, rna, summary}; use ui::{Ui, Verbosity}; -use rust_htslib::bam::Read as BamRead; - use rna::rseqc::accumulators::{RseqcAccumulators, RseqcAnnotations, RseqcConfig}; /// Common BAM filename suffixes added by alignment and duplicate-marking tools. @@ -291,7 +289,7 @@ fn run_rna(args: cli::RnaArgs, ui: &Ui) -> Result<()> { // Validate all input alignment files before expensive GTF parsing for bam_path in &args.input { - let mut reader = rust_htslib::bam::Reader::from_path(bam_path) + let mut reader = crate::rna::bam::Reader::from_path(bam_path) .with_context(|| format!("Cannot open alignment file '{}'", bam_path))?; if let Some(ref reference) = args.reference { reader @@ -1017,7 +1015,7 @@ fn process_single_bam( // Reference names + lengths from the alignment header (samtools-style // outputs, junction_annotation, and the split_bam target lookup) let bam_header_refs = { - let reader = rust_htslib::bam::Reader::from_path(bam_path) + let reader = crate::rna::bam::Reader::from_path(bam_path) .with_context(|| format!("Failed to open BAM for header: {}", bam_path))?; let header = reader.header(); (0..header.target_count()) diff --git a/src/rna/bam/align_header.rs b/src/rna/bam/align_header.rs new file mode 100644 index 00000000..cf0194f0 --- /dev/null +++ b/src/rna/bam/align_header.rs @@ -0,0 +1,66 @@ +//! SAM/BAM header wrapper. + +/// SAM header wrapper with rust-htslib-compatible helpers. +#[derive(Debug, Clone)] +pub struct Header { + pub(crate) inner: noodles::sam::Header, + ref_names: Vec, + ref_lengths: Vec, +} + +impl Header { + /// Wrap a noodles SAM header. + pub fn from_noodles(inner: noodles::sam::Header) -> Self { + let mut ref_names = Vec::new(); + let mut ref_lengths = Vec::new(); + for (name, map) in inner.reference_sequences() { + ref_names.push(String::from_utf8_lossy(name.as_ref()).into_owned()); + let len = u64::try_from(usize::from(map.length())).unwrap_or(0); + ref_lengths.push(len); + } + Self { + inner, + ref_names, + ref_lengths, + } + } + + /// Create an empty header (rust-htslib-compatible constructor). + pub fn new() -> Self { + Self::empty() + } + + /// Create an empty header. + pub fn empty() -> Self { + Self::from_noodles(noodles::sam::Header::default()) + } + + /// Number of reference sequences. + pub fn target_count(&self) -> u32 { + self.ref_names.len() as u32 + } + + /// Reference name for a target ID. + pub fn tid2name(&self, tid: u32) -> &[u8] { + self.ref_names + .get(tid as usize) + .map(|s| s.as_bytes()) + .unwrap_or(b"*") + } + + /// Reference length for a target ID. + pub fn target_len(&self, tid: u32) -> Option { + self.ref_lengths.get(tid as usize).copied() + } + + /// Borrow the underlying noodles header. + pub fn noodles_header(&self) -> &noodles::sam::Header { + &self.inner + } +} + +impl Default for Header { + fn default() -> Self { + Self::empty() + } +} diff --git a/src/rna/bam/align_record.rs b/src/rna/bam/align_record.rs new file mode 100644 index 00000000..14bebfe2 --- /dev/null +++ b/src/rna/bam/align_record.rs @@ -0,0 +1,347 @@ +//! BAM record wrapper with a rust-htslib-compatible API backed by noodles. + +use std::io; + +use anyhow::{Context, Result}; +use noodles::bam as noodles_bam; +use noodles::sam::alignment::record::data::field::Tag; +use noodles::sam::alignment::record_buf::data::field::Value; +use noodles::sam::alignment::Record as AlignmentRecord; +use noodles::sam::alignment::RecordBuf; + +use super::cigar::{decode_op, decode_op_from_op, Cigar, CigarStringView}; + +/// SAM/BAM auxiliary tag value (integer variants used by RustQC). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Aux { + U8(u8), + U16(u16), + U32(u32), + I8(i8), + I16(i16), + I32(i32), +} + +/// Sequence view with htslib-compatible base encoding. +pub struct Seq<'a> { + seq_packed: &'a [u8], + seq_len: usize, +} + +impl<'a> Seq<'a> { + pub fn len(&self) -> usize { + self.seq_len + } + + pub fn is_empty(&self) -> bool { + self.seq_len == 0 + } + + /// BAM 4-bit encoded sequence bytes for samtools-compatible CHK checksums. + pub fn encoded_bytes(&self) -> &[u8] { + let nbytes = self.seq_len.div_ceil(2); + &self.seq_packed[..nbytes.min(self.seq_packed.len())] + } + + /// BAM 4-bit encoded base at `i` (A=1, C=2, G=4, T=8, N=15). + pub fn encoded_base(&self, i: usize) -> u8 { + if i >= self.seq_len { + return 15; + } + let byte = self.seq_packed[i / 2]; + if i.is_multiple_of(2) { + byte >> 4 + } else { + byte & 0x0f + } + } + + pub fn as_bytes(&self) -> Vec { + (0..self.seq_len) + .map(|i| b"=ACMGRSVTWYHKDBN"[self.encoded_base(i) as usize]) + .collect() + } +} + +/// A BAM alignment record with rust-htslib-compatible accessors. +#[derive(Debug, Clone, PartialEq)] +pub struct Record { + inner: RecordBuf, + seq_packed: Vec, + qual_cache: Vec, + cigar_cache: Vec, +} + +impl Default for Record { + fn default() -> Self { + Self::new() + } +} + +impl Record { + pub fn new() -> Self { + Self { + inner: RecordBuf::default(), + seq_packed: Vec::new(), + qual_cache: Vec::new(), + cigar_cache: Vec::new(), + } + } + + pub fn set_buf(&mut self, buf: RecordBuf, seq_packed: Vec) { + self.inner = buf; + self.seq_packed = seq_packed; + self.refresh_caches(); + } + + fn refresh_caches(&mut self) { + self.qual_cache = self.inner.quality_scores().as_ref().to_vec(); + self.cigar_cache = self + .inner + .cigar() + .as_ref() + .iter() + .map(|&op| decode_op_from_op(op)) + .collect(); + } + + pub(crate) fn from_bam( + header: &noodles::sam::Header, + bam: &noodles_bam::Record, + ) -> Result { + let mut inner = RecordBuf::default(); + inner + .try_clone_from_alignment_record(header, bam) + .context("failed to convert BAM record")?; + let cigar_cache = bam + .cigar() + .iter() + .map(decode_op) + .collect::, io::Error>>() + .context("failed to decode BAM CIGAR")?; + Ok(Self { + inner, + seq_packed: bam.sequence().as_bytes().to_vec(), + qual_cache: bam.quality_scores().as_ref().to_vec(), + cigar_cache, + }) + } + + pub(crate) fn from_buf(buf: RecordBuf, seq_packed: Option>) -> Self { + let seq_packed = seq_packed.unwrap_or_else(|| pack_ascii_sequence(buf.sequence().as_ref())); + let mut record = Self { + inner: buf, + seq_packed, + qual_cache: Vec::new(), + cigar_cache: Vec::new(), + }; + record.refresh_caches(); + record + } + + pub fn flags(&self) -> u16 { + self.inner.flags().bits() + } + + pub fn tid(&self) -> i32 { + self.inner + .reference_sequence_id() + .map(|id| id as i32) + .unwrap_or(-1) + } + + pub fn pos(&self) -> i64 { + self.inner + .alignment_start() + .map(|p| i64::try_from(usize::from(p) - 1).unwrap_or(-1)) + .unwrap_or(-1) + } + + pub fn mtid(&self) -> i32 { + self.inner + .mate_reference_sequence_id() + .map(|id| id as i32) + .unwrap_or(-1) + } + + pub fn mpos(&self) -> i64 { + self.inner + .mate_alignment_start() + .map(|p| i64::try_from(usize::from(p) - 1).unwrap_or(-1)) + .unwrap_or(-1) + } + + pub fn mapq(&self) -> u8 { + self.inner + .mapping_quality() + .map(|mq| mq.get()) + .unwrap_or(255) + } + + pub fn qname(&self) -> &[u8] { + self.inner.name().map(|n| n.as_ref()).unwrap_or(b"*") + } + + pub fn seq_len(&self) -> usize { + self.inner.sequence().len() + } + + pub fn insert_size(&self) -> i64 { + i64::from(self.inner.template_length()) + } + + pub fn cigar(&self) -> CigarStringView { + CigarStringView::from_ops(self.cigar_cache.clone(), self.pos().max(0) as u64) + } + + /// BAM-encoded CIGAR operations (`len << 4 | op`), as htslib stores them. + pub fn raw_cigar(&self) -> Vec { + self.cigar_cache.iter().map(Cigar::encode).collect() + } + + pub fn seq(&self) -> Seq<'_> { + Seq { + seq_packed: &self.seq_packed, + seq_len: self.inner.sequence().len(), + } + } + + pub fn qual(&self) -> &[u8] { + &self.qual_cache + } + + pub fn aux(&self, tag: &[u8]) -> Result { + if tag.len() != 2 { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "aux tag must be 2 bytes", + )); + } + let tag = Tag::new(tag[0], tag[1]); + match self.inner.data().get(&tag) { + Some(Value::Int8(v)) => Ok(Aux::I8(*v)), + Some(Value::Int16(v)) => Ok(Aux::I16(*v)), + Some(Value::Int32(v)) => Ok(Aux::I32(*v)), + Some(Value::UInt8(v)) => Ok(Aux::U8(*v)), + Some(Value::UInt16(v)) => Ok(Aux::U16(*v)), + Some(Value::UInt32(v)) => Ok(Aux::U32(*v)), + Some(_) => Err(io::Error::new( + io::ErrorKind::InvalidData, + "non-integer aux tag", + )), + None => Err(io::Error::new(io::ErrorKind::NotFound, "aux tag not found")), + } + } + + pub fn is_paired(&self) -> bool { + self.inner.flags().is_segmented() + } + + pub fn is_reverse(&self) -> bool { + self.inner.flags().is_reverse_complemented() + } + + pub fn is_first_in_template(&self) -> bool { + self.inner.flags().is_first_segment() + } + + pub fn is_unmapped(&self) -> bool { + self.inner.flags().is_unmapped() + } + + pub fn is_mate_unmapped(&self) -> bool { + self.inner.flags().is_mate_unmapped() + } + + pub fn is_secondary(&self) -> bool { + self.inner.flags().is_secondary() + } + + pub fn is_supplementary(&self) -> bool { + self.inner.flags().is_supplementary() + } + + pub fn is_quality_check_failed(&self) -> bool { + self.inner.flags().is_qc_fail() + } +} +fn pack_ascii_sequence(seq: &[u8]) -> Vec { + // Full htslib `seq_nt16_table` mapping (the inverse of the `=ACMGRSVTWYHKDBN` + // decode table), so IUPAC ambiguity codes round-trip through SAM/CRAM packing + // and produce samtools-identical CHK checksums. Unknown bytes fall back to N. + const TABLE: [u8; 256] = { + let mut t = [15u8; 256]; + let symbols = b"=ACMGRSVTWYHKDBN"; + let mut code = 0usize; + while code < symbols.len() { + let upper = symbols[code]; + t[upper as usize] = code as u8; + // Map the lowercase variant of each letter to the same code. + if upper.is_ascii_uppercase() { + t[upper.to_ascii_lowercase() as usize] = code as u8; + } + code += 1; + } + t + }; + let mut out = Vec::with_capacity(seq.len().div_ceil(2)); + for chunk in seq.chunks(2) { + let l = TABLE[chunk[0] as usize]; + let r = chunk.get(1).map(|b| TABLE[*b as usize]).unwrap_or(0); + out.push((l << 4) | r); + } + out +} + +pub(crate) fn alignment_to_record( + header: &noodles::sam::Header, + alignment: &dyn AlignmentRecord, +) -> Result { + let mut inner = RecordBuf::default(); + inner + .try_clone_from_alignment_record(header, alignment) + .context("failed to clone alignment record")?; + Ok(Record::from_buf(inner, None)) +} + +/// Export for writer tests that need BAM bytes from a SAM line. +pub(crate) fn record_buf_for_writer(record: &Record) -> &RecordBuf { + &record.inner +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn packs_all_iupac_codes_losslessly() { + // The full set of IUPAC symbols, in htslib 4-bit code order, must pack + // and decode back unchanged (the inverse of the `=ACMGRSVTWYHKDBN` table). + let seq = b"=ACMGRSVTWYHKDBN".to_vec(); + let packed = pack_ascii_sequence(&seq); + let view = Seq { + seq_packed: &packed, + seq_len: seq.len(), + }; + assert_eq!(view.as_bytes(), seq); + for code in 0u8..16 { + assert_eq!(view.encoded_base(code as usize), code); + } + } + + #[test] + fn packs_lowercase_like_uppercase() { + assert_eq!( + pack_ascii_sequence(b"acgtnmrn"), + pack_ascii_sequence(b"ACGTNMRN") + ); + } + + #[test] + fn packs_odd_length_trailing_nibble_is_zero() { + // Odd-length sequences leave the final low nibble as 0 (`=`), matching + // the BAM 4-bit packing layout. + let packed = pack_ascii_sequence(b"A"); + assert_eq!(packed, vec![0b0001_0000]); + } +} diff --git a/src/rna/bam/cigar.rs b/src/rna/bam/cigar.rs new file mode 100644 index 00000000..ade873db --- /dev/null +++ b/src/rna/bam/cigar.rs @@ -0,0 +1,144 @@ +//! CIGAR types matching the rust-htslib API surface used by RustQC. + +use noodles::sam::alignment::record::cigar::{op::Kind, Op}; + +/// A CIGAR operation, mirroring `rust_htslib::bam::record::Cigar`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Cigar { + /// Alignment match (`M`). + Match(u32), + /// Insertion (`I`). + Ins(u32), + /// Deletion (`D`). + Del(u32), + /// Skipped region / intron (`N`). + RefSkip(u32), + /// Soft clip (`S`). + SoftClip(u32), + /// Hard clip (`H`). + HardClip(u32), + /// Padding (`P`). + Pad(u32), + /// Sequence match (`=`). + Equal(u32), + /// Sequence mismatch (`X`). + Diff(u32), +} + +impl Cigar { + /// Length of this operation. + pub fn len(&self) -> u32 { + match self { + Self::Match(n) + | Self::Ins(n) + | Self::Del(n) + | Self::RefSkip(n) + | Self::SoftClip(n) + | Self::HardClip(n) + | Self::Pad(n) + | Self::Equal(n) + | Self::Diff(n) => *n, + } + } + + /// BAM binary encoding (`len << 4 | op`, op codes `MIDNSHP=X`). + pub fn encode(&self) -> u32 { + let op = match self { + Self::Match(_) => 0, + Self::Ins(_) => 1, + Self::Del(_) => 2, + Self::RefSkip(_) => 3, + Self::SoftClip(_) => 4, + Self::HardClip(_) => 5, + Self::Pad(_) => 6, + Self::Equal(_) => 7, + Self::Diff(_) => 8, + }; + (self.len() << 4) | op + } + + /// Whether this operation has zero length. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +/// Decode a noodles CIGAR operation into RustQC's CIGAR enum. +pub fn decode_op_from_op(op: Op) -> Cigar { + match op.kind() { + Kind::Match => Cigar::Match(op.len() as u32), + Kind::Insertion => Cigar::Ins(op.len() as u32), + Kind::Deletion => Cigar::Del(op.len() as u32), + Kind::Skip => Cigar::RefSkip(op.len() as u32), + Kind::SoftClip => Cigar::SoftClip(op.len() as u32), + Kind::HardClip => Cigar::HardClip(op.len() as u32), + Kind::Pad => Cigar::Pad(op.len() as u32), + Kind::SequenceMatch => Cigar::Equal(op.len() as u32), + Kind::SequenceMismatch => Cigar::Diff(op.len() as u32), + } +} + +/// Decode a fallible noodles CIGAR iterator item. +pub fn decode_op(op: Result) -> Result { + op.map(decode_op_from_op) +} + +/// Compute the 1-based exclusive reference end position using htslib semantics +/// (M, D, N, =, X consume reference; I, S, H, P do not). +pub fn reference_end(start: u64, ops: &[Cigar]) -> u64 { + let mut end = start; + for op in ops { + match op { + Cigar::Match(len) | Cigar::Equal(len) | Cigar::Diff(len) => { + end += u64::from(*len); + } + Cigar::Del(len) | Cigar::RefSkip(len) => { + end += u64::from(*len); + } + Cigar::Ins(_) | Cigar::SoftClip(_) | Cigar::HardClip(_) | Cigar::Pad(_) => {} + } + } + end +} + +/// Owned CIGAR string (used in unit tests). +#[derive(Debug, Clone, Default)] +pub struct CigarString(pub Vec); + +/// View over a decoded CIGAR with htslib-compatible helpers. +#[derive(Debug, Clone)] +pub struct CigarStringView { + ops: Vec, + start: u64, +} + +impl CigarStringView { + /// Build a view from decoded operations and a 0-based reference start. + pub(crate) fn from_ops(ops: Vec, start: u64) -> Self { + Self { ops, start } + } + + /// Build a view from an owned CIGAR string and reference start (0-based). + pub fn new(cigar: CigarString, start: u64) -> Self { + Self { + ops: cigar.0, + start, + } + } + + /// Iterate CIGAR operations. + pub fn iter(&self) -> impl Iterator { + self.ops.iter() + } + + /// Reference end position (htslib `end_pos` semantics). + pub fn end_pos(&self) -> u64 { + reference_end(self.start, &self.ops) + } + + /// Slice view of decoded operations (rust-htslib `CigarStringView::as_ref`). + #[allow(clippy::wrong_self_convention, clippy::should_implement_trait)] + pub fn as_ref(&self) -> &[Cigar] { + &self.ops + } +} diff --git a/src/rna/bam/io.rs b/src/rna/bam/io.rs new file mode 100644 index 00000000..4dc5e849 --- /dev/null +++ b/src/rna/bam/io.rs @@ -0,0 +1,918 @@ +//! BAM/SAM/CRAM readers with a rust-htslib-compatible API. + +use std::collections::HashSet; +use std::fs::File; +use std::io::BufRead; +use std::path::{Path, PathBuf}; + +use super::align_header::Header; +use super::align_record::{alignment_to_record, Record}; +use anyhow::{Context, Result}; +use noodles::bam as noodles_bam; +use noodles::bgzf; +use noodles::bgzf::io::Seek as _; +use noodles::core::region::Interval; +use noodles::core::Region; +use noodles::cram as noodles_cram; +use noodles::csi::binning_index::index::reference_sequence::bin::Chunk; +use noodles::fasta as noodles_fasta; +use noodles::sam as noodles_sam; + +fn store_record(record: &mut Record, loaded: Record) -> Result<()> { + *record = loaded; + Ok(()) +} + +/// Fetch target for indexed readers. +#[derive(Debug, Clone, Copy)] +pub enum FetchDefinition { + /// Unmapped reads stored after mapped reads in the BAM file. + Unmapped, +} + +/// Fetch target accepted by [`IndexedReader::fetch`]. +#[derive(Debug, Clone, Copy)] +pub enum FetchTarget { + /// Reference sequence ID. + Tid(u32), + /// Unmapped reads bucket. + Unmapped, +} + +impl From for FetchTarget { + fn from(value: u32) -> Self { + Self::Tid(value) + } +} + +impl From for FetchTarget { + fn from(value: FetchDefinition) -> Self { + match value { + FetchDefinition::Unmapped => Self::Unmapped, + } + } +} + +/// Trait mirroring `rust_htslib::bam::Read`. +pub trait Read { + /// Read the next record into `record`. + fn read(&mut self, record: &mut Record) -> Option>; +} + +fn load_fasta_repository(path: &Path) -> Result { + let mut reader = noodles_fasta::io::reader::Builder + .build_from_path(path) + .with_context(|| format!("failed to open reference FASTA {}", path.display()))?; + let mut records = Vec::new(); + for result in reader.records() { + records.push(result.context("failed to read reference FASTA record")?); + } + Ok(noodles_fasta::Repository::new(records)) +} + +fn open_bam_reader(path: &Path) -> Result>> { + let file = + File::open(path).with_context(|| format!("failed to open BAM file {}", path.display()))?; + Ok(noodles_bam::io::Reader::new(file)) +} + +fn cram_container_query_index(path: &Path) -> Result { + let mut index_path = path.as_os_str().to_os_string(); + index_path.push(".crai"); + let mut index = noodles_cram::crai::fs::read(&index_path).with_context(|| { + format!( + "failed to read CRAM index {}", + Path::new(&index_path).display() + ) + })?; + // noodles 0.94 decodes the whole container for each CRAI slice entry. + // Keep one entry per reference/container, preserving other references' + // queries and all physical records, including repeated read names. + let mut seen = HashSet::new(); + index.retain(|entry| seen.insert((entry.reference_sequence_id(), entry.offset()))); + Ok(index) +} + +/// Owned iterator over decoded CRAM records. Boxed so the `query` and +/// `query_unmapped` iterators (which have distinct concrete types) can share one +/// field on the indexed cursor. +type CramRecordIter<'a> = + Box> + 'a>; + +/// Self-referential holder for a sequential CRAM reader plus its streaming record +/// iterator. +/// +/// noodles' `Records` iterator borrows the reader and header, so it cannot sit +/// next to them in a plain struct. ouroboros makes that borrow sound, letting us +/// stream one container at a time instead of collecting every record up front. +#[ouroboros::self_referencing] +struct CramReaderCursor { + reader: noodles_cram::io::Reader, + header: noodles_sam::Header, + #[borrows(mut reader, header)] + #[not_covariant] + iter: noodles_cram::io::reader::Records<'this, 'this, File>, +} + +/// Self-referential holder for an indexed CRAM reader plus the iterator from its +/// most recent `fetch`. Rebuilt on each fetch via `into_heads`; before the first +/// fetch the iterator is empty. +#[ouroboros::self_referencing] +struct CramIndexedCursor { + reader: noodles_cram::io::IndexedReader, + header: noodles_sam::Header, + #[borrows(mut reader, header)] + #[not_covariant] + iter: CramRecordIter<'this>, +} + +enum ReaderBackend { + Bam { + reader: noodles_bam::io::Reader>, + header: Header, + scratch: noodles_bam::Record, + }, + Sam { + reader: noodles_sam::io::Reader>, + header: Header, + scratch: noodles_sam::Record, + }, + Cram { + cursor: CramReaderCursor, + header: Header, + }, +} + +/// Sequential alignment file reader (BAM/SAM/CRAM). +pub struct Reader { + backend: ReaderBackend, + source_path: PathBuf, + cram_reference: Option, + decompression_threads: usize, +} + +impl Reader { + /// Open an alignment file, detecting the format from the extension. + pub fn from_path>(path: P) -> Result { + let path = path.as_ref().to_path_buf(); + let path_str = path.to_string_lossy(); + let backend = if path_str.ends_with(".sam") { + Self::open_sam(&path)? + } else if path_str.ends_with(".cram") { + Self::open_cram(&path, None)? + } else { + Self::open_bam(&path)? + }; + Ok(Self { + backend, + source_path: path, + cram_reference: None, + decompression_threads: 0, + }) + } + + fn open_bam(path: &Path) -> Result { + let mut reader = open_bam_reader(path)?; + let header = + Header::from_noodles(reader.read_header().context("failed to read BAM header")?); + Ok(ReaderBackend::Bam { + reader, + header, + scratch: noodles_bam::Record::default(), + }) + } + + fn open_sam(path: &Path) -> Result { + let mut reader = noodles_sam::io::reader::Builder::default() + .build_from_path(path) + .with_context(|| format!("failed to open SAM file {}", path.display()))?; + let header = + Header::from_noodles(reader.read_header().context("failed to read SAM header")?); + Ok(ReaderBackend::Sam { + reader, + header, + scratch: noodles_sam::Record::default(), + }) + } + + fn open_cram(path: &Path, reference: Option<&Path>) -> Result { + let repository = if let Some(fasta_path) = reference { + load_fasta_repository(fasta_path)? + } else { + noodles_fasta::Repository::default() + }; + let file = File::open(path) + .with_context(|| format!("failed to open CRAM file {}", path.display()))?; + let mut reader = noodles_cram::io::reader::Builder::default() + .set_reference_sequence_repository(repository) + .build_from_reader(file); + let sam_header = reader.read_header().context("failed to read CRAM header")?; + let header = Header::from_noodles(sam_header.clone()); + let cursor = CramReaderCursorBuilder { + reader, + header: sam_header, + iter_builder: |reader, header| reader.records(header), + } + .build(); + Ok(ReaderBackend::Cram { cursor, header }) + } + + /// Set the reference FASTA for CRAM decoding. + pub fn set_reference>(&mut self, path: P) -> Result<()> { + let path = path.as_ref().to_path_buf(); + self.cram_reference = Some(path.clone()); + if matches!(self.backend, ReaderBackend::Cram { .. }) { + self.backend = Self::open_cram(&self.source_path, Some(&path))?; + } + Ok(()) + } + + /// Enable BGZF decompression threads (BAM only). + /// + /// Multithreaded BGZF decompression is not yet wired through noodles; this + /// stores the requested thread count for API compatibility. + pub fn set_threads(&mut self, threads: usize) -> Result<()> { + self.decompression_threads = threads; + Ok(()) + } + + /// Return the SAM/BAM header. + pub fn header(&self) -> &Header { + match &self.backend { + ReaderBackend::Bam { header, .. } + | ReaderBackend::Sam { header, .. } + | ReaderBackend::Cram { header, .. } => header, + } + } +} + +impl Read for Reader { + fn read(&mut self, record: &mut Record) -> Option> { + match &mut self.backend { + ReaderBackend::Bam { + reader, + header, + scratch, + } => match reader.read_record(scratch) { + Ok(0) => None, + Ok(_) => Some( + Record::from_bam(header.noodles_header(), scratch) + .and_then(|loaded| store_record(record, loaded)), + ), + Err(e) => Some(Err(e.into())), + }, + ReaderBackend::Sam { + reader, + header, + scratch, + } => match reader.read_record(scratch) { + Ok(0) => None, + Ok(_) => Some( + alignment_to_record(header.noodles_header(), scratch) + .and_then(|loaded| store_record(record, loaded)), + ), + Err(e) => Some(Err(e.into())), + }, + ReaderBackend::Cram { cursor, .. } => match cursor.with_iter_mut(|iter| iter.next()) { + Some(Ok(buf)) => Some(store_record(record, Record::from_buf(buf, None))), + Some(Err(e)) => Some(Err(e.into())), + None => None, + }, + } + } +} + +/// Lazy streaming cursor for indexed BAM reads. +/// +/// Mirrors the chunk state machine in `noodles_csi::io::Query` so records are +/// decoded one at a time directly from the BGZF stream, instead of buffering an +/// entire reference sequence (or all unmapped reads) in memory. This matters +/// because dupRadar fetches one chromosome per worker thread concurrently, so +/// the old buffering cost scaled as reference size times thread count. +enum BamCursor { + /// No active fetch, or the current fetch has been exhausted. + Done, + /// Streaming the mapped records of a single reference via its index chunks. + Region { + chunks: std::vec::IntoIter, + /// End virtual position of the chunk currently being read; `None` means + /// the next chunk still needs to be seeked to. + chunk_end: Option, + reference_sequence_id: usize, + }, + /// Streaming records with no reference from a seeked position to end of file. + Unmapped, +} + +enum IndexedBackend { + Bam { + reader: noodles_bam::io::IndexedReader>, + header: Header, + scratch: noodles_bam::Record, + cursor: BamCursor, + }, + Cram { + /// `None` only transiently while a fetch rebuilds the cursor. + cursor: Option, + header: Header, + }, +} + +/// Indexed alignment file reader (BAM/CRAM with .bai/.csi/.crai). +pub struct IndexedReader { + backend: IndexedBackend, + source_path: PathBuf, + cram_reference: Option, +} + +impl IndexedReader { + /// Open an indexed alignment file. + pub fn from_path>(path: P) -> Result { + let path = path.as_ref().to_path_buf(); + let backend = if path.to_string_lossy().ends_with(".cram") { + let mut reader = noodles_cram::io::indexed_reader::Builder::default() + .set_index(cram_container_query_index(&path)?) + .build_from_path(&path) + .with_context(|| format!("failed to open indexed CRAM {}", path.display()))?; + let sam_header = reader + .read_header() + .context("failed to read indexed CRAM header")?; + let header = Header::from_noodles(sam_header.clone()); + let cursor = CramIndexedCursorBuilder { + reader, + header: sam_header, + iter_builder: |_reader, _header| Box::new(std::iter::empty()) as CramRecordIter, + } + .build(); + IndexedBackend::Cram { + cursor: Some(cursor), + header, + } + } else { + let mut reader = noodles_bam::io::indexed_reader::Builder::default() + .build_from_path(&path) + .with_context(|| format!("failed to open indexed BAM {}", path.display()))?; + let header = Header::from_noodles( + reader + .read_header() + .context("failed to read indexed BAM header")?, + ); + IndexedBackend::Bam { + reader, + header, + scratch: noodles_bam::Record::default(), + cursor: BamCursor::Done, + } + }; + Ok(Self { + backend, + source_path: path, + cram_reference: None, + }) + } + + /// Set the reference FASTA for CRAM decoding. + pub fn set_reference>(&mut self, path: P) -> Result<()> { + let path = path.as_ref().to_path_buf(); + self.cram_reference = Some(path.clone()); + let cram_path = self.source_path.clone(); + if let IndexedBackend::Cram { cursor, header } = &mut self.backend { + let repository = load_fasta_repository(&path)?; + let mut reader = noodles_cram::io::indexed_reader::Builder::default() + .set_reference_sequence_repository(repository) + .set_index(cram_container_query_index(&cram_path)?) + .build_from_path(&cram_path)?; + let sam_header = reader.read_header()?; + *header = Header::from_noodles(sam_header.clone()); + *cursor = Some( + CramIndexedCursorBuilder { + reader, + header: sam_header, + iter_builder: |_reader, _header| Box::new(std::iter::empty()) as CramRecordIter, + } + .build(), + ); + } + Ok(()) + } + + /// Enable BGZF decompression threads (BAM only). + /// + /// Indexed fetching dominates runtime; this is a no-op for indexed readers. + pub fn set_threads(&mut self, _threads: usize) -> Result<()> { + Ok(()) + } + + /// Seek to a reference ID or the unmapped read bucket. + pub fn fetch>(&mut self, target: T) -> Result<()> { + match target.into() { + FetchTarget::Tid(tid) => self.fetch_tid(tid), + FetchTarget::Unmapped => self.fetch_unmapped(), + } + } + + fn fetch_tid(&mut self, tid: u32) -> Result<()> { + match &mut self.backend { + IndexedBackend::Bam { reader, cursor, .. } => { + // Resolve the chunks covering the whole reference straight from + // the index and stream them lazily, rather than buffering every + // record on the reference in memory. + let chunks = reader + .index() + .query(tid as usize, Interval::from(..)) + .with_context(|| format!("failed to query index for tid {tid}"))?; + *cursor = BamCursor::Region { + chunks: chunks.into_iter(), + chunk_end: None, + reference_sequence_id: tid as usize, + }; + Ok(()) + } + IndexedBackend::Cram { cursor, header } => { + // Rebuild the cursor with a fresh region query. noodles' query + // iterator borrows the reader, so we recover the owned reader via + // `into_heads` and stream container-by-container from there. + let region = region_for_tid(header, tid); + let heads = cursor.take().expect("CRAM cursor present").into_heads(); + *cursor = Some( + CramIndexedCursorTryBuilder { + reader: heads.reader, + header: heads.header, + iter_builder: |reader, header| -> Result { + // noodles filters on the interval only, so a + // multi-reference slice also yields other references' + // records; keep this reference's. + let query = reader + .query(header, ®ion) + .with_context(|| format!("failed to query CRAM tid {tid}"))? + .filter(move |result| { + result.as_ref().map_or(true, |record| { + record.reference_sequence_id() == Some(tid as usize) + }) + }); + Ok(Box::new(query)) + }, + } + .try_build()?, + ); + Ok(()) + } + } + } + + fn fetch_unmapped(&mut self) -> Result<()> { + let source_path = self.source_path.clone(); + match &mut self.backend { + IndexedBackend::Bam { reader, cursor, .. } => { + // Seek to the last linear-index window of the last reference and + // stream from there, keeping only records with no reference + // (htslib's HTS_IDX_NOCOOR). Placed unmapped mates in that window + // belong to their reference's fetch. + match reader.index().last_first_record_start_position() { + Some(pos) => { + reader + .get_mut() + .seek_to_virtual_position(pos) + .context("failed to seek to unmapped BAM reads")?; + } + None => { + // The index carries no metadata pseudo-bin, so there is + // no recorded unmapped offset. Reopen and stream from the + // first record, relying on the per-record no-reference filter. + let mut fresh = noodles_bam::io::indexed_reader::Builder::default() + .build_from_path(&source_path) + .with_context(|| { + format!("failed to reopen indexed BAM {}", source_path.display()) + })?; + fresh + .read_header() + .context("failed to read indexed BAM header")?; + *reader = fresh; + } + } + *cursor = BamCursor::Unmapped; + Ok(()) + } + IndexedBackend::Cram { cursor, .. } => { + let heads = cursor.take().expect("CRAM cursor present").into_heads(); + *cursor = Some( + CramIndexedCursorTryBuilder { + reader: heads.reader, + header: heads.header, + iter_builder: |reader, header| -> Result { + // With no unplaced CRAI entry, noodles 0.94 seeks EOF + // and reports a truncated container instead of an empty query. + if reader + .index() + .iter() + .all(|entry| entry.reference_sequence_id().is_some()) + { + return Ok(Box::new(std::iter::empty())); + } + // The unplaced reads' slice can also hold placed records + // (multi-reference slice); keep only those with no reference. + let query = reader + .query_unmapped(header) + .context("failed to query unmapped CRAM reads")? + .filter(|result| { + result.as_ref().map_or(true, |record| { + record.reference_sequence_id().is_none() + }) + }); + Ok(Box::new(query)) + }, + } + .try_build()?, + ); + Ok(()) + } + } + } +} + +impl Read for IndexedReader { + fn read(&mut self, record: &mut Record) -> Option> { + match &mut self.backend { + IndexedBackend::Bam { + reader, + header, + scratch, + cursor, + } => loop { + // Take ownership of the cursor each iteration so `reader` can be + // mutated (seek/read) and the new state written back without + // fighting the borrow checker. Early returns leave the cursor as + // `Done`, which is the correct exhausted state. + match std::mem::replace(cursor, BamCursor::Done) { + BamCursor::Done => return None, + BamCursor::Unmapped => match reader.read_record(scratch) { + Ok(0) => return None, + Ok(_) => { + *cursor = BamCursor::Unmapped; + if scratch.reference_sequence_id().is_none() { + return Some( + Record::from_bam(header.noodles_header(), scratch) + .and_then(|loaded| store_record(record, loaded)), + ); + } + // Placed record before the unplaced tail: skip and continue. + } + Err(e) => return Some(Err(e.into())), + }, + BamCursor::Region { + mut chunks, + chunk_end, + reference_sequence_id, + } => match chunk_end { + None => { + let chunk = chunks.next()?; + if let Err(e) = reader.get_mut().seek_to_virtual_position(chunk.start()) + { + return Some(Err(anyhow::Error::new(e) + .context("failed to seek to BAM index chunk"))); + } + *cursor = BamCursor::Region { + chunks, + chunk_end: Some(chunk.end()), + reference_sequence_id, + }; + } + Some(end) => { + if reader.get_mut().virtual_position() >= end { + // Reached the end of this chunk; advance to the next. + *cursor = BamCursor::Region { + chunks, + chunk_end: None, + reference_sequence_id, + }; + continue; + } + match reader.read_record(scratch) { + Ok(0) => { + *cursor = BamCursor::Region { + chunks, + chunk_end: None, + reference_sequence_id, + }; + } + Ok(_) => { + *cursor = BamCursor::Region { + chunks, + chunk_end: Some(end), + reference_sequence_id, + }; + // A chunk may begin with a few records from a + // neighbouring reference; keep only ours. + let on_reference = match scratch.reference_sequence_id() { + Some(Ok(id)) => id == reference_sequence_id, + Some(Err(e)) => return Some(Err(e.into())), + None => false, + }; + if on_reference { + return Some( + Record::from_bam(header.noodles_header(), scratch) + .and_then(|loaded| store_record(record, loaded)), + ); + } + } + Err(e) => return Some(Err(e.into())), + } + } + }, + } + }, + IndexedBackend::Cram { cursor, .. } => { + let cursor = cursor.as_mut()?; + match cursor.with_iter_mut(|iter| iter.next()) { + Some(Ok(buf)) => Some(store_record(record, Record::from_buf(buf, None))), + Some(Err(e)) => Some(Err(e.into())), + None => None, + } + } + } + } +} + +fn region_for_tid(header: &Header, tid: u32) -> Region { + // Query the whole reference sequence by name. Building the `Region` directly + // (rather than formatting and re-parsing `name:start-end`) avoids mangling + // reference names that contain `:` or `-` (e.g. HLA contigs) and preserves + // non-UTF-8 names byte-for-byte. + Region::new(header.tid2name(tid).to_vec(), ..) +} + +#[cfg(test)] +mod tests { + use std::num::NonZero; + use std::sync::atomic::{AtomicU64, Ordering}; + + use noodles::core::Position; + use noodles::fasta; + use noodles::sam::alignment::io::Write as _; + use noodles::sam::alignment::record::cigar::{op::Kind, Op}; + use noodles::sam::alignment::record::Flags; + use noodles::sam::alignment::RecordBuf; + use noodles::sam::header::record::value::map::ReferenceSequence; + use noodles::sam::header::record::value::Map; + use noodles::{cram, sam}; + + use super::{FetchTarget, IndexedReader, Read, Reader}; + use crate::rna::bam::Record; + + static COUNTER: AtomicU64 = AtomicU64::new(0); + + fn temp_path(suffix: &str) -> std::path::PathBuf { + let id = COUNTER.fetch_add(1, Ordering::Relaxed); + std::env::temp_dir().join(format!( + "rustqc_cram_test_{}_{id}_{suffix}", + std::process::id() + )) + } + + // Writes a tiny reference-backed CRAM file and streams it back through the + // ouroboros-backed sequential `Reader`, verifying the records come through in + // order rather than being buffered or dropped. + #[test] + fn streams_cram_records_sequentially() { + let reference = b"ACGTACGTACGT".to_vec(); + let cram_path = temp_path("seq.cram"); + let fasta_path = temp_path("ref.fa"); + + std::fs::write(&fasta_path, b">ref0\nACGTACGTACGT\n").unwrap(); + + let repository = fasta::Repository::new(vec![fasta::Record::new( + fasta::record::Definition::new("ref0", None), + fasta::record::Sequence::from(reference.clone()), + )]); + + let header = sam::Header::builder() + .add_reference_sequence( + "ref0", + Map::::new(NonZero::new(reference.len()).unwrap()), + ) + .build(); + + let expected = [(b"r1".to_vec(), 0i64), (b"r2".to_vec(), 4i64)]; + let records: Vec = expected + .iter() + .map(|(name, start_zero)| { + let start = Position::new(*start_zero as usize + 1).unwrap(); + RecordBuf::builder() + .set_name(&name[..]) + .set_flags(Flags::empty()) + .set_reference_sequence_id(0) + .set_alignment_start(start) + .set_cigar([Op::new(Kind::Match, 4)].into_iter().collect()) + .set_sequence(b"ACGT".to_vec().into()) + .set_quality_scores(vec![30u8; 4].into()) + .build() + }) + .collect(); + + { + let mut writer = cram::io::writer::Builder::default() + .set_reference_sequence_repository(repository) + .build_from_path(&cram_path) + .unwrap(); + writer.write_header(&header).unwrap(); + for record in &records { + writer.write_alignment_record(&header, record).unwrap(); + } + writer.try_finish(&header).unwrap(); + } + + let mut reader = Reader::from_path(&cram_path).unwrap(); + reader.set_reference(&fasta_path).unwrap(); + + let mut record = Record::new(); + let mut got = Vec::new(); + while let Some(result) = reader.read(&mut record) { + result.unwrap(); + got.push((record.qname().to_vec(), record.pos())); + } + + let _ = std::fs::remove_file(&cram_path); + let _ = std::fs::remove_file(&fasta_path); + + assert_eq!(got, expected.to_vec()); + } + + // ------------------------------------------------------------------------ + // Unmapped sweep: htslib's HTS_IDX_NOCOOR returns exactly the records with + // no reference (tid -1). A placed unmapped mate (0x4 with a tid) belongs + // to its reference's fetch, so the sweep must not return it again. + // ------------------------------------------------------------------------ + + const CONTIG_LEN: usize = 100_000; + + /// Two mapped reads on chr1; on chr2, a mapped read whose unmapped mate is + /// placed at its position in chr2's last 16 kb linear-index window; two + /// unplaced reads (no reference) at the end. + fn sweep_world() -> (sam::Header, Vec) { + let header: sam::Header = format!( + "@HD\tVN:1.6\tSO:coordinate\n@SQ\tSN:chr1\tLN:{CONTIG_LEN}\n@SQ\tSN:chr2\tLN:{CONTIG_LEN}\n" + ) + .parse() + .unwrap(); + let rec = |name: &str, flags: u16, tid: Option, start: Option| { + let mut builder = RecordBuf::builder() + .set_name(name) + .set_flags(Flags::from(flags)) + .set_sequence(b"AAAA".to_vec().into()) + .set_quality_scores(vec![30u8; 4].into()); + if let (Some(tid), Some(start)) = (tid, start) { + let start = Position::new(start).unwrap(); + builder = builder + .set_reference_sequence_id(tid) + .set_alignment_start(start); + if flags & 0x1 != 0 { + builder = builder + .set_mate_reference_sequence_id(tid) + .set_mate_alignment_start(start); + } + if flags & 0x4 == 0 { + builder = builder + .set_mapping_quality( + sam::alignment::record::MappingQuality::new(60).unwrap(), + ) + .set_cigar([Op::new(Kind::Match, 4)].into_iter().collect()); + } + } + builder.build() + }; + let records = vec![ + rec("r0", 0x0, Some(0), Some(1_001)), + rec("r1", 0x0, Some(0), Some(1_201)), + rec("r2", 0x1 | 0x8 | 0x40, Some(1), Some(99_001)), + rec("r3", 0x1 | 0x4 | 0x80, Some(1), Some(99_001)), + rec("u1", 0x4, None, None), + rec("u2", 0x4, None, None), + ]; + (header, records) + } + + /// Fetch each reference, then the unmapped bucket; return (fetch, read name) + /// for every record returned. + fn fetch_everything( + path: &std::path::Path, + fasta: Option<&std::path::Path>, + ) -> Vec<(String, String)> { + let mut reader = IndexedReader::from_path(path).unwrap(); + if let Some(fasta) = fasta { + reader.set_reference(fasta).unwrap(); + } + let mut got = Vec::new(); + let mut record = Record::new(); + let targets = [ + ("tid 0", FetchTarget::Tid(0)), + ("tid 1", FetchTarget::Tid(1)), + ("unmapped", FetchTarget::Unmapped), + ]; + for (label, target) in targets { + reader.fetch(target).unwrap(); + while let Some(result) = reader.read(&mut record) { + result.unwrap(); + got.push(( + label.to_string(), + String::from_utf8(record.qname().to_vec()).unwrap(), + )); + } + } + got + } + + fn assert_sweep(got: &[(String, String)]) { + let swept: Vec<&str> = got + .iter() + .filter(|(label, _)| label == "unmapped") + .map(|(_, name)| name.as_str()) + .collect(); + assert_eq!( + swept, + ["u1", "u2"], + "unmapped sweep must return only the unplaced records; all fetches: {got:?}" + ); + } + + fn assert_each_record_once(got: &[(String, String)]) { + let mut names: Vec<&str> = got.iter().map(|(_, name)| name.as_str()).collect(); + names.sort_unstable(); + assert_eq!( + names, + ["r0", "r1", "r2", "r3", "u1", "u2"], + "each record must be fetched exactly once; all fetches: {got:?}" + ); + } + + #[test] + fn bam_unmapped_sweep_returns_only_unplaced_records() { + let (header, records) = sweep_world(); + let bam_path = temp_path("sweep.bam"); + { + let mut writer = noodles::bam::io::writer::Builder + .build_from_path(&bam_path) + .unwrap(); + writer.write_header(&header).unwrap(); + for record in &records { + writer.write_alignment_record(&header, record).unwrap(); + } + writer.try_finish().unwrap(); + } + let bai_path = std::path::PathBuf::from(format!("{}.bai", bam_path.display())); + let index = noodles::bam::fs::index(&bam_path).unwrap(); + noodles::bam::bai::fs::write(&bai_path, &index).unwrap(); + + let got = fetch_everything(&bam_path, None); + let _ = std::fs::remove_file(&bam_path); + let _ = std::fs::remove_file(&bai_path); + assert_sweep(&got); + assert_each_record_once(&got); + } + + /// samtools-written CRAMs of the same records (see the fixture README). + #[test] + fn cram_unmapped_sweep_returns_only_unplaced_records() { + let dir = std::path::Path::new("tests/data/unmapped_sweep"); + let fasta = dir.join("sweep.fa"); + + let got = fetch_everything(&dir.join("single_ref_slices.cram"), Some(&fasta)); + assert_sweep(&got); + assert_each_record_once(&got); + + let got = fetch_everything(&dir.join("multi_ref_slice.cram"), Some(&fasta)); + assert_sweep(&got); + assert_each_record_once(&got); + } + #[test] + fn cram_same_reference_multi_slice_container_is_read_once() { + let dir = std::path::Path::new("tests/data/unmapped_sweep"); + let got = fetch_everything( + &dir.join("same_reference_multi_slice.cram"), + Some(&dir.join("sweep.fa")), + ); + let mut names: Vec<_> = got.iter().map(|(_, name)| name.as_str()).collect(); + names.sort_unstable(); + assert_eq!( + names, + ["r0", "r0", "r1", "r1", "u1", "u2"], + "each physical record, including repeated names, must be fetched once: {got:?}" + ); + assert_sweep(&got); + } + #[test] + fn cram_unmapped_sweep_with_no_unplaced_reads_is_empty() { + let dir = std::path::Path::new("tests/data/unmapped_sweep"); + let got = fetch_everything(&dir.join("placed_only.cram"), Some(&dir.join("sweep.fa"))); + let swept: Vec<_> = got + .iter() + .filter(|(target, _)| target == "unmapped") + .collect(); + assert!( + swept.is_empty(), + "no unplaced records should be returned: {got:?}" + ); + let mut names: Vec<_> = got.iter().map(|(_, name)| name.as_str()).collect(); + names.sort_unstable(); + assert_eq!(names, ["r0", "r1", "r2", "r3"]); + } +} diff --git a/src/rna/bam/mod.rs b/src/rna/bam/mod.rs new file mode 100644 index 00000000..9fa72520 --- /dev/null +++ b/src/rna/bam/mod.rs @@ -0,0 +1,38 @@ +//! BAM/SAM/CRAM compatibility layer backed by [noodles](https://crates.io/crates/noodles). +//! +//! This module exposes a rust-htslib-shaped API so the rest of RustQC can read +//! alignment files without linking to htslib, while preserving samtools-identical +//! statistics output. + +mod align_header; +mod align_record; +mod cigar; +mod io; +mod writer; + +pub use align_header::Header; +pub use align_record::{Aux, Record, Seq}; +pub use io::{FetchDefinition, IndexedReader, Reader}; + +/// Trait mirroring `rust_htslib::bam::Read`. +pub use io::Read; + +/// Record sub-module mirroring `rust_htslib::bam::record`. +pub mod record { + pub use super::align_record::{Aux, Record, Seq}; + pub use super::cigar::{Cigar, CigarString, CigarStringView}; +} + +/// Header sub-module mirroring `rust_htslib::bam::header`. +pub mod header { + pub use super::align_header::Header; + pub use super::writer::{HeaderRecord, HeaderView}; +} + +/// BAM index helpers used by integration tests. +pub mod index { + pub use super::writer::index::*; +} + +/// BAM writer helpers used by integration tests. +pub use writer::{Format, Writer}; diff --git a/src/rna/bam/writer.rs b/src/rna/bam/writer.rs new file mode 100644 index 00000000..0532b96c --- /dev/null +++ b/src/rna/bam/writer.rs @@ -0,0 +1,190 @@ +//! BAM writing: split_bam output and test fixtures. + +use std::fs::File; +use std::io; +use std::num::NonZero; +use std::path::{Path, PathBuf}; + +use noodles::bam as noodles_bam; +use noodles::sam as noodles_sam; +use noodles::sam::header::record::value::map::header::{tag, Version}; +use noodles::sam::header::record::value::map::{self, ReferenceSequence}; +use noodles::sam::header::record::value::Map; + +use noodles::sam::alignment::io::Write as AlignmentWrite; + +use super::align_header::Header; +use super::align_record::{record_buf_for_writer, Record}; + +fn parse_sam_version(version: &str) -> Version { + let mut parts = version.split('.'); + let major = parts.next().and_then(|s| s.parse().ok()).unwrap_or(1); + let minor = parts.next().and_then(|s| s.parse().ok()).unwrap_or(6); + Version::new(major, minor) +} + +/// BAM output format. +#[derive(Debug, Clone, Copy)] +pub enum Format { + /// Binary BAM. + Bam, +} + +/// SAM header builder record (rust-htslib-compatible). +#[derive(Debug, Clone)] +pub struct HeaderRecord { + tag: [u8; 2], + fields: Vec<(Vec, String)>, +} + +impl HeaderRecord { + /// Create a new header line builder (`@HD`, `@SQ`, etc.). + pub fn new(tag: &[u8; 2]) -> Self { + Self { + tag: *tag, + fields: Vec::new(), + } + } + + /// Add a `TAG:value` field and return self for chaining. + pub fn push_tag(mut self, tag: &[u8], value: impl Into) -> Self { + self.fields.push((tag.to_vec(), value.into())); + self + } +} + +/// Header view used when parsing SAM lines into records. +#[derive(Debug, Clone)] +pub struct HeaderView { + header: noodles_sam::Header, +} + +impl HeaderView { + /// Build a header view from a RustQC header wrapper. + pub fn from_header(header: &Header) -> Self { + Self { + header: header.noodles_header().clone(), + } + } +} + +/// BAM writer for test fixtures. +pub struct Writer { + inner: noodles_bam::io::Writer>, + header: noodles_sam::Header, +} + +impl Writer { + /// Create a BAM writer at `path`. + pub fn from_path(path: &Path, header: &Header, _format: Format) -> io::Result { + let file = File::create(path)?; + let mut inner = noodles_bam::io::Writer::new(file); + inner.write_header(header.noodles_header())?; + Ok(Self { + inner, + header: header.noodles_header().clone(), + }) + } + + /// Write a BAM record. + pub fn write(&mut self, record: &Record) -> io::Result<()> { + self.inner + .write_alignment_record(&self.header, record_buf_for_writer(record)) + } +} + +impl Header { + /// Append a `@`-prefixed header record. + pub fn push_record(&mut self, record: HeaderRecord) { + let mut inner = self.inner.clone(); + match &record.tag { + b"HD" => { + let mut version = "1.6".to_string(); + let mut sort_order = None; + for (tag, value) in &record.fields { + match &tag[..] { + b"VN" => version = value.clone(), + b"SO" => sort_order = Some(value.clone()), + _ => {} + } + } + let version = parse_sam_version(&version); + let mut hd_builder = Map::::builder().set_version(version); + if let Some(so) = sort_order { + hd_builder = hd_builder.insert(tag::SORT_ORDER, so); + } + let hd = hd_builder.build().expect("valid SAM header map"); + inner = noodles_sam::Header::builder() + .set_header(hd) + .set_reference_sequences(inner.reference_sequences().clone()) + .build(); + } + b"SQ" => { + let mut name = String::new(); + let mut len = 0u64; + for (tag, value) in &record.fields { + match &tag[..] { + b"SN" => name = value.clone(), + b"LN" => len = value.parse().unwrap_or(0), + _ => {} + } + } + if !name.is_empty() { + let mut builder = noodles_sam::Header::builder(); + if let Some(hd) = inner.header().cloned() { + builder = builder.set_header(hd); + } + for (existing_name, map) in inner.reference_sequences() { + builder = builder.add_reference_sequence( + String::from_utf8_lossy(existing_name.as_ref()).as_ref(), + map.clone(), + ); + } + builder = builder.add_reference_sequence( + name.as_str(), + Map::::new(NonZero::new(len.max(1) as usize).unwrap()), + ); + inner = builder.build(); + } + } + _ => {} + } + *self = Header::from_noodles(inner); + } +} + +impl Record { + /// Parse a SAM line into a BAM record. + pub fn from_sam(header: &HeaderView, line: &[u8]) -> io::Result { + let sam_record = noodles_sam::Record::try_from(line)?; + super::align_record::alignment_to_record(&header.header, &sam_record) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) + } +} + +/// BAM index construction (test fixtures). +pub mod index { + use super::*; + + /// Index type (BAI only in tests). + #[derive(Debug, Clone, Copy)] + pub enum Type { + /// BAI index. + Bai, + } + + /// Build a BAI index beside a coordinate-sorted BAM file. + pub fn build( + bam_path: &Path, + index_path: Option<&Path>, + _kind: Type, + _min_shift: u32, + ) -> io::Result<()> { + let index = noodles_bam::fs::index(bam_path)?; + let index_path = index_path.map_or_else( + || PathBuf::from(format!("{}.bai", bam_path.display())), + |p| p.to_path_buf(), + ); + noodles_bam::bai::fs::write(&index_path, &index) + } +} diff --git a/src/rna/bam_flags.rs b/src/rna/bam_flags.rs index 949601a8..050ab4ce 100644 --- a/src/rna/bam_flags.rs +++ b/src/rna/bam_flags.rs @@ -2,6 +2,9 @@ //! //! Centralised definitions so every module uses the same constants. +use crate::rna::bam::record::Aux; +use crate::rna::bam::Record; + /// Read is paired in sequencing (0x1). pub const BAM_FPAIRED: u16 = 0x1; /// Read is mapped in a proper pair (0x2). @@ -36,8 +39,7 @@ pub const BAM_FSUPPLEMENTARY: u16 = 0x800; /// Handles all integer Aux variants (U8, U16, U32, I8, I16, I32) /// and returns the value as `i64`. Returns `None` if the tag is /// absent or has a non-integer type. -pub fn get_aux_int(record: &rust_htslib::bam::Record, tag: &[u8]) -> Option { - use rust_htslib::bam::record::Aux; +pub fn get_aux_int(record: &Record, tag: &[u8]) -> Option { match record.aux(tag) { Ok(Aux::U8(v)) => Some(v as i64), Ok(Aux::U16(v)) => Some(v as i64), diff --git a/src/rna/dupradar/counting.rs b/src/rna/dupradar/counting.rs index fa4e25a6..a0ba0b89 100644 --- a/src/rna/dupradar/counting.rs +++ b/src/rna/dupradar/counting.rs @@ -11,6 +11,7 @@ use crate::gtf::Gene; use crate::io::format_count; +use crate::rna::bam::{self, FetchDefinition, Read as BamRead}; use crate::rna::qualimap::QualimapAccum; use crate::rna::rseqc::accumulators::{RseqcAccumulators, RseqcAnnotations, RseqcConfig}; use crate::Strandedness; @@ -20,7 +21,6 @@ use indexmap::IndexMap; use indicatif::ProgressBar; use log::{debug, warn}; use rayon::prelude::*; -use rust_htslib::bam::{self, FetchDefinition, Read as BamRead}; use std::collections::HashMap; use std::sync::atomic::{AtomicU64, Ordering}; @@ -435,10 +435,10 @@ fn strand_matches( /// * `blocks` - Reusable buffer for aligned blocks (cleared before use) fn cigar_to_aligned_blocks( start: u64, - cigar: &rust_htslib::bam::record::CigarStringView, + cigar: &crate::rna::bam::record::CigarStringView, blocks: &mut Vec<(u64, u64)>, ) { - use rust_htslib::bam::record::Cigar; + use crate::rna::bam::record::Cigar; blocks.clear(); let mut ref_pos = start; @@ -2189,16 +2189,18 @@ mod tests { // --------------------------------------------------------------- struct SamScene { - header: bam::HeaderView, + header: bam::Header, index: HashMap, } fn sam_scene() -> SamScene { let mut header = bam::Header::new(); for name in ["chr1", "chr2"] { - let mut sq = bam::header::HeaderRecord::new(b"SQ"); - sq.push_tag(b"SN", name).push_tag(b"LN", 100_000); - header.push_record(&sq); + header.push_record( + bam::header::HeaderRecord::new(b"SQ") + .push_tag(b"SN", name) + .push_tag(b"LN", "100000"), + ); } let iv = |start: i32, end: i32, gene_idx: GeneIdx| { Interval::new( @@ -2216,10 +2218,7 @@ mod tests { COITree::new(&[iv(1001, 2000, 0), iv(3001, 4000, 1)]), ); index.insert("chr2".to_string(), COITree::new(&[iv(1001, 2000, 2)])); - SamScene { - header: bam::HeaderView::from_header(&header), - index, - } + SamScene { header, index } } /// One 50M SAM line. `mate` is (RNEXT, PNEXT); `tags` e.g. "NH:i:2". @@ -2259,10 +2258,11 @@ mod tests { let mut blocks = Vec::new(); let mut hits = Vec::new(); let mut bio_hits = Vec::new(); + let view = bam::header::HeaderView::from_header(&scene.header); let records: Vec<(String, bam::Record)> = lines .iter() .map(|l| { - let rec = bam::Record::from_sam(&scene.header, l.as_bytes()).unwrap(); + let rec = bam::Record::from_sam(&view, l.as_bytes()).unwrap(); let chrom = String::from_utf8_lossy(scene.header.tid2name(rec.tid() as u32)); (chrom.into_owned(), rec) }) diff --git a/src/rna/mod.rs b/src/rna/mod.rs index 7dbcc094..3ed54540 100644 --- a/src/rna/mod.rs +++ b/src/rna/mod.rs @@ -3,6 +3,7 @@ //! Contains dupRadar duplication rate analysis, featureCounts-compatible output, //! and RSeQC tool reimplementations. +pub mod bam; pub mod bam_flags; pub mod cpp_rng; pub mod dupradar; diff --git a/src/rna/preseq.rs b/src/rna/preseq.rs index 592664b0..98debb85 100644 --- a/src/rna/preseq.rs +++ b/src/rna/preseq.rs @@ -4,9 +4,9 @@ //! sequencing depth using the Good-Toulmin rational function extrapolation //! method, matching the behavior of preseq v3. +use crate::rna::bam; use anyhow::{bail, Context, Result}; use log::debug; -use rust_htslib::bam; use std::collections::HashMap; use std::io::Write; use std::path::Path; @@ -154,7 +154,7 @@ impl PreseqAccum { let tid = record.tid(); let start = record.pos(); - let end = record.cigar().end_pos(); + let end = record.cigar().end_pos() as i64; let info = MateInfo { tid, start, end }; diff --git a/src/rna/qualimap/accumulator.rs b/src/rna/qualimap/accumulator.rs index e8b96ebf..7058b216 100644 --- a/src/rna/qualimap/accumulator.rs +++ b/src/rna/qualimap/accumulator.rs @@ -13,9 +13,9 @@ use std::collections::{HashMap, HashSet}; +use crate::rna::bam; +use crate::rna::bam::record::Cigar; use coitrees::IntervalTree; -use rust_htslib::bam; -use rust_htslib::bam::record::Cigar; use crate::Strandedness; diff --git a/src/rna/rseqc/accumulators.rs b/src/rna/rseqc/accumulators.rs index 1b64c8e8..c6719e1b 100644 --- a/src/rna/rseqc/accumulators.rs +++ b/src/rna/rseqc/accumulators.rs @@ -7,9 +7,9 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use std::hash::{Hash, Hasher}; +use crate::rna::bam; use anyhow::Result; use indexmap::IndexMap; -use rust_htslib::bam; use super::bam_stat::{BamStatResult, GcDepthBin}; use super::flagstat::FlagstatCounts; @@ -530,21 +530,10 @@ impl BamStatAccum { let seq_len = record.seq_len(); if seq_len > 0 { - // SAFETY: We access the raw BAM record data to compute CRC32 - // checksums matching samtools' approach. The pointer arithmetic - // replicates htslib's bam_get_seq() macro: - // data + l_qname + (n_cigar << 2) - // The seq_len > 0 guard above ensures sequence data exists. - // The slice length seq_len.div_ceil(2) matches the BAM spec's - // 4-bit encoded sequence format: (seq_len+1)/2 bytes. - let seq_bytes = unsafe { - let inner = record.inner(); - let data = inner.data; - let seq_offset = - inner.core.l_qname as isize + ((inner.core.n_cigar as isize) << 2); - let seq_nbytes = seq_len.div_ceil(2); - std::slice::from_raw_parts(data.offset(seq_offset), seq_nbytes) - }; + let seq = record.seq(); + let seq_bytes = seq.encoded_bytes(); + let seq_nbytes = seq_len.div_ceil(2); + let seq_bytes = &seq_bytes[..seq_nbytes.min(seq_bytes.len())]; let seq_crc = crc32fast::hash(seq_bytes); self.chk[1] = self.chk[1].wrapping_add(seq_crc); @@ -629,7 +618,7 @@ impl BamStatAccum { let has_splice = record .cigar() .iter() - .any(|op| matches!(op, rust_htslib::bam::record::Cigar::RefSkip(_))); + .any(|op| matches!(op, crate::rna::bam::record::Cigar::RefSkip(_))); if has_splice { self.splice += 1; } else { @@ -650,7 +639,7 @@ impl BamStatAccum { /// Follows `collect_stats` in samtools `stats.c` (1.22.1) with default /// options: no flag filters, no reference, coordinate-sorted input. fn process_stats_read(&mut self, record: &bam::Record, flags: u16, seq_len: usize) { - use rust_htslib::bam::record::Cigar as C; + use crate::rna::bam::record::Cigar as C; let is_primary = flags & BAM_FSUPPLEMENTARY == 0; let is_unmapped = flags & BAM_FUNMAP != 0; @@ -955,12 +944,12 @@ impl BamStatAccum { /// read-oriented cycle (IC) of a mapped, non-secondary record. fn count_indels( &mut self, - cigar: &rust_htslib::bam::record::CigarStringView, + cigar: &crate::rna::bam::record::CigarStringView, is_reverse: bool, order: u8, seq_len: usize, ) { - use rust_htslib::bam::record::Cigar as C; + use crate::rna::bam::record::Cigar as C; let read_len = seq_len as i64; let mut icycle: i64 = 0; @@ -1240,7 +1229,7 @@ impl InferExpAccum { .cigar() .iter() .filter_map(|op| { - use rust_htslib::bam::record::Cigar::*; + use crate::rna::bam::record::Cigar::*; match op { Match(len) | Ins(len) | Equal(len) | Diff(len) => Some(*len as u64), _ => None, @@ -1374,7 +1363,7 @@ fn hash_sequence_encoded(seq: &bam::record::Seq<'_>) -> u128 { /// Hash position key matching RSeQC's `fetch_exon` + position key logic. /// Uses FNV-1a hashing to avoid string allocation per read. fn hash_position_key(chrom: &str, pos: i64, cigar: &bam::record::CigarStringView) -> u64 { - use rust_htslib::bam::record::Cigar; + use crate::rna::bam::record::Cigar; let mut h = crate::io::FNV1A_OFFSET; crate::io::fnv1a_update(&mut h, chrom.as_bytes()); @@ -1960,7 +1949,7 @@ fn compute_qalen_and_intron_size(record: &bam::Record) -> (u64, u64) { let mut qalen: u64 = 0; let mut intron_size: u64 = 0; for op in record.cigar().iter() { - use rust_htslib::bam::record::Cigar::*; + use crate::rna::bam::record::Cigar::*; match op { Match(len) | Equal(len) | Diff(len) => qalen += *len as u64, Ins(len) => qalen += *len as u64, @@ -1980,7 +1969,7 @@ fn fetch_exon_blocks_rseqc(record: &bam::Record) -> Vec<(u64, u64)> { let mut chrom_st = record.pos() as u64; for op in record.cigar().iter() { - use rust_htslib::bam::record::Cigar::*; + use crate::rna::bam::record::Cigar::*; match op { Match(len) => { let start = chrom_st; @@ -2330,9 +2319,9 @@ fn merge_vec_arrays(target: &mut Vec<[u64; N]>, source: Vec<[u64 if source.len() > target.len() { target.resize(source.len(), [0u64; N]); } - for (i, arr) in source.into_iter().enumerate() { - for j in 0..N { - target[i][j] += arr[j]; + for (target_row, source_row) in target.iter_mut().zip(source) { + for (target_count, source_count) in target_row.iter_mut().zip(source_row) { + *target_count += source_count; } } } diff --git a/src/rna/rseqc/bam_stat.rs b/src/rna/rseqc/bam_stat.rs index c72b7505..4e1d22c8 100644 --- a/src/rna/rseqc/bam_stat.rs +++ b/src/rna/rseqc/bam_stat.rs @@ -363,8 +363,8 @@ pub fn write_bam_stat(result: &BamStatResult, output_path: &Path) -> Result<()> #[cfg(test)] mod tests { + use crate::rna::bam::{self, Read as BamRead}; use crate::rna::rseqc::accumulators::BamStatAccum; - use rust_htslib::bam::{self, Read as BamRead}; #[test] fn test_bam_stat_small() { diff --git a/src/rna/rseqc/common.rs b/src/rna/rseqc/common.rs index b5d8902e..59f10c9a 100644 --- a/src/rna/rseqc/common.rs +++ b/src/rna/rseqc/common.rs @@ -27,8 +27,8 @@ use crate::gtf::Gene; /// /// # Returns /// Vector of `(intron_start, intron_end)` tuples (0-based coordinates). -pub fn fetch_introns(start_pos: u64, cigar: &[rust_htslib::bam::record::Cigar]) -> Vec<(u64, u64)> { - use rust_htslib::bam::record::Cigar::*; +pub fn fetch_introns(start_pos: u64, cigar: &[crate::rna::bam::record::Cigar]) -> Vec<(u64, u64)> { + use crate::rna::bam::record::Cigar::*; let mut pos = start_pos; let mut introns = Vec::new(); @@ -208,7 +208,7 @@ mod tests { #[test] fn test_fetch_introns_simple() { - use rust_htslib::bam::record::Cigar::*; + use crate::rna::bam::record::Cigar::*; // 50M500N50M — one intron at position 100+50=150 to 150+500=650 let cigar = vec![Match(50), RefSkip(500), Match(50)]; let introns = fetch_introns(100, &cigar); @@ -218,7 +218,7 @@ mod tests { #[test] fn test_fetch_introns_multiple() { - use rust_htslib::bam::record::Cigar::*; + use crate::rna::bam::record::Cigar::*; // 10M500N20M300N10M — two introns let cigar = vec![Match(10), RefSkip(500), Match(20), RefSkip(300), Match(10)]; let introns = fetch_introns(100, &cigar); @@ -229,7 +229,7 @@ mod tests { #[test] fn test_fetch_introns_with_deletions() { - use rust_htslib::bam::record::Cigar::*; + use crate::rna::bam::record::Cigar::*; // 10M5D10M500N10M let cigar = vec![Match(10), Del(5), Match(10), RefSkip(500), Match(10)]; let introns = fetch_introns(100, &cigar); @@ -239,7 +239,7 @@ mod tests { #[test] fn test_fetch_introns_no_introns() { - use rust_htslib::bam::record::Cigar::*; + use crate::rna::bam::record::Cigar::*; let cigar = vec![Match(100)]; let introns = fetch_introns(100, &cigar); assert!(introns.is_empty()); @@ -247,7 +247,7 @@ mod tests { #[test] fn test_fetch_introns_soft_clip_no_advance() { - use rust_htslib::bam::record::Cigar::*; + use crate::rna::bam::record::Cigar::*; // 5S50M500N50M — soft clip should NOT advance position let cigar = vec![SoftClip(5), Match(50), RefSkip(500), Match(50)]; let introns = fetch_introns(100, &cigar); diff --git a/src/rna/rseqc/flagstat.rs b/src/rna/rseqc/flagstat.rs index 750b2fbb..8735df74 100644 --- a/src/rna/rseqc/flagstat.rs +++ b/src/rna/rseqc/flagstat.rs @@ -210,8 +210,8 @@ fn format_flagstat(s: &FlagstatCounts) -> String { #[cfg(test)] mod tests { use super::*; + use crate::rna::bam::{self, Read as BamRead}; use crate::rna::rseqc::accumulators::BamStatAccum; - use rust_htslib::bam::{self, Read as BamRead}; use std::io::Read; #[test] fn test_flagstat_format() { @@ -420,21 +420,22 @@ mod tests { const PLACEMENTS: [(i32, i32, u8); 3] = [(0, 0, 60), (0, 1, 60), (1, 0, 3)]; fn record(flag: u16, (tid, mtid, mapq): (i32, i32, u8)) -> bam::Record { - use rust_htslib::bam::record::{Cigar, CigarString}; - let mut rec = bam::Record::new(); - rec.set( - b"r", - Some(&CigarString(vec![Cigar::Match(4)])), - b"ACGT", - &[30; 4], + use crate::rna::bam::header::{HeaderRecord, HeaderView}; + let mut header = bam::Header::new(); + for name in ["chr1", "chr2"] { + header.push_record( + HeaderRecord::new(b"SQ") + .push_tag(b"SN", name) + .push_tag(b"LN", "1000"), + ); + } + let chrom = |tid: i32| ["chr1", "chr2"][tid as usize]; + let line = format!( + "r\t{flag}\t{}\t10\t{mapq}\t4M\t{}\t10\t0\tACGT\t????", + chrom(tid), + chrom(mtid) ); - rec.set_flags(flag); - rec.set_tid(tid); - rec.set_pos(9); - rec.set_mtid(mtid); - rec.set_mpos(9); - rec.set_mapq(mapq); - rec + bam::Record::from_sam(&HeaderView::from_header(&header), line.as_bytes()).unwrap() } fn render_flagstat(accum: BamStatAccum, name: &str) -> String { diff --git a/src/rna/rseqc/idxstats.rs b/src/rna/rseqc/idxstats.rs index 93c018fe..de81e02a 100644 --- a/src/rna/rseqc/idxstats.rs +++ b/src/rna/rseqc/idxstats.rs @@ -60,8 +60,8 @@ pub fn write_idxstats( #[cfg(test)] mod tests { use super::*; + use crate::rna::bam::{self, Read as BamRead}; use crate::rna::rseqc::accumulators::BamStatAccum; - use rust_htslib::bam::{self, Read as BamRead}; use std::io::Read; #[test] fn test_idxstats_format() { diff --git a/src/rna/rseqc/read_duplication.rs b/src/rna/rseqc/read_duplication.rs index 005b2ed2..e8491d0a 100644 --- a/src/rna/rseqc/read_duplication.rs +++ b/src/rna/rseqc/read_duplication.rs @@ -156,8 +156,8 @@ fn write_r_script( #[cfg(test)] mod tests { use super::*; + use crate::rna::bam::{self, Read as BamRead}; use log::debug; - use rust_htslib::bam::{self, Read as BamRead}; use std::collections::HashMap; use std::time::Instant; @@ -166,7 +166,7 @@ mod tests { /// Constructs `{chrom}:{start}:{exon1_start}-{exon1_end}:{exon2_start}-{exon2_end}:...` /// matching RSeQC's `fetch_exon` + position key logic. fn build_position_key(chrom: &str, pos: i64, cigar: &bam::record::CigarStringView) -> String { - use rust_htslib::bam::record::Cigar; + use crate::rna::bam::record::Cigar; let mut key = format!("{}:{}:", chrom, pos); let mut ref_pos = pos; @@ -218,8 +218,9 @@ mod tests { let mut pos_dup: HashMap = HashMap::new(); let mut total_processed = 0u64; - for result in bam.records() { - let record = result.context("Failed to read BAM record")?; + let mut record = bam::Record::new(); + while let Some(result) = bam.read(&mut record) { + result.context("Failed to read BAM record")?; if record.is_unmapped() || record.is_quality_check_failed() || record.mapq() < mapq_cut { @@ -274,8 +275,8 @@ mod tests { #[test] fn test_build_position_key_simple() { - use rust_htslib::bam::record::Cigar; - use rust_htslib::bam::record::{CigarString, CigarStringView}; + use crate::rna::bam::record::Cigar; + use crate::rna::bam::record::{CigarString, CigarStringView}; let cigar_ops = vec![Cigar::Match(50)]; let cigar_string = CigarString(cigar_ops); @@ -287,8 +288,8 @@ mod tests { #[test] fn test_build_position_key_spliced() { - use rust_htslib::bam::record::Cigar; - use rust_htslib::bam::record::{CigarString, CigarStringView}; + use crate::rna::bam::record::Cigar; + use crate::rna::bam::record::{CigarString, CigarStringView}; let cigar_ops = vec![Cigar::Match(10), Cigar::RefSkip(500), Cigar::Match(20)]; let cigar_string = CigarString(cigar_ops); diff --git a/src/rna/rseqc/split_bam.rs b/src/rna/rseqc/split_bam.rs index 54a54b21..948f70f4 100644 --- a/src/rna/rseqc/split_bam.rs +++ b/src/rna/rseqc/split_bam.rs @@ -8,9 +8,9 @@ use std::collections::HashMap; use std::io::Write; use std::path::Path; +use crate::rna::bam::{self, Read as BamRead}; use anyhow::{bail, ensure, Context, Result}; use log::debug; -use rust_htslib::bam::{self, Read as BamRead}; use crate::rna::bam_flags::{BAM_FMUNMAP, BAM_FQCFAIL, BAM_FUNMAP}; @@ -380,35 +380,22 @@ pub fn write_split_bams( .set_reference(ref_path) .with_context(|| format!("Failed to set reference FASTA: {ref_path}"))?; } - let pool = if threads > 1 { - let pool = rust_htslib::tpool::ThreadPool::new(threads as u32) - .context("Failed to create htslib thread pool")?; - reader - .set_thread_pool(&pool) - .context("Failed to attach thread pool to reader")?; - Some(pool) - } else { - None - }; + reader + .set_threads(threads) + .context("Failed to set decompression threads")?; - let header_view = reader.header().clone(); - let target_names: Vec = (0..header_view.target_count()) - .map(|tid| String::from_utf8_lossy(header_view.tid2name(tid)).into_owned()) + let header = reader.header().clone(); + let target_names: Vec = (0..header.target_count()) + .map(|tid| String::from_utf8_lossy(header.tid2name(tid)).into_owned()) .collect(); let lookup = regions.lookup_for_targets(&target_names); - let header = bam::Header::from_template(&header_view); let prefix = prefix.to_string_lossy(); let open = |suffix: &str| -> Result { let path = format!("{prefix}.{suffix}.bam"); - let mut writer = bam::Writer::from_path(&path, &header, bam::Format::Bam) - .with_context(|| format!("Failed to create {path}"))?; - if let Some(ref pool) = pool { - writer - .set_thread_pool(pool) - .context("Failed to attach thread pool to writer")?; - } - Ok(writer) + // ponytail: single-threaded BGZF compression; use noodles' multithreaded bgzf writer if this pass gets slow + bam::Writer::from_path(Path::new(&path), &header, bam::Format::Bam) + .with_context(|| format!("Failed to create {path}")) }; let mut in_writer = open("in")?; let mut ex_writer = open("ex")?; @@ -535,7 +522,13 @@ mod tests { let sam = format!("@HD\tVN:1.6\n@SQ\tSN:chr1\tLN:20000\n@SQ\tSN:chr2\tLN:20000\n{body}"); let path = temp_file(name, &sam); let mut reader = bam::Reader::from_path(&path).unwrap(); - reader.records().map(|r| r.unwrap()).collect() + let mut records = Vec::new(); + let mut record = bam::Record::new(); + while let Some(result) = reader.read(&mut record) { + result.unwrap(); + records.push(record.clone()); + } + records } #[test] diff --git a/src/rna/rseqc/stats.rs b/src/rna/rseqc/stats.rs index 406d892c..17155326 100644 --- a/src/rna/rseqc/stats.rs +++ b/src/rna/rseqc/stats.rs @@ -538,13 +538,13 @@ fn write_gcc( for cycle in 0..max_cycles { let mut combined = [0u64; 6]; if cycle < fbc.len() { - for j in 0..6 { - combined[j] += fbc[cycle][j]; + for (count, &value) in combined.iter_mut().zip(&fbc[cycle]) { + *count += value; } } if cycle < lbc.len() { - for j in 0..6 { - combined[j] += lbc[cycle][j]; + for (count, &value) in combined.iter_mut().zip(&lbc[cycle]) { + *count += value; } } // Denominator is A+C+G+T only (first 4 elements), matching upstream @@ -948,8 +948,8 @@ fn write_gc_depth( #[cfg(test)] mod tests { use super::*; + use crate::rna::bam::{self, Read as BamRead}; use crate::rna::rseqc::accumulators::BamStatAccum; - use rust_htslib::bam::{self, Read as BamRead}; use std::io::Read; #[test] fn test_stats_sn_format() { diff --git a/src/rna/rseqc/tin.rs b/src/rna/rseqc/tin.rs index c20b3c04..6a3fa458 100644 --- a/src/rna/rseqc/tin.rs +++ b/src/rna/rseqc/tin.rs @@ -4,7 +4,7 @@ //! uniformity across sampled exonic positions. Reimplementation of //! RSeQC's `tin.py` tool. -use rust_htslib::bam; +use crate::rna::bam; use std::cmp::Reverse; use std::collections::{BTreeMap, BinaryHeap, HashMap, HashSet}; use std::hash::{BuildHasher, Hasher}; @@ -1320,8 +1320,8 @@ impl TinAccum { }, &mut MateView { pos: record.pos(), - cigar: record.raw_cigar(), - seq: record.seq().encoded, + cigar: &record.raw_cigar(), + seq: record.seq().encoded_bytes(), qual: &mut b_qual, }, qname, @@ -1361,8 +1361,8 @@ impl TinAccum { if store { if let Some(last) = group.recs.last_mut() { last.data = Some(Box::new(MateData { - cigar: record.raw_cigar().to_vec(), - seq: record.seq().encoded.to_vec(), + cigar: record.raw_cigar(), + seq: record.seq().encoded_bytes().to_vec(), qual: quals.to_vec(), bases: self.covered_buf.clone(), })); @@ -1502,7 +1502,7 @@ struct AlignedBlock { /// The reference end of the alignment (0-based, exclusive), including /// deletions and skipped regions. fn fill_aligned_blocks(record: &bam::Record, buf: &mut Vec) -> u64 { - use rust_htslib::bam::record::Cigar; + use crate::rna::bam::record::Cigar; buf.clear(); let mut pos = record.pos().max(0) as u64; diff --git a/tests/data/unmapped_sweep/README.md b/tests/data/unmapped_sweep/README.md new file mode 100644 index 00000000..e63fdf6d --- /dev/null +++ b/tests/data/unmapped_sweep/README.md @@ -0,0 +1,30 @@ +# Unmapped-sweep CRAM fixtures + +`sweep.sam` has two mapped reads on chr1, a mapped read on chr2 with its unmapped mate placed at the same position (flag 0x85, tid 1), and two unplaced reads (no reference). The CRAMs are that file written by samtools 1.22.1 against `sweep.fa`: + +```bash +samtools view -C -T sweep.fa -o single_ref_slices.cram sweep.sam +samtools view -C -T sweep.fa --output-fmt-option multi_seq_per_slice=1 -o multi_ref_slice.cram sweep.sam +samtools index single_ref_slices.cram +samtools index multi_ref_slice.cram +``` + +`single_ref_slices.cram` has one slice per reference plus one for the unplaced reads; `multi_ref_slice.cram` holds all six records in one multi-reference slice, so its index points the unplaced-read entry at a slice that also holds placed records. + +`same_reference_multi_slice.cram` contains one chr1 container with two slices plus the unplaced-read container. Both chr1 slices hold r0 and r1, deliberately retaining repeated names as distinct physical records. Its CRAI has two chr1 entries at the same container offset. Regenerate with: + +```bash +python3 make_multi_slice.py +samtools index same_reference_multi_slice.cram +samtools quickcheck -v same_reference_multi_slice.cram +samtools view -T sweep.fa same_reference_multi_slice.cram +``` + +The generator reuses the original fixture's encoded slices, updates the second slice's record counter and the container's counts, landmarks, size and CRC. It omits the chr2 container, keeping the existing unplaced container's record counter correct. Samtools 1.22.1 decodes six records: r0, r1, r0, r1, u1, u2. Record-level or read-name deduplication would incorrectly discard two legitimate records. + +`placed_only.sam` drops the two unplaced reads from `sweep.sam`. It pins the empty-unplaced-sweep case; regenerate with samtools 1.22.1: + +```bash +samtools view --no-PG -C -T sweep.fa -o placed_only.cram placed_only.sam +samtools index placed_only.cram +``` diff --git a/tests/data/unmapped_sweep/make_multi_slice.py b/tests/data/unmapped_sweep/make_multi_slice.py new file mode 100644 index 00000000..579d284d --- /dev/null +++ b/tests/data/unmapped_sweep/make_multi_slice.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""Make a two-slice CRAM container from the checked-in single-slice fixture.""" +import gzip +from pathlib import Path +import struct +import zlib + + +def read_itf8(data, position): + first = data[position] + size = next((n for n in range(1, 5) if first < (0x100 - (0x80 >> (n - 1)))), 5) + if size == 5: + value = ((first & 15) << 28) | (data[position + 1] << 20) | (data[position + 2] << 12) | (data[position + 3] << 4) | (data[position + 4] & 15) + else: + value = first & (0xff >> size) + for byte in data[position + 1:position + size]: + value = (value << 8) | byte + return value, position + size + + +def itf8(value): + value &= 0xffffffff + for size in range(1, 5): + if value < (1 << (7 * size)): + encoded = bytearray(value.to_bytes(size, 'big')) + encoded[0] |= (0xff << (9 - size)) & 0xff + return bytes(encoded) + return bytes([0xf0 | (value >> 28), (value >> 20) & 255, (value >> 12) & 255, (value >> 4) & 255, value & 15]) + + +def read_ltf8(data, position): + first = data[position] + leading = 0 + while leading < 8 and first & (0x80 >> leading): + leading += 1 + value = first & (0x7f >> leading) + for byte in data[position + 1:position + leading + 1]: + value = (value << 8) | byte + return value, position + leading + 1 + + +def ltf8(value): + if value < 128: + return bytes([value]) + raise ValueError('This fixture only needs small record counters') + + +def container(data, offset): + length = struct.unpack_from('chr1 +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +>chr2 +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA diff --git a/tests/data/unmapped_sweep/sweep.sam b/tests/data/unmapped_sweep/sweep.sam new file mode 100644 index 00000000..2c86967e --- /dev/null +++ b/tests/data/unmapped_sweep/sweep.sam @@ -0,0 +1,9 @@ +@HD VN:1.6 SO:coordinate +@SQ SN:chr1 LN:1000 +@SQ SN:chr2 LN:1000 +r0 0 chr1 101 60 4M * 0 0 AAAA IIII +r1 0 chr1 201 60 4M * 0 0 AAAA IIII +r2 73 chr2 901 60 4M = 901 0 AAAA IIII +r3 133 chr2 901 0 * = 901 0 AAAA IIII +u1 4 * 0 0 * * 0 0 AAAA IIII +u2 4 * 0 0 * * 0 0 AAAA IIII diff --git a/tests/integration_test.rs b/tests/integration_test.rs index d7743028..1819e018 100644 --- a/tests/integration_test.rs +++ b/tests/integration_test.rs @@ -9,8 +9,8 @@ use std::path::PathBuf; use std::process::Command; use std::time::{SystemTime, UNIX_EPOCH}; -use rust_htslib::bam; -use rust_htslib::bam::header::HeaderRecord; +use rustqc::rna::bam; +use rustqc::rna::bam::header::{HeaderRecord, HeaderView}; /// Helper: get the path to the rustqc binary. /// @@ -116,11 +116,11 @@ fn write_bam_fixture(path: &Path, chroms: &[(&str, u64)], sam_lines: &[&str]) { header.push_record( HeaderRecord::new(b"SQ") .push_tag(b"SN", *chrom) - .push_tag(b"LN", *len as i64), + .push_tag(b"LN", len.to_string()), ); } - let header_view = bam::HeaderView::from_header(&header); + let header_view = HeaderView::from_header(&header); let mut writer = bam::Writer::from_path(path, &header, bam::Format::Bam).unwrap(); for line in sam_lines { let record = bam::Record::from_sam(&header_view, line.as_bytes()).unwrap(); @@ -1047,12 +1047,17 @@ fn run_split_bam(outdir: &Path, extra: &[&str]) -> std::process::Output { } /// Read a BAM's header text and all records. -fn read_bam(path: &Path) -> (Vec, Vec) { - use rust_htslib::bam::Read; +fn read_bam(path: &Path) -> (noodles::sam::Header, Vec) { + use rustqc::rna::bam::Read; let mut reader = bam::Reader::from_path(path) .unwrap_or_else(|e| panic!("cannot open {}: {e}", path.display())); - let header = reader.header().as_bytes().to_vec(); - let records = reader.records().map(|r| r.unwrap()).collect(); + let header = reader.header().noodles_header().clone(); + let mut records = Vec::new(); + let mut record = bam::Record::new(); + while let Some(result) = reader.read(&mut record) { + result.unwrap(); + records.push(record.clone()); + } (header, records) } @@ -1448,3 +1453,238 @@ fn test_samtools_flagstat_and_stats_match_on_every_flag() { let _ = fs::remove_dir_all(root); } } + +// =================================================================== +// Unmapped sweep on the parallel path +// =================================================================== + +/// A placed unmapped mate (0x4 with a reference) in the last reference's final +/// 16 kb, plus two unplaced reads. The parallel path's unmapped sweep must not +/// count the placed mate a second time. Expected text is `samtools flagstat` +/// 1.22.1 output for this input. +#[test] +fn test_parallel_unmapped_sweep_counts_placed_unmapped_mate_once() { + let expected = "\ +6 + 0 in total (QC-passed reads + QC-failed reads) +6 + 0 primary +0 + 0 secondary +0 + 0 supplementary +0 + 0 duplicates +0 + 0 primary duplicates +3 + 0 mapped (50.00% : N/A) +3 + 0 primary mapped (50.00% : N/A) +2 + 0 paired in sequencing +1 + 0 read1 +1 + 0 read2 +0 + 0 properly paired (0.00% : N/A) +0 + 0 with itself and mate mapped +1 + 0 singletons (50.00% : N/A) +0 + 0 with mate mapped to a different chr +0 + 0 with mate mapped to a different chr (mapQ>=5) +"; + let seq = "ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTAC"; + let qual = "??????????????????????????????????????????????????"; + let lines: Vec = [ + "r0\t0\tchr1\t1001\t60\t50M\t*\t0\t0", + "r1\t0\tchr1\t1201\t60\t50M\t*\t0\t0", + "r2\t73\tchr2\t99001\t60\t50M\t=\t99001\t0", + "r3\t133\tchr2\t99001\t0\t*\t=\t99001\t0", + "u1\t4\t*\t0\t0\t*\t*\t0\t0", + "u2\t4\t*\t0\t0\t*\t*\t0\t0", + ] + .iter() + .map(|fields| format!("{fields}\t{seq}\t{qual}")) + .collect(); + let lines: Vec<&str> = lines.iter().map(String::as_str).collect(); + + for threads in [1, 4] { + let root = unique_test_dir(&format!("unmapped-sweep-t{threads}")); + let bam_path = root.join("s.bam"); + let gtf_path = root.join("a.gtf"); + let outdir = root.join("out"); + fs::create_dir_all(&outdir).unwrap(); + fs::write( + >f_path, + "chr1\tt\tgene\t900\t3000\t.\t+\t.\tgene_id \"g1\"; gene_name \"g1\";\n\ + chr1\tt\texon\t900\t3000\t.\t+\t.\tgene_id \"g1\"; transcript_id \"t1\"; exon_number \"1\";\n", + ) + .unwrap(); + write_bam_fixture(&bam_path, &[("chr1", 100_000), ("chr2", 100_000)], &lines); + + let output = run_rustqc_custom(&outdir, &bam_path, >f_path, threads, true, &[]); + assert!( + output.status.success(), + "rustqc failed with --threads {threads}:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + let flagstat = fs::read_to_string(outdir.join("samtools/s.flagstat")).unwrap(); + assert_eq!(flagstat, expected, "flagstat with --threads {threads}"); + let _ = fs::remove_dir_all(root); + } +} + +/// The same records as a samtools-written CRAM holding all of them in one +/// multi-reference slice: each per-reference fetch on the parallel path must +/// return only its own reference's records. Expected text is `samtools +/// flagstat` 1.22.1 output for this file. +#[test] +fn test_parallel_cram_multi_reference_slice_counts_each_record_once() { + let expected = "\ +6 + 0 in total (QC-passed reads + QC-failed reads) +6 + 0 primary +0 + 0 secondary +0 + 0 supplementary +0 + 0 duplicates +0 + 0 primary duplicates +3 + 0 mapped (50.00% : N/A) +3 + 0 primary mapped (50.00% : N/A) +2 + 0 paired in sequencing +1 + 0 read1 +1 + 0 read2 +0 + 0 properly paired (0.00% : N/A) +0 + 0 with itself and mate mapped +1 + 0 singletons (50.00% : N/A) +0 + 0 with mate mapped to a different chr +0 + 0 with mate mapped to a different chr (mapQ>=5) +"; + let data = Path::new("tests/data/unmapped_sweep"); + for threads in [1, 4] { + let root = unique_test_dir(&format!("cram-multi-ref-t{threads}")); + let gtf_path = root.join("a.gtf"); + let outdir = root.join("out"); + fs::create_dir_all(&outdir).unwrap(); + fs::write( + >f_path, + "chr1\tt\tgene\t1\t1000\t.\t+\t.\tgene_id \"g1\"; gene_name \"g1\";\n\ + chr1\tt\texon\t1\t1000\t.\t+\t.\tgene_id \"g1\"; transcript_id \"t1\"; exon_number \"1\";\n", + ) + .unwrap(); + + let output = Command::new(rustqc_binary()) + .args(["rna", "--skip-dup-check", "--threads", &threads.to_string()]) + .arg("--reference") + .arg(data.join("sweep.fa")) + .arg("--gtf") + .arg(>f_path) + .arg("--outdir") + .arg(&outdir) + .arg(data.join("multi_ref_slice.cram")) + .output() + .expect("Failed to execute rustqc"); + assert!( + output.status.success(), + "rustqc failed with --threads {threads}:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + let flagstat = + fs::read_to_string(outdir.join("samtools/multi_ref_slice.flagstat")).unwrap(); + assert_eq!(flagstat, expected, "flagstat with --threads {threads}"); + let _ = fs::remove_dir_all(root); + } +} + +/// Multiple CRAI slice entries for one reference/container must not duplicate reads. +#[test] +fn test_parallel_cram_same_reference_multi_slice_counts_each_record_once() { + let expected = "\ +6 + 0 in total (QC-passed reads + QC-failed reads) +6 + 0 primary +0 + 0 secondary +0 + 0 supplementary +0 + 0 duplicates +0 + 0 primary duplicates +4 + 0 mapped (66.67% : N/A) +4 + 0 primary mapped (66.67% : N/A) +0 + 0 paired in sequencing +0 + 0 read1 +0 + 0 read2 +0 + 0 properly paired (N/A : N/A) +0 + 0 with itself and mate mapped +0 + 0 singletons (N/A : N/A) +0 + 0 with mate mapped to a different chr +0 + 0 with mate mapped to a different chr (mapQ>=5) +"; + let data = Path::new("tests/data/unmapped_sweep"); + for threads in [1, 4] { + let root = unique_test_dir(&format!("cram-same-reference-multi-slice-t{threads}")); + let gtf_path = root.join("a.gtf"); + let outdir = root.join("out"); + fs::write(>f_path, + "chr1\tt\tgene\t1\t1000\t.\t+\t.\tgene_id \"g1\"; gene_name \"g1\";\n\ + chr1\tt\texon\t1\t1000\t.\t+\t.\tgene_id \"g1\"; transcript_id \"t1\"; exon_number \"1\";\n" + ).unwrap(); + let output = Command::new(rustqc_binary()) + .args(["rna", "--skip-dup-check", "--threads", &threads.to_string()]) + .arg("--reference") + .arg(data.join("sweep.fa")) + .arg("--gtf") + .arg(>f_path) + .arg("--outdir") + .arg(&outdir) + .arg(data.join("same_reference_multi_slice.cram")) + .output() + .expect("Failed to execute rustqc"); + assert!( + output.status.success(), + "rustqc failed with --threads {threads}:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + let flagstat = + fs::read_to_string(outdir.join("samtools/same_reference_multi_slice.flagstat")) + .unwrap(); + assert_eq!(flagstat, expected, "flagstat with --threads {threads}"); + fs::remove_dir_all(root).unwrap(); + } +} + +/// A CRAM with no unplaced records must succeed on the parallel sweep path too. +#[test] +fn test_parallel_cram_with_no_unplaced_reads() { + let expected = "\ +4 + 0 in total (QC-passed reads + QC-failed reads) +4 + 0 primary +0 + 0 secondary +0 + 0 supplementary +0 + 0 duplicates +0 + 0 primary duplicates +3 + 0 mapped (75.00% : N/A) +3 + 0 primary mapped (75.00% : N/A) +2 + 0 paired in sequencing +1 + 0 read1 +1 + 0 read2 +0 + 0 properly paired (0.00% : N/A) +0 + 0 with itself and mate mapped +1 + 0 singletons (50.00% : N/A) +0 + 0 with mate mapped to a different chr +0 + 0 with mate mapped to a different chr (mapQ>=5) +"; + let data = Path::new("tests/data/unmapped_sweep"); + for threads in [1, 4] { + let root = unique_test_dir(&format!("cram-no-unplaced-t{threads}")); + let gtf_path = root.join("a.gtf"); + let outdir = root.join("out"); + fs::write(>f_path, + "chr1\tt\tgene\t1\t1000\t.\t+\t.\tgene_id \"g1\"; gene_name \"g1\";\n\ + chr1\tt\texon\t1\t1000\t.\t+\t.\tgene_id \"g1\"; transcript_id \"t1\"; exon_number \"1\";\n" + ).unwrap(); + let output = Command::new(rustqc_binary()) + .args(["rna", "--skip-dup-check", "--threads", &threads.to_string()]) + .arg("--reference") + .arg(data.join("sweep.fa")) + .arg("--gtf") + .arg(>f_path) + .arg("--outdir") + .arg(&outdir) + .arg(data.join("placed_only.cram")) + .output() + .expect("Failed to execute rustqc"); + assert!( + output.status.success(), + "rustqc failed with --threads {threads}:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + let flagstat = fs::read_to_string(outdir.join("samtools/placed_only.flagstat")).unwrap(); + assert_eq!(flagstat, expected, "flagstat with --threads {threads}"); + fs::remove_dir_all(root).unwrap(); + } +}