Skip to content

Commit

Permalink
feat: make OverlapDetector iterable (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
nh13 authored Jun 27, 2023
1 parent 9a7b0a7 commit ba47eba
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
13 changes: 10 additions & 3 deletions pybedlite/overlap_detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,18 @@
a set of genomic regions and another genomic region
"""

import attr
import cgranges as cr
import itertools
from pathlib import Path
from typing import Dict
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Optional
from typing import Set

import attr
import cgranges as cr

from pybedlite.bed_record import BedStrand
from pybedlite.bed_source import BedSource

Expand Down Expand Up @@ -98,7 +101,7 @@ def length(self) -> int:
return self.end - self.start


class OverlapDetector:
class OverlapDetector(Iterable[Interval]):
"""Detects and returns overlaps between a set of genomic regions and another genomic region.
Since :class:`~samwell.overlap_detector.Interval` objects are used both to populate the
Expand All @@ -117,6 +120,10 @@ def __init__(self) -> None:
self._refname_to_indexed: Dict[str, bool] = {}
self._refname_to_intervals: Dict[str, List[Interval]] = {}

def __iter__(self) -> Iterator[Interval]:
"""Iterates over the intervals in the overlap detector."""
return itertools.chain(*self._refname_to_intervals.values())

def add(self, interval: Interval) -> None:
"""Adds an interval to this detector.
Expand Down
14 changes: 14 additions & 0 deletions pybedlite/tests/test_overlap_detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,17 @@ def test_get_enclosed() -> None:
assert detector.get_enclosed(Interval("1", 16, 20)) == [c]
assert detector.get_enclosed(Interval("1", 15, 19)) == [c]
assert detector.get_enclosed(Interval("1", 10, 99)) == [b, c, d]


def test_iterable() -> None:
a = Interval("1", 1, 250)
b = Interval("1", 5, 30)
c = Interval("1", 10, 99)
d = Interval("1", 15, 19)
e = Interval("1", 16, 20)

detector = OverlapDetector()
detector.add_all([a])
assert list(detector) == [a]
detector.add_all([a, b, c, d, e])
assert list(detector) == [a, a, b, c, d, e]

0 comments on commit ba47eba

Please sign in to comment.