Skip to content

Commit 94b3696

Browse files
authored
feat: add SupplementaryAlignment constructor from read (#85)
* feat: add SupplementaryAlignment constructor from read * refactor: use cls * doc: update docstring
1 parent d2578f1 commit 94b3696

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

fgpyo/sam/__init__.py

+19
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,7 @@
163163
from typing import Optional
164164
from typing import Tuple
165165
from typing import Union
166+
from typing import cast
166167

167168
import attr
168169
import pysam
@@ -575,6 +576,24 @@ def parse_sa_tag(tag: str) -> List["SupplementaryAlignment"]:
575576
"""
576577
return [SupplementaryAlignment.parse(a) for a in tag.split(";") if len(a) > 0]
577578

579+
@classmethod
580+
def from_read(cls, read: pysam.AlignedSegment) -> List["SupplementaryAlignment"]:
581+
"""
582+
Construct a list of SupplementaryAlignments from the SA tag in a pysam.AlignedSegment.
583+
584+
Args:
585+
read: An alignment. The presence of the "SA" tag is not required.
586+
587+
Returns:
588+
A list of all SupplementaryAlignments present in the SA tag.
589+
If the SA tag is not present, or it is empty, an empty list will be returned.
590+
"""
591+
if read.has_tag("SA"):
592+
sa_tag: str = cast(str, read.get_tag("SA"))
593+
return cls.parse_sa_tag(sa_tag)
594+
else:
595+
return []
596+
578597

579598
def isize(r1: AlignedSegment, r2: AlignedSegment) -> int:
580599
"""Computes the insert size for a pair of records."""

fgpyo/sam/tests/test_supplementary_alignments.py

+21
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from fgpyo.sam import Cigar
44
from fgpyo.sam import SupplementaryAlignment
5+
from fgpyo.sam.builder import SamBuilder
56

67

78
def test_supplementary_alignment() -> None:
@@ -48,3 +49,23 @@ def test_format_supplementary_alignment() -> None:
4849
for sa_string in ["chr1,123,-,100M50S,60,4", "chr1,123,+,100M50S,60,3"]:
4950
sa = SupplementaryAlignment.parse(sa_string)
5051
assert str(sa) == sa_string
52+
53+
54+
def test_from_read() -> None:
55+
"""Test that we can construct a SupplementaryAlignment from an AlignedSegment."""
56+
57+
builder = SamBuilder()
58+
59+
read = builder.add_single()
60+
assert SupplementaryAlignment.from_read(read) == []
61+
62+
s1 = "chr1,123,+,50S100M,60,0"
63+
s2 = "chr2,456,-,75S75M,60,1"
64+
sa1 = SupplementaryAlignment("chr1", 122, True, Cigar.from_cigarstring("50S100M"), 60, 0)
65+
sa2 = SupplementaryAlignment("chr2", 455, False, Cigar.from_cigarstring("75S75M"), 60, 1)
66+
67+
read = builder.add_single(attrs={"SA": f"{s1};"})
68+
assert SupplementaryAlignment.from_read(read) == [sa1]
69+
70+
read = builder.add_single(attrs={"SA": f"{s1};{s2};"})
71+
assert SupplementaryAlignment.from_read(read) == [sa1, sa2]

0 commit comments

Comments
 (0)