Skip to content

Instantly share code, notes, and snippets.

@arq5x
Created April 26, 2014 16:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arq5x/11324587 to your computer and use it in GitHub Desktop.
Save arq5x/11324587 to your computer and use it in GitHub Desktop.
import sys
class Line(object):
def __init__(self, line):
self.fields = line.split('\t')
self.chrom = self.fields[0]
self.start = int(self.fields[1])
self.end = int(self.fields[2])
self.depth = int(self.fields[3])
"""
C8628693 0 1 0
C8628693 1 2 0
C8628693 2 3 0
C8628693 3 4 1
C8628693 4 5 1
C8628693 5 6 2
C8628693 6 7 2
C8628693 7 8 2
C8628693 8 9 2
"""
prev = None
min_start = None
max_end = None
for line in sys.stdin:
curr = Line(line)
if prev is None:
min_start = curr.start
prev = curr
continue
# depth change. report BEDGRAPH
if curr.chrom == prev.chrom and \
curr.depth != prev.depth:
print prev.chrom, min_start, max_end, prev.depth
min_start = curr.start
max_end = curr.end
# same chrom and depth. update max_end
elif curr.chrom == prev.chrom and \
curr.depth == prev.depth:
max_end = curr.end
# chromosome change. report then reset
elif curr.chrom != prev.chrom:
print prev.chrom, min_start, max_end, prev.depth
min_start = curr.start
max_end = curr.end
prev = curr
# handle the final block in the file.
print prev.chrom, min_start, max_end, prev.depth
cat test.txt | python pos_to_bedgraph.py
C8628693 0 3 0
C8628693 3 5 1
C8628693 5 9 2
D8628693 0 3 0
D8628693 3 5 1
D8628693 5 9 2
C8628693 0 1 0
C8628693 1 2 0
C8628693 2 3 0
C8628693 3 4 1
C8628693 4 5 1
C8628693 5 6 2
C8628693 6 7 2
C8628693 7 8 2
C8628693 8 9 2
D8628693 0 1 0
D8628693 1 2 0
D8628693 2 3 0
D8628693 3 4 1
D8628693 4 5 1
D8628693 5 6 2
D8628693 6 7 2
D8628693 7 8 2
D8628693 8 9 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment