-
Notifications
You must be signed in to change notification settings - Fork 0
/
fill_genomic_interval_gaps.py
executable file
·167 lines (125 loc) · 4.2 KB
/
fill_genomic_interval_gaps.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
#!/usr/bin/env python
from sys import argv,stdin,stderr,exit
def usage(s=None):
message = """
usage: cat intervals | fill_genomic_interval_gaps [options] > intervals
--chromosomes=<filename> read chromosome names and lengths from a file
--origin=0 intervals are origin-zero, half-open (default)
--origin=1 intervals are origin-one, closed"""
if (s == None): exit (message)
else: exit ("%s\n%s" % (s,message))
def main():
global debug
# parse the command line
chromsFilename = None
origin = "zero"
debug = []
for arg in argv[1:]:
if ("=" in arg):
argVal = arg.split("=",1)[1].strip()
if (arg.startswith("--chromosomes=")) or (arg.startswith("--chroms=")):
chromsFilename = argVal
elif (arg.startswith("--origin=")):
origin = argVal
if (origin == "0"): origin = "zero"
if (origin == "1"): origin = "one"
assert (origin in ["zero","one"]), "can't understand %s" % arg
elif (arg == "--debug"):
debug += ["debug"]
elif (arg.startswith("--debug=")):
debug += argVal.split(",")
elif (arg.startswith("--")):
usage("unrecognized option: %s" % arg)
else:
usage("unrecognized option: %s" % arg)
if (chromsFilename == None):
usage("you have to give me a chromosome lengths file")
# read the chromosome lengths file
chromToLength = {}
chroms = []
f = file(chromsFilename,"rt")
for (chrom,length) in name_and_length(f):
assert (chrom not in chromToLength), \
"%s occurs twice in %s" % (chrom,lengthsFile)
chromToLength[chrom] = length
chroms += [chrom]
f.close()
# process the intervals
chromToIntervals = {}
for (chrom,start,end,val) in read_intervals(stdin,origin=origin):
if (chrom not in chromToIntervals):
assert (chrom in chromToLength), \
"%s is in input but not in %s" % (chrom,lengthsFile)
chromToIntervals[chrom] = []
chromToIntervals[chrom] += [(start,end,val)]
for chrom in chroms:
if (chrom not in chromToIntervals):
start = 0
if (origin == "one"): start += 1
print "%s\t%d\t%d\t%s" % (chrom,start,chromToLength[chrom],"0")
continue
intervals = chromToIntervals[chrom]
intervals.sort()
prevEnd = 0
for (start,end,val) in intervals:
if (start < prevEnd):
if (origin == "one"): start += 1
assert (False), "overlapping intervals on %s: ?-%d and %d-%d" \
% (chrom,prevEnd,start,end)
if (prevEnd < start):
if (origin == "one"): prevEnd += 1
print "%s\t%d\t%d\t%s" % (chrom,prevEnd,start,"0")
if (origin == "one"): start += 1
print "%s\t%d\t%d\t%s" % (chrom,start,end,val)
prevEnd = end
if (prevEnd < chromToLength[chrom]):
if (origin == "one"): prevEnd += 1
print "%s\t%d\t%d\t%s" % (chrom,prevEnd,chromToLength[chrom],"0")
# returns the next interval as (chrom,start,end)
def read_intervals(f,origin="zero"):
columnsNeeded = 3
numFields = None
lineNumber = 0
for line in f:
lineNumber += 1
line = line.strip()
if (line == ""): continue
if (line.startswith("#")): continue
fields = line.split()
assert (len(fields) >= columnsNeeded), \
"not enough fields at line %d (%d, expected at least %d)" \
% (lineNumber,len(fields),columnsNeeded)
if (numFields == None):
numFields = len(fields)
else:
assert (len(fields) == numFields), \
"inconsistent number of fields at line %d (%d, expected %d)" \
% (lineNumber,len(fields),numFields)
try:
chrom = fields[0]
start = int(fields[1])
end = int(fields[2])
if (numFields < 4): val = 1
else: val = float(fields[3])
if (end < start): raise ValueError
if (origin == "one"): start -= 1
except ValueError:
assert (False), "bad line (%d): %s" % (lineNumber,line)
yield (chrom,start,end,val)
# yields the next name,length pair
def name_and_length(f):
lineNumber = 0
for line in f:
lineNumber += 1
line = line.strip()
fields = line.split()
assert (len(fields) == 2), \
"inconsistent number of fields at line %d (%d, expected %d)" \
% (lineNumber,len(fields),2)
try:
name = fields[0]
length = int(fields[1])
except ValueError:
assert (False), "bad length at line %d\n%s" % (lineNumber,line)
yield (name,length)
if __name__ == "__main__": main()