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

fix: Correctly handle non str index list for bwa-mem2/mem #3101

Merged
merged 8 commits into from
Aug 15, 2024

Conversation

votti
Copy link
Contributor

@votti votti commented Aug 6, 2024

As reported in #522, currently the bwa2-mem wrapper has issues if idx is a sequence is it incorrectly checked input.index to be as string instead of input.idx.

This bug was silent, as usually snakemake.input.index would always be a available as functools.partial(<function Namedlist._used_attribute at 0x73ac4dbc0c20>, _name='index') or similar. Thus the predicate that it was not a str was always true.
Now with snakemake=8.16.0 this changed and the bug becomes an error running the already existing tests.

While the discussion in #522 indicates, that there is an underlying issue with the concept of input.idx being as sequence of indices, this may need rework later. Until all the details are decided, having a correct working version should be still valuable. With the current state any workflow using this wrapper using snakemake=8.16.0 is broken.

QC

While the contributions guidelines are more extensive, please particularly ensure that:

  • test.py was updated to call any added or updated example rules in a Snakefile
  • input: and output: file paths in the rules can be chosen arbitrarily
  • wherever possible, command line arguments are inferred and set automatically (e.g. based on file extensions in input: or output:)
  • temporary files are either written to a unique hidden folder in the working directory, or (better) stored where the Python function tempfile.gettempdir() points to
  • the meta.yaml contains a link to the documentation of the respective tool or command under url:
  • conda environments use a minimal amount of channels and packages, in recommended ordering

Summary by CodeRabbit

  • New Features

    • Enhanced documentation clarifying input requirements for index files, ensuring users know all necessary file extensions.
    • Added a new function to extract the longest common prefix from index file names, improving error handling.
  • Bug Fixes

    • Updated index file specifications to require a complete list of index files, preventing execution errors due to missing files.
  • Documentation

    • Improved comments and descriptions in the Snakefile and meta.yaml for better user guidance on index file usage.

As reported in snakemake#522, currently this wrapper
has issues if `idx` is a sequence is it incorrectly
checked `input.index` to be as tring instead of `input.idx`.
This is fixed now.

While the discussin in snakemake#522 indicates, that there
is an underlying issue with the concept of `input.idx` being
as sequence of indices, this may need rework later.
Until all the details are decided, having a correct version
should be still valuable.
@fgvieira
Copy link
Collaborator

fgvieira commented Aug 6, 2024

I think that all input files should be specified as input, so that snakemake can check if they exist and are updated. Also, idx is mandatory, no?

If so, can't we just have something lile:

if not isinstance(snakemake.input.idx, list):
    RAISE ERROR
index = path.splitext(snakemake.input.idx[0])[0]

@votti
Copy link
Contributor Author

votti commented Aug 6, 2024

I agree that this should be more specific, but would think that expecting any list may still be a bit vague.
Wouldn't the better thing be to check if at least all the files required are there?

I lack a bit the domain knowledge but would think, this should be all outputs of bwa-mem2/index: https://snakemake-wrappers.readthedocs.io/en/stable/wrappers/bwa-mem2/index.html ?

So wouldnt the even better solution be to:

REQUIRED_IDX = {".0123", ".amb", ".ann", ".bwt.2bit.64", ".pac"}

idx_base, idx_ext = zip(*(path.splitext(index)
                                for index in snakemake.input.idx))

missing_idx = REQUIRED_IDX - set(idx_ext)
if len(missing_idx) > 0:
    raise ValueError(f"Missing required indices: {missing_idx} declarad as input.idx")

index = idx_base[0]

@fgvieira
Copy link
Collaborator

fgvieira commented Aug 6, 2024

I am not super familiar with bwa-mem2, but I'd also say those are all outputs.
And your solution is definitely better!

@votti
Copy link
Contributor Author

votti commented Aug 7, 2024

Reading again through the discussion #522 I have 3 points:

  1. I think the reference itself (genome.fasta in the example) would also be an implicitly required input.

Should this be added as well as part of this PR, eg as an explicit ref input?

  1. I think the reference and the indices need to be in the same input folder and have matching naming - should this be validated as well?
    -> i.e. validate that all indices have the basename of {ref}

  2. Even the example does not mention all the indices:
    multiext("genome.fasta", ".amb", ".ann", ".bwt.2bit.64", ".pac"),
    while the index wrapper additionally mentiones: {genome}.0123
    Is this an omission, or does BWA-MEM2 not require this?
    At least I find this mentioned in the BWA-MEM2 source code.

CC @lczech @dlaehnemann '

@dlaehnemann
Copy link
Contributor

Regarding your questions:

  1. I don't think samtools sort actually needs the reference. It is not used in the command and the docs don't even mention a reference file for this command: https://www.htslib.org/doc/samtools-sort.html
    So I think, this was a mis-phrasing or misunderstanding in the original discussion. I would say, there's no need to add the reference itself on this wrapper.
  2. With 1. not necessary, this also shouldn't be necessary.
  3. Yes, make it as complete as possible, and make it match what the bwa-mem2/index wrapper provides as output. 👍 The mismatch you found most likely is an omission.

@dlaehnemann
Copy link
Contributor

By the way, many thanks for taking this up and for putting in the effort of fixing this properly!

@votti
Copy link
Contributor Author

votti commented Aug 12, 2024

Sorry for being a bit delayed in impelementing the "proper" solution: I got a strong flu last week and now battling catching up to dooming deadlines. After Wednesday I would have time to do this - if this is more urgent and someone else has time to finish this please go ahead!

Vito Zanotelli added 3 commits August 14, 2024 17:08
These are typically built by the bwa-mem2/index
tool.
Now all indices required need to be declared.
The previous solution using os.path.splitext does
fail with the index "a.fasta.bwt.2bit.64"
Copy link
Contributor

coderabbitai bot commented Aug 15, 2024

Warning

Rate limit exceeded

@votti has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 1 minutes and 15 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

Files that changed from the base of the PR and between 63e8483 and 19c9ed5.

Walkthrough

The recent updates enhance the documentation and functionality of the bio/bwa-mem2/mem module. Key improvements include a detailed description of the required index files in the meta.yaml, stricter input requirements in the Snakefile rules, and enhanced error handling in the wrapper.py. These changes aim to improve user clarity and ensure that all necessary index files are provided, thereby facilitating successful execution of the BWA-MEM2 algorithm.

Changes

File Change Summary
.../bio/bwa-mem2/mem/meta.yaml Enhanced documentation for the idx input parameter to specify all required reference genome index file extensions.
.../bio/bwa-mem2/mem/test/Snakefile Updated comments to clarify the requirement for a complete list of index files. Added ".0123" as a required file extension in the idx parameter for both bwa_mem2_mem and bwa_mem2_mem_sam rules.
.../bio/bwa-mem2/mem/wrapper.py Introduced a constant REQUIRED_IDX for index file extensions. Added a function get_common_prefix for extracting common prefixes from index file names. Improved error handling to check for the presence of all required index files.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Wrapper
    participant IndexFile

    User->>Wrapper: Provide index files
    Wrapper->>IndexFile: Validate presence of required files
    IndexFile-->>Wrapper: All required files present
    Wrapper-->>User: Execute BWA-MEM2 algorithm
Loading
sequenceDiagram
    participant User
    participant Wrapper
    participant IndexFile

    User->>Wrapper: Provide index files
    Wrapper->>IndexFile: Validate presence of required files
    IndexFile-->>Wrapper: Missing files detected
    Wrapper-->>User: Raise ValueError with missing files
Loading

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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.

@votti
Copy link
Contributor Author

votti commented Aug 15, 2024

I have now finished implementing this and also updated the tests and documentation.

What I found was that previously implemented approach of using os.path.splitext to identify the extension would actually not work correctly for an index such as a.fasta.bwt.2bit.64 (where the extension is .bwt.2bit.64).
I have now implemented a routine to identify the longest common prefix for all indices (i.e. a.fasta) and the extension from this.

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

Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between 8b42097 and 63e8483.

Files selected for processing (3)
  • bio/bwa-mem2/mem/meta.yaml (1 hunks)
  • bio/bwa-mem2/mem/test/Snakefile (2 hunks)
  • bio/bwa-mem2/mem/wrapper.py (2 hunks)
Additional context used
Path-based instructions (1)
bio/bwa-mem2/mem/wrapper.py (1)

Pattern **/*.py: Do not suggest to add trailing commas.
Do not suggest type annotations for functions that are defined inside of functions or methods.
Do not suggest type annotation of the self argument of methods.

Ruff
bio/bwa-mem2/mem/wrapper.py

11-11: os.path imported but unused

Remove unused import: os.path

(F401)


47-47: Missing return type annotation for private function all_same

(ANN202)


47-47: Missing type annotation for function argument x

(ANN001)


57-57: Undefined name snakemake

(F821)


60-63: Avoid specifying long messages outside the exception class

(TRY003)


62-62: Trailing comma missing

Add trailing comma

(COM812)


65-65: Undefined name snakemake

(F821)


68-71: Avoid specifying long messages outside the exception class

(TRY003)


70-70: Trailing comma missing

Add trailing comma

(COM812)

Additional comments not posted (8)
bio/bwa-mem2/mem/meta.yaml (1)

11-14: Documentation improvement approved.

The updated description for the idx parameter provides clear guidance on the required index files, enhancing user understanding.

bio/bwa-mem2/mem/test/Snakefile (2)

4-5: Index file specification update approved.

The addition of the ".0123" file extension ensures that all required index files are specified, aligning with the updated requirements.


23-24: Index file specification update approved.

The addition of the ".0123" file extension ensures that all required index files are specified, aligning with the updated requirements.

bio/bwa-mem2/mem/wrapper.py (5)

16-17: Introduction of REQUIRED_IDX approved.

Defining the required index file extensions as a constant improves code maintainability and clarity.


35-53: Introduction of get_common_prefix approved.

The function efficiently extracts the longest common prefix, enhancing the robustness of index handling.

Tools
Ruff

47-47: Missing return type annotation for private function all_same

(ANN202)


47-47: Missing type annotation for function argument x

(ANN001)


65-65: Verify the usage of snakemake.

The variable snakemake is used but not defined in the provided context. Ensure it is correctly imported or passed to this script.

Tools
Ruff

65-65: Undefined name snakemake

(F821)


68-71: Consider using exception classes for long messages.

To improve readability, consider defining a custom exception class for long error messages.

Tools
Ruff

68-71: Avoid specifying long messages outside the exception class

(TRY003)


70-70: Trailing comma missing

Add trailing comma

(COM812)


57-57: Verify the usage of snakemake.

The variable snakemake is used but not defined in the provided context. Ensure it is correctly imported or passed to this script.

Tools
Ruff

57-57: Undefined name snakemake

(F821)

Comment on lines 60 to 63
raise ValueError(
"Could not determine common prefix of index files.\n"
"Please make sure that the index files are named correctly."
)
Copy link
Contributor

@coderabbitai coderabbitai bot Aug 15, 2024

Choose a reason for hiding this comment

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

Consider using exception classes for long messages.

To improve readability, consider defining a custom exception class for long error messages.

class IndexPrefixError(ValueError):
    def __init__(self):
        super().__init__(
            "Could not determine common prefix of index files.\n"
            "Please make sure that the index files are named correctly."
        )

# Usage
raise IndexPrefixError()
Tools
Ruff

60-63: Avoid specifying long messages outside the exception class

(TRY003)


62-62: Trailing comma missing

Add trailing comma

(COM812)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@fgvieira How do you think about this one - should I go for the custom exception class?

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Collaborator

Choose a reason for hiding this comment

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

I think it is a bit overkill, but up to you (this coderabitai thing is quite new).

Copy link
Contributor

Choose a reason for hiding this comment

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

Johannes turned this coderabbitai application on. It's very chatty, but it does have some useful suggestions -- but also a lot of suggestions you can ignore. And you can chat back at it, telling it not to review certain things or why a certain suggestion is not useful. It then at least claims to learn from it... 😅

bio/bwa-mem2/mem/wrapper.py Outdated Show resolved Hide resolved
bio/bwa-mem2/mem/wrapper.py Outdated Show resolved Hide resolved
@fgvieira
Copy link
Collaborator

You also added a log file. Is that needed?

@votti
Copy link
Contributor Author

votti commented Aug 15, 2024

@log file and bam file: this were added by accident, I removed them from the corresponding commit.
Sorry!

@fgvieira fgvieira enabled auto-merge (squash) August 15, 2024 07:35
@fgvieira fgvieira merged commit 6f46508 into snakemake:master Aug 15, 2024
6 checks passed
johanneskoester pushed a commit that referenced this pull request Aug 21, 2024
🤖 I have created a release \*beep\* \*boop\*
---
##
[4.1.0](https://www.github.com/snakemake/snakemake-wrappers/compare/v4.0.0...v4.1.0)
(2024-08-21)


### Features

* Allow outputting of rendered yte config in Datavzrd wrapper
([#3123](https://www.github.com/snakemake/snakemake-wrappers/issues/3123))
([e74be78](https://www.github.com/snakemake/snakemake-wrappers/commit/e74be7843299478a276febfacb52825a9762500c))


### Bug Fixes

* Correctly handle non str index list for bwa-mem2/mem
([#3101](https://www.github.com/snakemake/snakemake-wrappers/issues/3101))
([6f46508](https://www.github.com/snakemake/snakemake-wrappers/commit/6f46508aa99663930e70c82114205929aee2dfcb))


### Performance Improvements

* autobump bio/gatk3/baserecalibrator
([#3119](https://www.github.com/snakemake/snakemake-wrappers/issues/3119))
([6c2bdfd](https://www.github.com/snakemake/snakemake-wrappers/commit/6c2bdfdca79c7037448bc601a4aeb3d578ea0980))
* autobump bio/gatk3/realignertargetcreator
([#3118](https://www.github.com/snakemake/snakemake-wrappers/issues/3118))
([ba219e7](https://www.github.com/snakemake/snakemake-wrappers/commit/ba219e7698eb078fe22c703a9662c8cb6deee0eb))
* autobump bio/genomescope
([#3117](https://www.github.com/snakemake/snakemake-wrappers/issues/3117))
([6292229](https://www.github.com/snakemake/snakemake-wrappers/commit/62922298404397c7b23dc5b8fb01bc33e445e97f))
* autobump bio/igv-reports
([#3120](https://www.github.com/snakemake/snakemake-wrappers/issues/3120))
([fe33c2c](https://www.github.com/snakemake/snakemake-wrappers/commit/fe33c2c27328212c528e94f995fd0bc26d7fde39))
* autobump bio/trinity
([#3121](https://www.github.com/snakemake/snakemake-wrappers/issues/3121))
([62b0231](https://www.github.com/snakemake/snakemake-wrappers/commit/62b0231c99920200e3fa6794f87578869cc35bd5))
* Update Datavzrd wrapper
([#3122](https://www.github.com/snakemake/snakemake-wrappers/issues/3122))
([5101461](https://www.github.com/snakemake/snakemake-wrappers/commit/51014613939bfc5e48e0b2ae619e283cf36bfd88))
---


This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
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.

4 participants