generated from snakemake-workflows/snakemake-workflow-template
-
Notifications
You must be signed in to change notification settings - Fork 3
feat: add vaf calculation for strelka results #109
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
Open
famosab
wants to merge
5
commits into
main
Choose a base branch
from
feat/calculate-vaf
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
channels: | ||
- conda-forge | ||
- bioconda | ||
dependencies: | ||
- cyvcf2 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,145 @@ | ||
from cyvcf2 import VCF, Writer | ||
import sys | ||
import argparse | ||
import numpy as np | ||
|
||
def get_snv_allele_freq(variant): | ||
refCounts = variant.format(variant.REF + "U") | ||
altCounts = variant.format(variant.ALT[0] + "U") | ||
|
||
# TODO: check which value is the correct one from the matrix (this leads to many zero VAF) | ||
tier1RefCounts = refCounts[0, 0] | ||
tier1AltCounts = altCounts[0, 0] | ||
|
||
vaf = tier1AltCounts / (tier1AltCounts + tier1RefCounts) | ||
|
||
return vaf | ||
|
||
def get_indel_allele_freq(variant): | ||
tier1RefCounts = variant.format("TAR")[0,0] | ||
tier1AltCounts = variant.format("TIR")[0,0] | ||
|
||
vaf = tier1AltCounts / (tier1AltCounts + tier1RefCounts) | ||
return vaf | ||
|
||
def calculate_vaf(variant, samples): | ||
""" | ||
Calculates the Variant Allele Frequency (VAF) for each sample and | ||
each alternate allele based on the AD (Allelic Depth) FORMAT field. | ||
|
||
Args: | ||
variant (cyvcf2.Variant): The variant object. | ||
samples (list): List of sample names. | ||
|
||
Returns: | ||
numpy.ndarray: A numpy array of shape (n_samples, n_alt_alleles) | ||
containing the VAFs. Returns None if AD field is missing. | ||
Missing values or divisions by zero result in np.nan. | ||
""" | ||
try: | ||
# Get Allelic Depths (AD) - shape: (n_samples, n_alleles) | ||
# n_alleles includes the reference allele | ||
ad = variant.format('AD') | ||
except KeyError: | ||
# AD field is not present for this variant | ||
print(f"Warning: AD field missing for variant at {variant.CHROM}:{variant.POS}. Skipping VAF calculation.", file=sys.stderr) | ||
return None | ||
|
||
n_samples = len(samples) | ||
n_alleles = len(variant.alleles) # Includes reference | ||
n_alt_alleles = n_alleles - 1 | ||
|
||
# Initialize VAF array with NaNs | ||
# Shape: (n_samples, n_alt_alleles) | ||
vaf_values = np.full((n_samples, n_alt_alleles), np.nan, dtype=np.float32) | ||
|
||
for i in range(n_samples): | ||
sample_ad = ad[i] | ||
|
||
# Check for missing AD data for the sample (represented by negative values or could be None depending on VCF) | ||
# cyvcf2 often uses negative numbers for missing integers in FORMAT fields like AD | ||
if np.any(sample_ad < 0): | ||
# Keep VAF as NaN if AD is missing for this sample | ||
continue | ||
|
||
# Calculate total depth for this sample | ||
total_depth = np.sum(sample_ad) | ||
|
||
if total_depth == 0: | ||
# Avoid division by zero, keep VAFs as NaN | ||
continue | ||
|
||
# Calculate VAF for each alternate allele | ||
for j in range(n_alt_alleles): | ||
alt_depth = sample_ad[j + 1] # AD format is [ref_depth, alt1_depth, alt2_depth, ...] | ||
vaf = alt_depth / total_depth | ||
vaf_values[i, j] = vaf | ||
|
||
return vaf_values | ||
|
||
def add_vaf_to_vcf(input_vcf_path, output_vcf_path): | ||
""" | ||
Reads an input VCF, calculates VAF for each variant/sample, adds it | ||
as a new FORMAT field 'VAF', and writes to an output VCF file. | ||
""" | ||
# Open the input VCF file | ||
try: | ||
vcf_reader = VCF(input_vcf_path) | ||
except Exception as e: | ||
print(f"Error opening input VCF file '{input_vcf_path}': {e}", file=sys.stderr) | ||
sys.exit(1) | ||
|
||
|
||
# Add the new VAF FORMAT field definition to the header | ||
# Number='A' means one value per alternate allele | ||
# Type='Float' for the frequency value | ||
try: | ||
vcf_reader.add_format_to_header({ | ||
'ID': 'VAF', | ||
'Description': 'Variant Allele Frequency calculated from AD field (Alt Depth / Total Depth)', | ||
'Type': 'Float', | ||
'Number': 'A' # One value per alternate allele | ||
}) | ||
except ValueError as e: | ||
# Catch error if the field already exists | ||
print(f"Warning: FORMAT field 'VAF' might already exist in header: {e}", file=sys.stderr) | ||
|
||
|
||
# Create a VCF writer object using the modified header | ||
try: | ||
vcf_writer = Writer(output_vcf_path, vcf_reader) | ||
except Exception as e: | ||
print(f"Error creating output VCF file '{output_vcf_path}': {e}", file=sys.stderr) | ||
vcf_reader.close() | ||
sys.exit(1) | ||
|
||
print(f"Processing VCF: {input_vcf_path}") | ||
print(f"Writing output to: {output_vcf_path}") | ||
|
||
processed_count = 0 | ||
# Iterate through each variant in the VCF | ||
for variant in vcf_reader: | ||
# Calculate VAFs for all samples for the current variant | ||
vaf_array = calculate_vaf(variant, vcf_reader.samples) | ||
|
||
# Add the calculated VAFs to the variant's FORMAT fields | ||
# The vaf_array must have shape (n_samples, n_alt_alleles) | ||
if vaf_array is not None: | ||
try: | ||
# Use set_format to add/update the VAF field for all samples | ||
variant.set_format('VAF', vaf_array) | ||
except Exception as e: | ||
print(f"Error setting VAF format for variant at {variant.CHROM}:{variant.POS}: {e}", file=sys.stderr) | ||
# Decide if you want to skip writing this variant or write without VAF | ||
# Here, we'll still write the variant but VAF might be missing/incorrect | ||
|
||
# Write the (potentially modified) variant record to the output file | ||
vcf_writer.write_record(variant) | ||
processed_count += 1 | ||
if processed_count % 1000 == 0: | ||
print(f"Processed {processed_count} variants...", file=sys.stderr) | ||
|
||
# Close the VCF reader and writer | ||
vcf_reader.close() | ||
vcf_writer.close() | ||
print(f"Finished processing. Total variants processed: {processed_count}") |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add a main block to make the script executable.
The script doesn't have a way to be executed from the command line. Since the file will likely be used as a command-line tool in a Snakemake workflow, you should add a main block to parse arguments and execute the
add_vaf_to_vcf
function.🧰 Tools
🪛 Ruff (0.8.2)
3-3:
argparse
imported but unusedRemove unused import:
argparse
(F401)
🤖 Prompt for AI Agents