Skip to content

Commit

Permalink
feat: add SupplementaryAlignment constructor from read
Browse files Browse the repository at this point in the history
  • Loading branch information
msto committed Jan 30, 2024
1 parent 0c5d6ff commit a6d52a3
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
10 changes: 10 additions & 0 deletions fgpyo/sam/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@
from typing import Optional
from typing import Tuple
from typing import Union
from typing import cast

import attr
import pysam
Expand Down Expand Up @@ -575,6 +576,15 @@ def parse_sa_tag(tag: str) -> List["SupplementaryAlignment"]:
"""
return [SupplementaryAlignment.parse(a) for a in tag.split(";") if len(a) > 0]

@classmethod
def from_read(cls, read: pysam.AlignedSegment) -> List["SupplementaryAlignment"]:
"""Returns a list of SupplementaryAlignments for a given pysam.AlignedSegment."""
if read.has_tag("SA"):
sa_tag: str = cast(str, read.get_tag("SA"))
return SupplementaryAlignment.parse_sa_tag(sa_tag)
else:
return []


def isize(r1: AlignedSegment, r2: AlignedSegment) -> int:
"""Computes the insert size for a pair of records."""
Expand Down
21 changes: 21 additions & 0 deletions fgpyo/sam/tests/test_supplementary_alignments.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from fgpyo.sam import Cigar
from fgpyo.sam import SupplementaryAlignment
from fgpyo.sam.builder import SamBuilder


def test_supplementary_alignment() -> None:
Expand Down Expand Up @@ -48,3 +49,23 @@ def test_format_supplementary_alignment() -> None:
for sa_string in ["chr1,123,-,100M50S,60,4", "chr1,123,+,100M50S,60,3"]:
sa = SupplementaryAlignment.parse(sa_string)
assert str(sa) == sa_string


def test_from_read() -> None:
"""Test that we can construct a SupplementaryAlignment from an AlignedSegment."""

builder = SamBuilder()

read = builder.add_single()
assert SupplementaryAlignment.from_read(read) == []

s1 = "chr1,123,+,50S100M,60,0"
s2 = "chr2,456,-,75S75M,60,1"
sa1 = SupplementaryAlignment("chr1", 122, True, Cigar.from_cigarstring("50S100M"), 60, 0)
sa2 = SupplementaryAlignment("chr2", 455, False, Cigar.from_cigarstring("75S75M"), 60, 1)

read = builder.add_single(attrs={"SA": f"{s1};"})
assert SupplementaryAlignment.from_read(read) == [sa1]

read = builder.add_single(attrs={"SA": f"{s1};{s2};"})
assert SupplementaryAlignment.from_read(read) == [sa1, sa2]

0 comments on commit a6d52a3

Please sign in to comment.