Skip to content

Commit

Permalink
Adding initial batch of samtools type hinted wrapper functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Nathan Roach committed Jan 3, 2023
1 parent 299cc7c commit 015aa54
Show file tree
Hide file tree
Showing 6 changed files with 1,187 additions and 94 deletions.
9 changes: 5 additions & 4 deletions fgpyo/sam/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,13 +197,14 @@ class SamFileType(enum.Enum):
ext (str): The standard file extension for this file type.
"""

def __init__(self, mode: str, ext: str) -> None:
def __init__(self, mode: str, ext: str, index_ext: Optional[str]) -> None:
self.mode = mode
self.extension = ext
self.index_extension = index_ext

SAM = ("", ".sam")
BAM = ("b", ".bam")
CRAM = ("c", ".cram")
SAM = ("", ".sam", None)
BAM = ("b", ".bam", ".bai")
CRAM = ("c", ".cram", ".crai")

@classmethod
def from_path(cls, path: Union[Path, str]) -> "SamFileType":
Expand Down
23 changes: 9 additions & 14 deletions fgpyo/sam/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from pysam import AlignmentHeader

from fgpyo import sam
from fgpyo import samtools
from fgpyo.sam import SamOrder


Expand Down Expand Up @@ -544,7 +545,7 @@ def to_path(

with NamedTemporaryFile(suffix=".bam", delete=True) as fp:
file_handle: IO
if self.sort_order is SamOrder.Unsorted:
if self.sort_order in [SamOrder.Unsorted, SamOrder.Unknown]:
file_handle = path.open("w")
else:
file_handle = fp.file
Expand All @@ -555,20 +556,14 @@ def to_path(
for rec in self._records:
if pred(rec):
writer.write(rec)

default_samtools_opt_list = ["-o", str(path), fp.name]

file_handle.close()
if self.sort_order == SamOrder.QueryName:
# Ignore type hints for now until we have wrappers to use here.
pysam.sort(*(["-n"] + default_samtools_opt_list)) # type: ignore
elif self.sort_order == SamOrder.Coordinate:
# Ignore type hints for now until we have wrappers to use here.
pysam.sort(*default_samtools_opt_list) # type: ignore
if index:
# Ignore type hints for now until we have wrappers to use here.
pysam.index(str(path)) # type: ignore

if self.sort_order not in [SamOrder.Unsorted, SamOrder.Unknown]:
samtools.sort(
input=Path(fp.name),
output=path,
index_output=index,
sort_order=self.sort_order,
)
return path

def __len__(self) -> int:
Expand Down
Loading

0 comments on commit 015aa54

Please sign in to comment.