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

attempt parallelized demultiplexing #200

Merged
merged 8 commits into from
Feb 6, 2025
Merged

attempt parallelized demultiplexing #200

merged 8 commits into from
Feb 6, 2025

Conversation

pdimens
Copy link
Owner

@pdimens pdimens commented Feb 5, 2025

The goal of this is to see if the new demultiplexing can be done by parsing the multiplexed data only looking for one sample at a time, which can be done in parallel. The results are then piped into gzip for fast comrpession

Summary by CodeRabbit

  • New Features

    • Enhanced demultiplexing now supports multiple barcode associations per sample.
    • Added an output file that provides detailed barcode information for improved traceability.
    • Introduced a flag to retain reads that could not be demultiplexed.
  • Bug Fixes

    • Updated thread count minimum to 2 for improved parallel processing capabilities.
  • Refactor

    • Simplified sample configuration by directly using user-defined parameters, removing the need for intermediary configuration files.
    • Optimized read processing and logging by consolidating performance metrics into a unified summary.
    • Streamlined workflow by removing unnecessary indexing steps and associated functions.
    • Improved error message clarity and formatting for better user guidance.

Copy link

coderabbitai bot commented Feb 5, 2025

📝 Walkthrough

Walkthrough

The pull request simplifies the demultiplexing process in the primary Python script by removing the schema-reading function and instead relying on Snakemake parameters to obtain sample names and segment identifiers. Output file handling is streamlined to directly produce sample-specific files and a unified log. In parallel, the Snakefile is adjusted to rename variables, remove the schema input, update output management by using pipes, and add new lambda parameters for sample and id_segments. A backup version of the original script with legacy barcode and schema functions is retained.

Changes

File(s) Summary of Changes
harpy/scripts/demultiplex_gen1.py Removed the read_schema function along with associated variables; updated sample handling to use snakemake.params.sample and snakemake.params.id_segments; simplified output file management (direct sample files for R1 and R2) and consolidated log output with read summary details.
harpy/scripts/demultiplex_gen1.py.bak Retains the legacy implementation with functions for reading barcodes and schema, calculating Levenshtein distances, and determining read codes, as well as traditional logic for demultiplexing based on barcode matches.
harpy/snakefiles/demultiplex_gen1.smk Renamed variable smpl to sample in the barcodedict function; removed the schema input in the demultiplex rule; changed output handling from temporary collections to pipes; introduced a new output (bx_info) for barcode logs; added lambda parameters to fetch sample and id_segments.
harpy/demultiplex.py Updated the --threads option in the gen1 command to enforce a minimum value of 2 for thread counts, altering the acceptable range for parallel processing capabilities.
harpy/bin/bx_stats.py Updated the read fetching loop to continue until the end of the file is reached by adding until_eof=True to the fetch() method.
harpy/bin/check_bam.py Commented out the existence check for BAM index files and updated the fetch() method to include until_eof=True.
harpy/bin/concatenate_bam.py Commented out checks for BAM index files and their creation, affecting the handling of temporary index files.
harpy/bin/deconvolve_alignments.py Commented out code that checks for BAM file indexing, altering the control flow related to BAM file handling.
harpy/bin/leviathan_bx_shim.py Commented out the check for BAM index files and updated the fetch method to include until_eof=True.
harpy/snakefiles/preflight_bam.smk Removed the get_align_index function and the index_alignments rule, simplifying the BAM file processing workflow.
harpy/snakefiles/sv_leviathan.smk Removed the process_alignments rule and introduced the index_barcodes rule, shifting focus from alignment processing to barcode indexing.

Sequence Diagram(s)

sequenceDiagram
    participant S as Snakefile (demultiplex rule)
    participant P as demultiplex_gen1.py
    participant OF as Output Files
    participant L as Log

    S->>P: Invoke demultiplex script with sample and id_segments parameters
    P->>P: Process input reads and determine status using id_segments
    P->>OF: Write processed reads to sample-specific R1 and R2 files
    P->>L: Log total, correct, and corrected reads summary
Loading

Assessment against linked issues

Objective Addressed Explanation
Speedup demultiplex barcode by parallelisation (#198) The PR focuses on simplifying sample handling and output management rather than implementing parallelisation techniques.

Possibly related issues

  • Speedup Demultiplex workflow #190: The changes simplify parameter usage and output handling, which may be a preliminary step toward improving the demultiplex workflow, but they do not implement the comprehensive parallelization or speed enhancements described in the issue.

Possibly related PRs

  • revisit demultiplexing, sv cli commands #191: The changes in the main PR, which involve significant modifications to the demultiplex_gen1.py script including the removal of the read_schema function, are related to the changes in the retrieved PR that also focuses on demultiplexing functionalities and includes updates to the demultiplex_gen1.smk file, which directly interacts with the demultiplex_gen1.py script.

Suggested labels

enhancement

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

Copy link

@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

🧹 Nitpick comments (1)
harpy/snakefiles/demultiplex_gen1.smk (1)

37-37: Minor style note.
samplenames = list(samples) might be more concise, but this is purely stylistic.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ad259db and 2d2be42.

📒 Files selected for processing (3)
  • harpy/scripts/demultiplex_gen1.py (2 hunks)
  • harpy/scripts/demultiplex_gen1.py.bak (1 hunks)
  • harpy/snakefiles/demultiplex_gen1.smk (2 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
harpy/scripts/demultiplex_gen1.py

65-65: Undefined name snakemake

(F821)


66-66: Undefined name snakemake

(F821)


93-93: Undefined name snakemake

(F821)


100-100: Undefined name status_R1

(F821)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build/Cache Container
🔇 Additional comments (20)
harpy/scripts/demultiplex_gen1.py (9)

65-67: Confirm snakemake is defined in the execution environment.
These lines assume that snakemake is globally available. Since static analysis flags snakemake as undefined, please confirm that this script is only executed in a Snakemake environment where snakemake is injected.

🧰 Tools
🪛 Ruff (0.8.2)

65-65: Undefined name snakemake

(F821)


66-66: Undefined name snakemake

(F821)


91-93: Confirm snakemake usage for output file references.
Similar to lines 65–67, these references to snakemake might fail if the script is run outside Snakemake. Just verify that your workflow always injects snakemake.output.bx_info.

🧰 Tools
🪛 Ruff (0.8.2)

93-93: Undefined name snakemake

(F821)


110-110: No issues found.
The check for "unclear" within statuses appears logically correct.


116-116: No issues found.
The check for "corrected" in statuses is consistent and appears correct.


122-122: No issues found.
Verifying "found" for all statuses is appropriate for this logic branch.


126-126: Looks good.
The map initialization with [1,0] is consistent with your logic for counting correct vs. corrected reads.


128-128: Log header format is clear.
The newly added header clarifies the output columns well.


130-130: LGTM for clear read map output.
Writing the total and the breakdown of correct vs. corrected reads is a helpful summary.


132-132: LGTM for unclear reads output.
This line properly logs unclear barcode reads as requested.

harpy/scripts/demultiplex_gen1.py.bak (7)

1-2: Shebang and blank line.
This looks fine; ensure that the script is marked as executable if needed.


3-6: Imports appear appropriate.
No apparent issues; pysam and Levenshtein usage likely assumes an environment where these are installed.


7-21: Review of read_barcodes function.
The logic reads each line, validates the segment, and stores the data in a dict. The approach is clear and consistent.


23-41: Review of read_schema function.
This function loads sample-to-segment mappings. It’s clear and well-commented. However, note that id_letter is assumed to be unique if multiple code letters exist. Confirm that your schema never includes more than one letter type.


42-58: Review of get_min_dist function.
The Levenshtein-based approach for nearest barcodes is standard. The logic for tying a tie (nbFound > 1) to XX00 code is also clear.


60-78: Review of get_read_codes function.
The code properly splits the index read, checks dictionary membership, and falls back to get_min_dist. The use of status = "found"/"corrected"/"unclear" is consistent.


80-162: Main execution block.

  1. The global bar_codes dictionary is loaded from segment files; consider clarifying this usage with a comment.
  2. All references to snakemake should be verified if used outside a Snakemake environment.
  3. Output is well-structured: valid vs invalid logs, plus separate R1/R2 files for each sample.

Otherwise, logic and flow appear correct for demultiplexing.

harpy/snakefiles/demultiplex_gen1.smk (4)

27-31: Check for multiple barcodes per sample.
Appending multiple barcodes to each sample is a good enhancement. This code block looks correct for building a multi‐barcode dictionary.


60-62: Pipe-based outputs look good.
Switching to pipe(...) for read outputs simplifies intermediate file handling and is consistent with your new approach.


66-66: No issues found.
Retaining outdir as a parameter is consistent with the rest of the workflow usage.


68-69: Parameterized sample and segment retrieval.
Defining lambdas to fetch sample and id_segments from samples is a straightforward approach.

harpy/scripts/demultiplex_gen1.py Outdated Show resolved Hide resolved
Copy link

@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: 0

🧹 Nitpick comments (1)
harpy/scripts/demultiplex_gen1.py (1)

65-67: Document Snakemake dependency.

Add a docstring at the beginning of the script to clarify that this script is intended to be run by Snakemake and requires the snakemake variable to be injected.

Add this docstring at the beginning of the file:

 #!/usr/bin/env python

+"""
+This script is designed to be run by Snakemake and requires the `snakemake` variable
+to be injected by the Snakemake workflow engine.
+"""
🧰 Tools
🪛 Ruff (0.8.2)

65-65: Undefined name snakemake

(F821)


66-66: Undefined name snakemake

(F821)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2d2be42 and af447b3.

📒 Files selected for processing (2)
  • harpy/demultiplex.py (1 hunks)
  • harpy/scripts/demultiplex_gen1.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
harpy/scripts/demultiplex_gen1.py

65-65: Undefined name snakemake

(F821)


66-66: Undefined name snakemake

(F821)


93-93: Undefined name snakemake

(F821)

🔇 Additional comments (5)
harpy/scripts/demultiplex_gen1.py (4)

91-93: LGTM! Simplified output handling supports parallelization.

The direct file output approach aligns well with the PR's objective of parallelizing demultiplexing by focusing on one sample at a time.

🧰 Tools
🪛 Ruff (0.8.2)

93-93: Undefined name snakemake

(F821)


96-97: LGTM! Clear and consistent variable naming.

The status variables are well-named and the logic is correct.


98-100: LGTM! Efficient segment filtering.

The filtering logic effectively supports the parallelization strategy by focusing on one sample at a time.


129-133: LGTM! Clear and consistent log format.

The log file output is well-structured and provides all necessary information in a readable format.

harpy/demultiplex.py (1)

42-42: Verify minimum thread count requirement.

The minimum thread count has been increased from 1 to 2, which enforces parallelization. While this aligns with the PR's objective, it may prevent users from running the tool on single-core systems.

Please confirm:

  1. Is this a deliberate design choice to enforce parallelization?
  2. Have you considered the impact on users with single-core systems?

Copy link

@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 7f271ee and a6a24e3.

📒 Files selected for processing (2)
  • harpy/_validations.py (2 hunks)
  • test/demux/samples.schema (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build/Cache Container
🔇 Additional comments (3)
harpy/_validations.py (3)

268-268: LGTM! Enhanced error message visibility.

The addition of color formatting for the segment ID improves error message readability.


286-287: LGTM! Improved error message clarity.

The addition of color formatting for the filename and the clear example format enhances user understanding.


289-295: LGTM! Enhanced error message with better guidance.

The updated error message now provides clearer guidance about sample IDs needing to be in a single segment, with helpful examples using color formatting.

test/demux/samples.schema Show resolved Hide resolved
@pdimens pdimens merged commit 97283ed into main Feb 6, 2025
20 checks passed
@pdimens pdimens deleted the demux_parallelized branch February 6, 2025 17:01
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.

speedup demultiplex barcode by parallelisation
1 participant