Skip to content

Commit

Permalink
support for BedTool creation with tuples/lists
Browse files Browse the repository at this point in the history
  • Loading branch information
daler committed Mar 28, 2012
1 parent 98bf552 commit 4c12cee
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
7 changes: 4 additions & 3 deletions pybedtools/bedtool.py
Original file line number Diff line number Diff line change
Expand Up @@ -850,13 +850,14 @@ def __iter__(self):
# gets passed to create_interval_from_fields.
return IntervalIterator(self.fn)

# Otherwise assume fn is already an iterable
else:
if isinstance(self.fn, (IntervalIterator, IntervalFile)):
return self.fn

return IntervalIterator(self.fn)

@property
def intervals(self):
return IntervalFile(self.fn)
return iter(self)

def __repr__(self):
if isinstance(self.fn, file):
Expand Down
25 changes: 22 additions & 3 deletions pybedtools/cbedtools.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -574,16 +574,28 @@ cdef list bed_vec2list(vector[BED] bv):
def overlap(int s1, int s2, int e1, int e2):
return min(e1, e2) - max(s1, s2)


cdef class IntervalIterator:
cdef object stream
cdef int _isstring
def __init__(self, stream):
self.stream = stream

# For speed, check int rather than call isinstance().
# -1 is unset, 0 assumes list/tuple/iterable, and 1 is a string.
#
# Also assumes that all items in the iterable `stream` are the same
# type...this seems like a reasonable assumption.
self._isstring = -1

def __iter__(self):
return self
def __next__(self):
while True:
try:
line = self.stream.next()
if self._isstring < 0:
self._isstring = int(isinstance(line, basestring))

# If you only trap StopIteration, for some reason even after
# raising a new StopIteration it goes back to the top of the
Expand All @@ -597,13 +609,20 @@ cdef class IntervalIterator:
pass
raise StopIteration
break
if line.startswith(('@', '#', 'track', 'browser')):
continue

if self._isstring:
if line.startswith(('@', '#', 'track', 'browser')):
continue
break
fields = line.rstrip('\r\n').split('\t')

if self._isstring:
fields = line.rstrip('\r\n').split('\t')
else:
fields = map(str, line)
return create_interval_from_list(fields)



cdef class IntervalFile:
cdef BedFile *intervalFile_ptr
cdef bint _loaded
Expand Down

0 comments on commit 4c12cee

Please sign in to comment.