Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow specifying reference FASTA #684

Merged
merged 24 commits into from
Feb 17, 2025
Merged

feat: allow specifying reference FASTA #684

merged 24 commits into from
Feb 17, 2025

Conversation

tedil
Copy link
Contributor

@tedil tedil commented Feb 13, 2025

To properly shift genomic variants in the 3' direction as enforced by HGVS nomenclature, reference sequences have to be available. This is especially important for variants close to / crossing / shuffled towards intron/exon boundaries (about ~40k in clinvar VCF), as otherwise the hgvs descriptions will be incorrect.
Therefore, users can now optionally specify a genomic reference FASTA file via --reference.
Right now, we read the reference sequences into memory completely, which requires ~3GB of memory for a standard human reference genome.
TODO:

  • reading on-demand from FASTA + FAI
  • reading on-demand from FASTA.BGZ + FAI/GZI (postponed)
  • explore caching only 1 contig at a time, which would be fine for sorted VCFs
  • translate accessions between reference FASTA ←→ RefSeq accessions

Summary by CodeRabbit

  • New Features
    • Added command-line options to specify a reference genome file and choose in-memory processing, enabling more flexible annotation setups.
    • Introduced enhanced reference sequence handling to streamline and improve variant interpretation.
  • Refactor
    • Simplified internal mapping logic for consequence prediction, resulting in improved performance and adaptability.
    • Updated configuration processes to dynamically reflect the availability of reference data for more accurate results.
    • Improved the construction of the ConsequencePredictor for better initialization efficiency.

Copy link
Contributor

coderabbitai bot commented Feb 13, 2025

Warning

Rate limit exceeded

@tedil has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 9 minutes and 5 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between df869d7 and 88caabb.

📒 Files selected for processing (1)
  • src/annotate/seqvars/reference.rs (1 hunks)

Walkthrough

This pull request updates dependencies and integrates new features to support reference genome handling in the annotation process. It modifies dependency versions in the package manifest, refactors mapping logic in consequence predictors, adds support for providing a reference genome (with an option for in-memory loading), and updates command-line argument parsing. A new module for FASTA reference reading has also been introduced, affecting various modules in the annotator and provider.

Changes

Files Summary
Cargo.toml Updated dependency version: hgvs from "0.17.5" to "0.18.0"; added new dependency memmap2 version "0.9.5".
src/annotate/seqvars/csq.rs and src/annotate/strucvars/csq.rs Refactored mapping construction in ConsequencePredictor by replacing manual logic with a call to provider.build_chrom_to_acc, and updated internal logic and tests to reflect new provider initialization.
src/annotate/seqvars/mod.rs, src/annotate/seqvars/provider.rs, and src/annotate/seqvars/reference.rs Integrated reference genome support: added new fields and parameters (such as reference and in_memory_reference), introduced the ReferenceReader trait with implementations for in-memory and indexed FASTA access, and updated provider initialization to build chromosome-accession mappings accordingly.
src/server/run/mod.rs and src/verify/seqvars.rs Extended command-line interface by adding new options (reference and in_memory_reference) to allow users to specify and control reference genome usage, with associated modifications to downstream annotator and provider initialization.

Sequence Diagram(s)

sequenceDiagram
  participant CLI as Command Line
  participant Server as Server Runner
  participant Annotator as ConsequenceAnnotator
  participant Provider as MehariProvider
  participant RefReader as ReferenceReader

  CLI->>Server: Pass arguments (reference, in_memory_reference)
  Server->>Annotator: setup_seqvars_annotator(reference, in_memory_reference)
  Annotator->>Provider: Initialize provider(new reference parameters)
  Provider->>RefReader: Initialize ReferenceReader (if reference provided)
  RefReader-->>Provider: Return reference access handle
  Provider-->>Annotator: Return configured provider
  Annotator-->>Server: Annotator ready
Loading

Suggested reviewers

  • holtgrewe

Poem

I'm a bouncy rabbit, quick on my feet,
Spreading fresh changes with a cheerful beat.
New references and maps, like carrots in a row,
In every little module, vibrant features grow.
With code that hops ahead, I cheer with delight!
Happy coding under the starlit night.
🥕🐇


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@tedil tedil marked this pull request as ready for review February 17, 2025 12:59
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (15)
src/annotate/seqvars/reference.rs (3)

1-15: Consider avoiding .expect() for production-grade code.

While using .expect("Failed to...") is acceptable for rapid prototyping, returning an error instead of panicking is often preferable for robust libraries and applications. This approach will allow upstream error handling and avoid abrupt terminations on recoverable failures.

- let reference_reader = bio::io::fasta::Reader::from_file(&reference_path)
-     .expect("Failed to create FASTA reader");
+ let reference_reader = bio::io::fasta::Reader::from_file(&reference_path)
+     .map_err(|e| anyhow!("Failed to create FASTA reader: {}", e))?;

17-36: Use a more descriptive error on read failures.

Currently, the code uses .expect("Failed to read FASTA record"), which can cause a panic. A better practice is to collect the error and return via ?, preserving the original cause and improving debuggability.

- let record = r.expect("Failed to read FASTA record");
+ let record = r.map_err(|e| anyhow!("Error reading FASTA record: {}", e))?;

58-96: Return errors instead of panics for file operations.

In from_path(), certain checks rely on expect. Swapping those out for graceful error handling will make the code more resilient and user-friendly. This ensures an I/O error does not crash the entire application.

src/annotate/seqvars/provider.rs (7)

27-30: Consolidate import statements for clarity.

These imports appear in consecutive lines. Consider grouping them into a single block or reusing existing blocks if your style guidelines allow it, to keep the module more organized.


183-192: Document the new fields.

reference_reader, chrom_to_acc, and acc_to_chrom are added. Add doc comments explaining their intended usage (on-demand reference retrieval, chromosome-accession mapping) for future maintainers.


305-314: Watch out for large memory usage.

Loading large references in memory (line 311) can lead to high memory usage. This might be addressed in future tasks (like on-demand reading). For now, consider adding a warning in the docs or logs when using InMemoryFastaAccess.


334-449: Transcript picking logic.

The picked-genes approach is thorough. However, keep an eye on performance if the gene list grows very large. A small micro-optimization might include short-circuiting once you find a suitable pick in TranscriptPickMode::First.


525-529: Consider caching the built chromosome-to-acc map.

If build_chrom_to_acc() is repeatedly called, it might be beneficial to cache the result. If it’s only called once, the current approach is fine.


543-545: Publicly exposing _get_assembly_map might improve composability.

Having a single place where assembly data is retrieved fosters consistency. If there's potential reuse in other modules, re-export or rename _get_assembly_map to reflect a more general usage.


887-894: Assembly map building.

This function is essential for capturing sequence name mappings. The usage of IndexMap for preserving insertion order is a nice touch if order matters, otherwise a regular HashMap may suffice.

src/server/run/mod.rs (1)

119-126: Optional reference and in-memory flag.

These added CLI options look good. #[arg(long, requires = "reference")] ensures correctness if in_memory_reference is set. Just make sure help messages highlight the memory impact of loading a large reference.

src/verify/seqvars.rs (3)

36-38: Improve field documentation for memory implications.

The in_memory_reference field should include documentation about memory requirements, especially since loading a human reference genome requires approximately 3GB of memory.

 /// Read the reference genome into memory.
+/// Note: Loading a human reference genome requires approximately 3GB of memory.
 #[arg(long, requires = "reference")]
 pub in_memory_reference: bool,

149-150: Remove commented out code.

This commented out code is no longer needed and should be removed to maintain code cleanliness.

-    // let reference = noodles::fasta::io::indexed_reader::Builder::default()
-    //     .build_from_path(&args.path_reference_fasta)?;

134-137: Enhance error message for FASTA file opening.

The error message could be more specific about potential issues when opening the reference FASTA file.

     tracing::info!(
-        "Opening reference FASTA file: {}",
+        "Opening reference FASTA file (requires FAI index): {}",
         &args.path_reference_fasta
     );
src/annotate/seqvars/csq.rs (1)

1251-1255: Add test cases for reference FASTA handling.

Consider adding test cases that verify the behavior with and without a reference FASTA file.

Add test cases like:

#[test]
fn test_with_reference_fasta() {
    // Test prediction with reference FASTA
}

#[test]
fn test_without_reference_fasta() {
    // Test prediction without reference FASTA
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8f11ae4 and c564d72.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (8)
  • Cargo.toml (2 hunks)
  • src/annotate/seqvars/csq.rs (10 hunks)
  • src/annotate/seqvars/mod.rs (15 hunks)
  • src/annotate/seqvars/provider.rs (10 hunks)
  • src/annotate/seqvars/reference.rs (1 hunks)
  • src/annotate/strucvars/csq.rs (1 hunks)
  • src/server/run/mod.rs (3 hunks)
  • src/verify/seqvars.rs (4 hunks)
🔇 Additional comments (19)
src/annotate/seqvars/provider.rs (10)

4-6: Imports look consistent.
No issues found. The addition of reference-related modules seems correct.


199-202: Enum usage is appropriate.
This approach of wrapping each struct variant is a clean way to unify multiple implementations under one trait object.


204-216: Consistent trait forwarding is good.

Allowing ReferenceReaderImpl to proxy calls to either InMemoryFastaAccess or UnbufferedIndexedFastaAccess is a tidy design. No immediate issues.


240-245: Support for optional reference is handled well.

The new parameters for the Provider::new() method gracefully handle both in-memory and unbuffered reference usage. Nicely done.


287-287: Ensure all impacted code paths honor this new picking logic.

Whenever picked_gene_to_tx_map is used, confirm that you do not inadvertently override or skip references if new transcript picks are required. This new logic looks fine but double-check usage in downstream code.


316-318: Chromosome-accession mapping is a great addition.

This mapping will help unify the naming conventions. No direct issues found.


521-523: Getter is straightforward.
No concerns regarding reference_available(), as it cleanly checks presence of reference_reader.


572-587: Reference-based retrieval logic.

The fallback to reference_reader is sound for “NC|NT|NW” accessions. Verify that partial range requests for these reference sequences are validated. A quick boundary check prior to line 583 would avoid empty or out-of-bounds slices.


588-611: Transcript-based fallback logic is clear.

Using transcript DB if the reference is not available is sensible. Just ensure the fallback performs well for large queries, especially in server scenarios.
[approve]


896-908: chrom → acc mapping extension.

Appending both “chrX” and “X” keys fosters robust queries. Potentially watch out for collisions if non-standard contigs are present (e.g., “chrUn”). Using a fallback for unknown contigs might help.

src/server/run/mod.rs (1)

17-17: Import PathBuf is consistent with usage.
No issues identified.

src/annotate/strucvars/csq.rs (1)

454-454: LGTM! Improved code maintainability.

The change to use provider.build_chrom_to_acc encapsulates the chromosome-to-accession mapping logic, making the code more maintainable.

src/annotate/seqvars/csq.rs (1)

88-96: LGTM! Improved mapper configuration based on reference availability.

The mapper configuration is now properly set based on reference availability, which is crucial for accurate HGVS nomenclature.

src/annotate/seqvars/mod.rs (4)

62-62: LGTM!

The new reference module is appropriately scoped and named.


85-91: LGTM!

The new fields are well-documented and properly constrained. The requires attribute ensures correct usage of the in-memory option.


1834-1839: LGTM!

The function signature is updated consistently with the new configuration options.


1842-1850: LGTM!

The provider initialization correctly incorporates the new reference parameters while maintaining existing configuration.

Cargo.toml (2)

81-81: LGTM!

The memmap2 dependency is appropriate for efficient memory-mapped file access to reference FASTA files.


48-48:

❓ Verification inconclusive

Verify compatibility with HGVS 0.18.0.

The HGVS dependency has been updated to a new minor version, which may include breaking changes.


🌐 Web query:

What are the breaking changes in HGVS 0.18.0 compared to 0.17.5?

💡 Result:

The provided search results do not contain information about an "HGVS 0.18.0" release or breaking changes between versions 0.17.5 and 0.18.0 for any software named "HGVS." This appears to be a potential misunderstanding:

  1. HGVS Nomenclature (Human Genome Variation Society) uses version numbers like 21.x.x ([source][2]), with no mention of a 0.x.x version scheme in any of the provided resources.

  2. The only reference to version 0.18.0 comes from an unrelated project called wlroots ([source][10]), which describes breaking changes for compositors in its backend system.

Before providing further assistance, please verify:

  • Whether this refers to HGVS nomenclature guidelines (human genome variant descriptions)
  • Or a software/library named "HGVS" with semantic versioning (e.g., hgvs Python package)

Let me know how you'd like to proceed!

Citations:


HGVS 0.18.0 Compatibility Verification

The dependency update in Cargo.toml (line 48) changes HGVS from version 0.17.5 to 0.18.0. A web query for documented breaking changes did not return any official notes or changelogs indicating modifications that would impact our usage. However, since the version bump might signal subtle differences, please ensure that:

  • All functionality relying on HGVS is thoroughly tested.
  • Integration tests are run to confirm that the new version’s behavior matches expectations.
  • If any undocumented changes are discovered during testing, consider reviewing the dependency’s repository or contacting its maintainers for clarification.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c564d72 and df869d7.

📒 Files selected for processing (1)
  • src/annotate/seqvars/mod.rs (18 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Testing
  • GitHub Check: Schema
  • GitHub Check: build-and-push-image
🔇 Additional comments (3)
src/annotate/seqvars/mod.rs (3)

62-62: LGTM!

The new reference module is correctly declared with appropriate visibility and follows Rust naming conventions.


85-91: LGTM!

The new fields are well-designed with:

  • Appropriate types for their purposes
  • Clear documentation
  • Correct dependency enforcement between fields using the requires attribute

1834-1839: LGTM!

The function signature changes are consistent and properly propagate the new reference parameters throughout the codebase.

Also applies to: 1996-2002, 2077-2083

@tedil tedil merged commit a9dc3da into main Feb 17, 2025
9 checks passed
@tedil tedil deleted the require-reference-fasta branch February 17, 2025 13:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant