Skip to content

Commit a6d52a3

Browse files
committed
feat: add SupplementaryAlignment constructor from read
1 parent 0c5d6ff commit a6d52a3

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

fgpyo/sam/__init__.py

+10
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,15 @@ 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+
"""Returns a list of SupplementaryAlignments for a given pysam.AlignedSegment."""
582+
if read.has_tag("SA"):
583+
sa_tag: str = cast(str, read.get_tag("SA"))
584+
return SupplementaryAlignment.parse_sa_tag(sa_tag)
585+
else:
586+
return []
587+
578588

579589
def isize(r1: AlignedSegment, r2: AlignedSegment) -> int:
580590
"""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)