-
Notifications
You must be signed in to change notification settings - Fork 0
/
intervals_to_ucsc_catalog.py
executable file
·405 lines (328 loc) · 11.5 KB
/
intervals_to_ucsc_catalog.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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#!/usr/bin/env python
"""
Convert genomic intervals to an html "catalog" for controlling the UCSC browser.
"""
from sys import argv,stdin,stdout,stderr,exit
from math import ceil
try: from hashlib import md5 as md5_new
except ImportError: from md5 import new as md5_new
def usage(s=None):
message = """
usage: cat <intervals> | intervals_to_ucsc_catalog [options]
<filename1> (usually required) file to write frame holder to
<filename2> (required) file to write catalog frame to
--catalogonly don't create a frame holder
--url=<text> base URL the catalog frame will reside at
(default is "current directory")
--title=<text> title for catalog frame
--browser=<text> base URL the genome browser
(default is http://genome.ucsc.edu/cgi-bin)
--genome=<name> reference genome
(default is hg19)
--expand=<ratio> (cumulative) add link to view intervals, expanded
--center=<width> (cumulative) add link to view intervals, centered
--names[=<length>] assign hash-based names to the intervals
--show:numbers number the intervals
--show:comments show any comments for each interval
--framesplit=<fraction> catalog/content frame split
--origin=one input intervals are origin-one, closed
--origin=zero input intervals are origin-zero, half-open
(this is the default)
--head=<number> limit the number of input intervals"""
if (s == None): exit (message)
else: exit ("%s%s" % (s,message))
def main():
global frameTitle,catalogUrl
global browserUrlBase,refGenome
global nameLength
global frameSplit
global commentsSeparator
global debug
# parse args
holderFilename = None
catalogFilename = None
catalogOnly = False
catalogUrlBase = None
frameTitle = None
browserUrlBase = "http://genome.ucsc.edu/cgi-bin"
refGenome = "hg19"
expansionSpecs = []
nameLength = None
showNumbers = False
showComments = False
commentsSeparator = None
frameSplit = (20,80)
origin = "zero"
headLimit = None
debug = []
for arg in argv[1:]:
if ("=" in arg):
argVal = arg.split("=",1)[1]
if (arg.startswith("--title=")):
frameTitle = argVal
elif (arg.startswith("--url=")):
catalogUrlBase = argVal
if (catalogUrlBase.endswith("/")): catalogUrlBase = catalogUrlBase[:-1]
elif (arg == "--catalogonly"):
catalogOnly = True
elif (arg.startswith("--browser=")):
browserUrlBase = argVal
if (browserUrlBase.endswith("/")): browserUrlBase = browserUrlBase[:-1]
elif (arg.startswith("--genome=")):
refGenome = argVal
elif (arg.startswith("--expand=")) or (arg.startswith("--expansion=")):
try: expansionRatio = int(argVal)
except ValueError: expansionRatio = float(argVal)
expansionSpecs += [("ratio",expansionRatio,argVal)]
elif (arg.startswith("--center=")):
expansionWidth = int_with_units(argVal)
expansionSpecs += [("center",expansionWidth,argVal)]
elif (arg == "--names"):
nameLength = 3
elif (arg == "--show:numbers"):
showNumbers = True
elif (arg == "--show:comments"):
showComments = True
commentsSeparator = None
elif (arg.startswith("--show:comments=")):
showComments = True
commentsSeparator = argVal
elif (arg.startswith("--framesplit=")) or (arg.startswith("--split=")):
if (argVal.endswith("%")):
f = float(argVal[:-1]) / 100
elif ("," in argVal):
(n,d) = argVal.split(",")
(n,d) = (float(n),float(d))
f = n / (n+d)
elif ("/" in argVal):
(n,d) = argVal.split("/")
(n,d) = (float(n),float(d))
f = n / d
else:
f = float(argVal)
f = int(round(100*f))
f = min(max(f,10),90)
frameSplit = (f,100-f)
elif (arg.startswith("--names=")):
nameLength = int(argVal)
nameLength = max( 3,nameLength)
nameLength = min(10,nameLength)
elif (arg.startswith("--head=")):
headLimit = int_with_units(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)
elif (holderFilename == None):
holderFilename = arg
elif (catalogFilename == None):
catalogFilename = arg
else:
usage("unrecognized option: %s" % arg)
if (catalogOnly):
if (catalogFilename != None):
usage("you can't give me the name of the frame holder file with --catalogonly")
(holderFilename,catalogFilename) = (None,holderFilename)
if (not catalogOnly) and (holderFilename == None):
usage("you have to give me the names of the frame holder and catalog frame files")
if (catalogFilename == None):
usage("you have to give me the name of the catalog frame file")
if (frameTitle == None): frameTitle = "(no title)"
# process the intervals
if (holderFilename != None): holderF = file(holderFilename,"wt")
else: holderF = None
catalogF = file(catalogFilename,"wt")
if (catalogUrlBase == None): catalogUrl = catalogFilename.split("/")[-1]
else: catalogUrl = catalogUrlBase + "/" + catalogFilename.split("/")[-1]
intervalsPrinted = False
iChrom = None
intervalNum = 0
for (chrom,start,end,comment) in read_intervals(stdin,origin=origin):
intervalNum += 1
if (headLimit != None) and (intervalNum > headLimit):
print >>stderr, "limit of %s intervals reached" % (commatize(headLimit))
break
if (not intervalsPrinted):
intervalsPrinted = True
print >>catalogF, interval_frame_head()
if (iChrom == None):
(iChrom,iStart,iEnd) = (chrom,start,end)
if (showNumbers): number = str(intervalNum)
else: number = None
if (not showComments): comment = None
elif (comment == None): comment = ""
print >>catalogF, link_to_interval(chrom,start,end,number,comment,
expansions=expansionSpecs)
if (intervalsPrinted):
print >>catalogF, interval_frame_tail()
if (holderF != None): print >>holderF, frame_holder(iChrom,iStart,iEnd)
if (holderF != None): holderF.close()
catalogF.close()
def frame_holder(iChrom,iStart,iEnd):
intervalName = "%s:%d-%d" % (iChrom,iStart+1,iEnd)
url = browserUrlBase \
+ "/hgTracks?" \
+ "db=" + refGenome \
+ "&position=%s" % intervalName
lines = []
lines += ["<html><head><title>%s</title></head>" % frameTitle]
lines += ["<frameset cols=\"%d%%,%d%%\">" % (frameSplit[0],frameSplit[1])]
lines += [" <frame name=\"catalog\" src=\"%s\">" % catalogUrl]
lines += [" <frame name=\"browser\" src=\"%s\">" % url]
lines += ["</frameset>"]
lines += ["</html>"]
return "\n".join(lines)
def interval_frame_head():
lines = []
lines += ["<html>"]
lines += ["<head>"]
lines += ["<title>"]
lines += [frameTitle]
lines += ["</title>"]
lines += ["</head>"]
lines += [""]
lines += ["<table border cellpadding=\"1\">"]
return "\n".join(lines)
def interval_frame_tail():
lines = []
lines += ["</table>"]
lines += [""]
lines += ["</body>"]
lines += ["</html>"]
return "\n".join(lines)
def link_to_interval(chrom,start,end,number,comment,expansions=None):
if (expansions == None): expansions = []
intervalString = "%s:%s-%s" % (chrom,commatize(start+1),commatize(end))
url = browserUrlBase \
+ "/hgTracks?" \
+ "db=" + refGenome \
+ "&position=%s%%3A%d-%d" % (chrom,start+1,end)
fields = []
# add number
if (number != None):
fields += ["<a href=\"%s\" target=browser>%s</a>" % (url,number)]
# add name
if (nameLength != None):
hashVal = md5_new()
hashVal.update(intervalString)
hashVal = md5_to_value(hashVal.hexdigest()[:25],26**nameLength)
fakeName = value_to_name(hashVal,nameLength)
if ("md5" in debug):
print >>stderr, "%s -> %d -> %s" % (intervalString,hashVal,fakeName)
fields += ["<a href=\"%s\" target=browser>%s</a>" % (url,fakeName)]
# add primary interval link
fields += ["<a href=\"%s\" target=browser>%s</a>" % (url,intervalString)]
# add expanded interval link(s)
for expansion in expansions:
if (expansion[0] == "ratio"):
(_,ratio,ratioStr) = expansion
mid = (start+end) / 2
exStart = int(mid + ((start - mid) * ratio))
exEnd = int(mid + ((end - mid) * ratio))
if (exStart < 0): exStart = 0
exUrl = browserUrlBase \
+ "/hgTracks?" \
+ "db=" + refGenome \
+ "&position=%s%%3A%d-%d" % (chrom,exStart+1,exEnd)
fields += ["<a href=\"%s\" target=browser>zoom out %sx</a>" % (exUrl,ratioStr)]
if (expansion[0] == "center"):
(_,width,widthStr) = expansion
mid = (start+end) / 2
length = end - start
excess = length - width
exEnd = end - excess/2
exStart = max(0,exEnd-width)
if (exStart < 0): exStart = 0
exUrl = browserUrlBase \
+ "/hgTracks?" \
+ "db=" + refGenome \
+ "&position=%s%%3A%d-%d" % (chrom,exStart+1,exEnd)
fields += ["<a href=\"%s\" target=browser>%s @ %s:%s</a>" \
% (exUrl,widthStr,chrom,mid)]
# add comment
if (comment != None):
if (commentsSeparator != None):
comment = comment.split(commentsSeparator)
comment = "\n".join([c.strip() for c in comment])
fields += [comment]
return "<tr>" + "".join(["<td>%s</td>" % s for s in fields]) + "</tr>"
def md5_to_value(s,modulus=None):
v = int(s,16)
if (modulus != None):
v %= modulus
return v
def value_to_name(val,numLetters):
name = []
for ix in xrange(numLetters):
letter = val % 26
val = val / 26
name += [chr(ord("a") + letter)]
name.reverse()
return "".join(name)
def read_intervals(f,origin="zero"):
columnsNeeded = 3
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)
try:
chrom = fields[0]
start = int(fields[1])
end = int(fields[2])
if (end < start): raise ValueError
if (origin == "one"): start -= 1
comment = None
if (len(fields) > 3) and (fields[3].startswith("#")):
comment = " ".join(fields[3:])[1:]
except ValueError:
assert (False), "bad line (%d): %s" % (lineNumber,line)
yield (chrom,start,end,comment)
# parse a string as an integer, allowing units (e.g. "3.2M")
def int_with_units(s):
if (s.endswith("K")):
multiplier = 1000
s = s[:-1]
elif (s.endswith("M")):
multiplier = 1000 * 1000
s = s[:-1]
elif (s.endswith("G")):
multiplier = 1000 * 1000 * 1000
s = s[:-1]
else:
multiplier = 1
try: return int(s) * multiplier
except ValueError: return int(ceil(float(s) * multiplier))
# commatize--
# Convert a numeric string into one with commas.
def commatize(s):
if (type(s) != str): s = str(s)
(prefix,val,suffix) = ("",s,"")
if (val.startswith("-")): (prefix,val) = ("-",val[1:])
if ("." in val):
(val,suffix) = val.split(".",1)
suffix = "." + suffix
try: int(val)
except: return s
digits = len(val)
if (digits > 3):
leader = digits % 3
chunks = []
if (leader != 0):
chunks += [val[:leader]]
chunks += [val[ix:ix+3] for ix in xrange(leader,digits,3)]
val = ",".join(chunks)
return prefix + val + suffix
if __name__ == "__main__": main()