Skip to content

Commit

Permalink
Add a method for progress logging templates
Browse files Browse the repository at this point in the history
  • Loading branch information
clintval committed Dec 23, 2024
1 parent 017dbc2 commit c5791a1
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
19 changes: 19 additions & 0 deletions fgpyo/util/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@

from pysam import AlignedSegment

from fgpyo.sam import Template

# Global that is set to True once logging initialization is run to prevent running > once.
__FGPYO_LOGGING_SETUP: bool = False

Expand Down Expand Up @@ -163,6 +165,23 @@ def record_alignment(
else:
return self.record(rec.reference_name, rec.reference_start + 1)

def record_template(
self,
template: Template,
) -> bool:
"""Correctly record all records in a fgpyo.sam.Template (zero-based coordinates).
Args:
template: fgpyo.sam.Template objects
Returns:
true if a message was logged, false otherwise
"""
logged_message: bool = False
for rec in template.all_recs():
logged_message = self.record_alignment(rec) or logged_message
return logged_message

def _log(
self,
refname: Optional[str] = None,
Expand Down
40 changes: 40 additions & 0 deletions tests/fgpyo/util/test_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import pytest

from fgpyo import sam
from fgpyo.sam import Template
from fgpyo.sam.builder import SamBuilder
from fgpyo.util.logging import ProgressLogger

Expand Down Expand Up @@ -59,3 +60,42 @@ def test_record_alignment_mapped_record(record: pysam.AlignedSegment) -> None:

# Assert record is logged
assert progress.record_alignment(rec=record) is True


def test_record_template() -> None:
builder: SamBuilder = SamBuilder()
(r1, r2) = builder.add_pair(name="x", chrom="chr1", start1=1, start2=2)
(r1_secondary, r2_secondary) = builder.add_pair(name="x", chrom="chr1", start1=10, start2=12)
r1_secondary.is_secondary = True
r2_secondary.is_secondary = True
(r1_supplementary, r2_supplementary) = builder.add_pair(
name="x", chrom="chr1", start1=4, start2=6
)
r1_supplementary.is_supplementary = True
r2_supplementary.is_supplementary = True

template = Template.build(builder.to_unsorted_list())
expected = Template(
name="x",
r1=r1,
r2=r2,
r1_secondaries=[r1_secondary],
r2_secondaries=[r2_secondary],
r1_supplementals=[r1_supplementary],
r2_supplementals=[r2_supplementary],
)

assert template == expected

# Define instance of ProgressLogger
actual: list[str] = []

progress = ProgressLogger(
printer=lambda rec: actual.append(rec), noun="record(s)", verb="recorded", unit=1
)

# Assert record is logged
assert progress.record_template(template=expected) is True

# Assert every record was logged
assert len(actual) == 6

0 comments on commit c5791a1

Please sign in to comment.