Skip to content

Commit

Permalink
feat: add SupplementaryAlignment constructor from read (#85)
Browse files Browse the repository at this point in the history
* feat: add SupplementaryAlignment constructor from read

* refactor: use cls

* doc: update docstring
  • Loading branch information
msto authored Feb 9, 2024
1 parent d2578f1 commit 94b3696
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
19 changes: 19 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,24 @@ 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"]:
"""
Construct a list of SupplementaryAlignments from the SA tag in a pysam.AlignedSegment.
Args:
read: An alignment. The presence of the "SA" tag is not required.
Returns:
A list of all SupplementaryAlignments present in the SA tag.
If the SA tag is not present, or it is empty, an empty list will be returned.
"""
if read.has_tag("SA"):
sa_tag: str = cast(str, read.get_tag("SA"))
return cls.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 94b3696

Please sign in to comment.