chase mateusiak
02/28/2024, 5:58 PMThomas Danhorn
03/21/2024, 3:04 AMchase mateusiak
03/22/2024, 8:20 PMThomas Danhorn
03/22/2024, 8:22 PMchase mateusiak
03/22/2024, 8:32 PM# Example usage
# bam_file <- "TH0003_sorted_markdups_tagged.bam"
# region <- "TH_C8_NAT_IR6:301"
# min_alignment_score <- 0 # no filter
# reads_df <- extract_reads_by_alignment_score('sample1',bam_file, region, min_alignment_score)
# Define the function
extract_reads_by_alignment_score <- function(sample, bam_file, region, min_alignment_score) {
# Parse the region
chrom <- gsub(":.*", "", region)
pos <- as.numeric(gsub(".*:", "", region))
# Ensure only valid fields are requested
valid_fields <- scanBamWhat()
requested_fields <- c("qname", "pos", "cigar", "qual")
what_fields <- requested_fields[requested_fields %in% valid_fields]
# Define the scan parameters, ensuring only valid fields are included
param <- ScanBamParam(
which = GRanges(chrom, IRanges(start = pos, end = pos)),
what = what_fields,
tag = c("AS", "NM")
)
# Read the BAM file
aln <- scanBam(bam_file, param = param)[[1]]
match_length_left_right <- parse_cigar_for_coordinate(aln$pos, aln$cigar, pos)
tibble(sample=sample,
chr=chrom,
pos=pos,
qname = aln$qname,
cigar=aln$cigar,
align_qual=aln$tag$AS,
edit_dist=aln$tag$NM) %>%
bind_cols(match_length_left_right)
}
output:
sample,chr,pos,qname,cigar,align_qual,edit_dist,length_aln_left,length_aln_right
SLB0003,SB_C8_NAT,2245,<qname1>,150M,150,0,113,36
SLB0003,SB_C8_NAT,2245,<qname2>,150M,150,0,63,86
...
where this would be an example of the right junction (2245) with coverage, but the left (which was something like 550) withoutchase mateusiak
03/22/2024, 8:33 PMlength_aln_left and _right to remove reads that cover due to soft clipping (filter out a record if either of those is 0)chase mateusiak
03/22/2024, 8:34 PMparse_cigar_for_coordinate <- function(positions, cigars, coordinate) {
results <- lapply(seq_along(cigars), function(i) {
pos <- positions[i]
cigar <- cigars[i]
# Split CIGAR string into operations and lengths
ops <- gregexpr("[A-Z]", cigar)[[1]]
lengths <- as.integer(unlist(regmatches(cigar, gregexpr("[0-9]+", cigar))))
operations <- regmatches(cigar, gregexpr("[A-Z]", cigar))[[1]]
aln_left <- 0
aln_right <- 0
reached_coordinate <- FALSE
for (j in seq_along(operations)) {
op <- operations[j]
len <- lengths[j]
# For alignment length calculation, consider match, deletion, and mismatch
if(op %in% c("M", "D", "N", "=", "X")) {
if (pos + len <= coordinate) {
aln_left <- aln_left + len
} else if (pos > coordinate) {
aln_right <- aln_right + len
} else {
aln_left <- aln_left + (coordinate - pos)
aln_right <- aln_right + (pos + len - coordinate - 1)
reached_coordinate <- TRUE
break
}
pos <- pos + len
}
if (reached_coordinate) break
}
return(c(length_aln_left = aln_left, length_aln_right = aln_right))
})
return(bind_rows(results))
}