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: only consider MAPPING/ALIGNING SUMMARY entries from dragen qc summary file #134

Merged
merged 3 commits into from
Nov 6, 2024

Conversation

tedil
Copy link
Contributor

@tedil tedil commented Nov 4, 2024

Fixes #131
However, I assume that the MAPPING/ALIGNING SUMMARY entries were supposed to be used, when in fact the MAPPING/ALIGNING PER RG entries were the ones actually ending up being used. Not sure if these were actually different in the old files, but in the new files, they certainly are, since they are partitioned into the WGS, EvidenceRead_Normal and EvidenceHaplotype cases.

Summary by CodeRabbit

  • New Features

    • Enhanced data filtering in the sample data loading process for improved accuracy in metrics.
  • Bug Fixes

    • Adjusted how the summary field is accessed, ensuring more relevant data is processed in mapping metrics.
  • Tests

    • Updated test snapshots to reflect changes in statistical values for test_dragen_to_bam_qc and test_load_bam_qc, ensuring accuracy in metrics.

Copy link
Contributor

coderabbitai bot commented Nov 4, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes in this pull request involve modifications to the load_sample_data function within the varfish_cli/cli/tools/__init__.py file. Key alterations include renaming a field in the fieldnames list and implementing a conditional filter for populating the mapping_metrics dictionary. This filter ensures that only entries meeting specific criteria are included. The error handling remains unchanged, and the overall structure of the function is preserved. The dragen_to_bam_qc function's reliance on the updated load_sample_data function may affect its data processing.

Changes

File Path Change Summary
varfish_cli/cli/tools/init.py Modified load_sample_data: renamed field from "_coverage_summary" to "_summary"; updated logic for mapping_metrics to filter entries based on new criteria.
tests/cli/snapshots/test_tools.ambr Updated snapshot data for test_dragen_to_bam_qc and test_load_bam_qc to reflect new statistical values for bamstats.

Assessment against linked issues

Objective Addressed Explanation
Ensure varfish-cli tools dragen-to-bam-qc can parse current mapping_metrics.csv files (#131) The new filtering may affect parsing, but it's unclear if it resolves the issue.

🐇 In the meadow, I hop and play,
With changes made to brighten the day.
Data now filtered, oh what a sight,
Mapping metrics dancing, all feels just right!
Let's parse those files without a care,
For every entry, there's joy to share! 🌼


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 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
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: 2

🧹 Outside diff range and nitpick comments (2)
varfish_cli/cli/tools/__init__.py (2)

27-27: Consider separating fieldnames for different file types.

The same fieldnames are used for parsing both QC coverage and mapping metrics files. This coupling could make the code brittle if the file formats evolve differently.

Consider defining separate fieldnames for each file type:

-    fieldnames = ["_summary", "_empty", "label", "value"]
+    qc_coverage_fieldnames = ["_summary", "_empty", "label", "value"]
+    mapping_metrics_fieldnames = ["_summary", "_empty", "label", "value"]

Also, consider adding validation for the CSV structure before parsing to fail fast if the file format changes.


Line range hint 77-91: Improve handling of NA values in metrics.

The PR objectives mention handling NA values, but the current error handling doesn't distinguish between NA values and other invalid values. This could make debugging harder when NA values are encountered.

Consider adding specific handling for NA values:

     key_insert_length_mean = "Insert length: mean"
     try:
+        value = mapping_metrics[key_insert_length_mean]
+        if value.upper() == "NA":
+            logger.warning(f"NA value found for {key_insert_length_mean}, using 0.0")
+            insert_length_mean = 0.0
+        else:
+            insert_length_mean = float(value)
-        insert_length_mean = float(mapping_metrics[key_insert_length_mean])
     except (KeyError, ValueError) as e:
-        logger.error(f"'{key_insert_length_mean}' not in {mapping_metrics_path} or no int")
+        logger.error(
+            f"'{key_insert_length_mean}' not in {mapping_metrics_path} or invalid value: {str(e)}"
+        )
         raise typer.Exit() from e

Apply similar changes to other metric parsing blocks to handle NA values consistently.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f6f5adc and d86667d.

📒 Files selected for processing (1)
  • varfish_cli/cli/tools/__init__.py (2 hunks)

Comment on lines +39 to +43
mapping_metrics = {
row["label"]: row["value"]
for row in reader
if row["_summary"] == "MAPPING/ALIGNING SUMMARY" and row["_empty"] == ""
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Handle NA values in mapping metrics dictionary construction

The verification reveals that NA values are present in several important metrics, but the current implementation doesn't explicitly handle them. This could lead to potential issues when these values are used downstream.

  • The code should explicitly handle 'NA' string values when constructing the mapping_metrics dictionary
  • Multiple metrics contain NA values, including:
    • "Number of duplicate marked and mate reads removed"
    • "Reads with MAPQ NA"
    • "Bases in target bed [% of genome]"
    • "Provided sex chromosome ploidy"
🔗 Analysis chain

Verify handling of Dragen output variations.

Let's verify that the implementation handles different variations of Dragen output files correctly.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for variations in Dragen output files to ensure robust parsing

# Test 1: Check for different summary types in mapping metrics files
echo "Checking for different summary types in mapping metrics files..."
rg -A 1 "^_summary" --no-filename | sort -u

# Test 2: Check for multiple occurrences of insert length fields
echo "Checking for multiple insert length entries..."
rg -B 1 "Insert length: mean" --no-filename

# Test 3: Check for NA values in metrics
echo "Checking for NA values in metrics..."
rg -i "\bna\b" --no-filename

Length of output: 2768


🛠️ Refactor suggestion

Add logging and validation for mapping metrics filtering.

While the filtering correctly implements the requirement to only consider "MAPPING/ALIGNING SUMMARY" entries, there are several improvements that could make the code more robust and maintainable:

  1. The purpose of the row["_empty"] == "" condition is not documented
  2. Silent filtering could make debugging difficult if no rows match the criteria
  3. No validation ensures that required metrics are present after filtering

Consider implementing these improvements:

     mapping_metrics: Dict[str, str] = {}
+    required_metrics = {
+        "Total input reads",
+        "Number of duplicate marked reads",
+        "Insert length: mean",
+        "Insert length: standard deviation"
+    }
+    filtered_count = 0
     with open(mapping_metrics_path, "rt") as coverage_metrics_file:
         reader = csv.DictReader(coverage_metrics_file, fieldnames=fieldnames, delimiter=",")
         mapping_metrics = {
             row["label"]: row["value"]
             for row in reader
             if row["_summary"] == "MAPPING/ALIGNING SUMMARY" and row["_empty"] == ""
         }
+        logger.debug(
+            f"Filtered {filtered_count} non-MAPPING/ALIGNING SUMMARY entries from {mapping_metrics_path}"
+        )
+        missing_metrics = required_metrics - mapping_metrics.keys()
+        if missing_metrics:
+            logger.error(
+                f"Required metrics {missing_metrics} not found in {mapping_metrics_path}"
+            )
+            raise typer.Exit()

Committable suggestion skipped: line range outside the PR's diff.

Copy link

@Nicolai-vKuegelgen Nicolai-vKuegelgen left a comment

Choose a reason for hiding this comment

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

LGTM

I've also confirmed with LB that we should use the values from the 'Summary' section, not the 'per RG' ones.

@tedil
Copy link
Contributor Author

tedil commented Nov 6, 2024

It seems that some test snapshots are no longer valid then ( https://github.com/varfish-org/varfish-cli/actions/runs/11668684344/job/32488937744?pr=134 ); in other words, we might not always have used the correct entries?

@tedil tedil enabled auto-merge (squash) November 6, 2024 15:53
@tedil tedil merged commit c4b8dd1 into main Nov 6, 2024
10 of 11 checks passed
@tedil tedil deleted the 131-adapt-to-dragen-summary-changes branch November 6, 2024 15:54
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.

varfish-cli tools dragen-to-bam-qc fails with current Dragen output
2 participants