-
Notifications
You must be signed in to change notification settings - Fork 6
/
query
executable file
·702 lines (594 loc) · 23.5 KB
/
query
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
#!/usr/bin/env python2.7
# A beacon allows very limited queries against a set of variants without allowing someone
# to download the list of variants
# see ga4gh.org/#/beacon (UCSC redmine 14393)
import cgi, subprocess, sys, cgitb, os, socket, time, json, glob, urlparse, time
import sqlite3, gzip, optparse, gc, string, re, socket
from os.path import join, isfile, dirname, isdir, basename
cherryPyLoaded = False
try:
import cherrypy
cherryPyLoaded = True
except:
pass # in case user hasn't installed cherrypy
# current host name, if running as a CGI
hostName = os.environ.get("HTTP_HOST", "localhost")
# cache of hg.conf dict
hgConf = None
# descriptions of datasets that this beacon is serving
DataSetDescs = {
"hgmd" : "Human Genome Variation Database, only single-nucleotide variants, public version, provided by Biobase",
"lovd" : "Leiden Open Varation Database installations that agreed to share their variants, only single-nucleotide variants and deletions",
"test" : "small test data on Chromosome 1, from ICGC",
"test2" : "another piece of test data from Chromosome 1, also from ICGC"
}
# special case: same datasets do not have alt alleles. In this case, an overlap is enough to trigger a "true"
NoAltDataSets = ["hgmd"]
def queryBottleneck(host, port, ip):
" contact UCSC-style bottleneck server to get current delay time "
# send ip address
s = socket.socket()
s.connect((host, int(port)))
msg = ip
d = chr(len(msg))+msg
s.send(d)
# read delay time
expLen = ord(s.recv(1))
totalLen = 0
buf = list()
while True:
resp = s.recv(1024)
buf.append(resp)
totalLen+= len(resp)
if totalLen==expLen:
break
return int("".join(buf))
def parseConf(fname):
" parse a hg.conf style file, return as dict key -> value (both are strings) "
conf = {}
for line in open(fname):
line = line.strip()
if line.startswith("#"):
continue
elif line.startswith("include "):
inclFname = line.split()[1]
inclPath = join(dirname(fname), inclFname)
if isfile(inclPath):
inclDict = parseConf(inclPath)
conf.update(inclDict)
elif "=" in line: # string search for "="
key, value = line.split("=")
conf[key] = value
return conf
def parseHgConf(confDir="."):
""" return beacon.conf or alternatively hg.conf as dict key:value """
global hgConf
if hgConf is not None:
return hgConf
hgConf = dict() # python dict = hash table
currDir = dirname(__file__)
fname = join(currDir, confDir, "beacon.conf")
if not isfile(fname):
fname = join(currDir, confDir, "hg.conf")
if not isfile(fname):
fname = join(currDir, "hg.conf")
if not isfile(fname):
return {}
hgConf = parseConf(fname)
return hgConf
def jsonErrMsg(errMsg=None):
" wrap error message into a JSON dict "
if errMsg == None:
sys.exit(0)
helpUrl = getBeaconDesc()["homepage"]
ret = {"errormsg":errMsg,
"more_info":"for a complete description of the parameters, read the help message at %s" % helpUrl}
return json.dumps(ret, indent=4, sort_keys=True,separators=(',', ': '))
def makeHelp():
" return help text to as a string "
lines = []
lines.append( "<html><body>" )
host = hostName # convert from global to local var
if host.endswith(".ucsc.edu"):
helpDir = "/gbdb/hg19/beacon"
else:
helpDir = dirname(__file__)
helpPath = join(helpDir, "help.txt")
if not isfile(helpPath):
return jsonErrMsg("no file %s found. The beacon is not activated on this machine" % helpPath)
helpText = open(helpPath).read()
lines.append( helpText % locals() )
lines.append( "</body></html>" )
return "\n".join(lines)
def dataSetResources():
" Returns the list of DataSetResources "
totalSize = 0
dsrList = []
for refDb in getBeaconRefs():
conn = dbOpen(refDb, mustExist=True)
if conn==None:
continue
for tableName in dbListTables(conn):
rows = dbQuery(conn, "SELECT COUNT(*) from %s" % tableName, None)
itemCount = rows[0][0]
# the dataset ID is just the file basename without extension
dsId = tableName
dsr = (dsId, DataSetDescs.get(dsId, ""), itemCount)
dsrList.append(dsr)
totalSize += itemCount
return totalSize, dsrList
def getBeaconDesc():
" return beaconDesc dict, built from beacon.conf "
parseHgConf()
# default values are set so the beacon works as part of
# a UCSC mirror installation without any config file
homepage = "http://%s/cgi-bin/hgBeacon" % hostName
beaconDesc = {
"id":hgConf.get("beacon-id", "ucsc-browser"), \
"name":hgConf.get("beacon-name", "Genome Browser"), \
"organization" : hgConf.get("beacon-org", "UCSC"), \
"description" : hgConf.get("beacon-desc", "UCSC Genome Browser"),
"api" : "0.2",
"homepage": hgConf.get("beacon-url", homepage),
}
return beaconDesc
def getBeaconRefs():
""" return the list of valid reference assemblies from beacon.conf """
parseHgConf()
return hgConf.get("beacon-refs", "GRCh37").split(",")
def beaconInfo():
" return a beaconInfo dict "
size, dsrList = dataSetResources()
if size==0:
return jsonErrMsg("This beacon is not serving any data. There are either no *.sqlite files in the beacon directory or they contain no data.")
return \
{
"beacon": getBeaconDesc(),
"references": getBeaconRefs(),
"datasets": dsrList,
"size": size
}
def makeJson(data):
" convert a dictionary to a JSON-encoded string "
return json.dumps(data, indent=4, sort_keys=True,separators=(',', ': '))
def hgBotDelay():
" implement bottleneck delay, get bottleneck server from hg.conf "
global hgConf
hgConf = parseHgConf()
if "bottleneck.host" not in hgConf:
return
ip = os.environ["REMOTE_ADDR"]
delay = queryBottleneck(hgConf["bottleneck.host"], hgConf["bottleneck.port"], ip)
if delay>10000:
time.sleep(delay/1000.0)
if delay>20000:
print("Blocked")
sys.exit(0)
class BeaconError(Exception):
def __init__(self, msg):
self.msg = msg
def checkParams(chrom, pos, allele, reference, track):
" make sure the parameters follow the spec "
# default is GRCh37 is not assembly has been provided
if reference==None or reference=="":
reference=getBeaconRefs()[0]
# make sure that the assembly is a valid one
if reference not in getBeaconRefs():
raise BeaconError("invalid 'reference' parameter, valid ones are %s" % ",".join(getBeaconRefs()))
# chrom is required
if chrom==None or chrom=="":
raise BeaconError("missing chromosome parameter")
# allele is required
if allele==None or allele=="":
raise BeaconError("missing allele parameter")
allele = allele.upper()
# allele can only be a DNA sequence (~SNP) or an indel
if not (re.compile("^[ACTG]+$").match(allele)!=None or \
re.compile("^I[ACTG]+$").match(allele)!=None or \
re.compile("^D[0-9]+$").match(allele)!=None):
raise("invalid allele parameter, can only be a [ACTG]+ or I[ACTG]+ or D[0-9]+")
if track is not None:
if not track.isalnum():
raise BeaconError("'dataset' parameter must contain only alphanumeric characters")
if len(track)>100:
raise BeaconError("'dataset' parameter must not be longer than 100 chars")
if pos==None or not pos.isdigit():
raise BeaconError("'position' parameter is not a number")
pos = int(pos)
# convert chrom to UCSC 'chr'+Num format
# we currently don't accept the new hg38 sequences
# -> is this a problem?
if chrom==None:
raise BeaconError( "missing chromosome parameter")
if not ((chrom.isdigit() and int(chrom)>=1 and int(chrom)<=22) or chrom in ["X","Y","M","test"]):
raise BeaconError( "invalid chromosome name %s" % chrom)
return chrom, pos, allele, reference, track
def lookupAllele(chrom, pos, allele, reference, dataset):
" check if an allele is present in a sqlite DB "
conn = dbOpen(reference, mustExist=True)
tableList = dbListTables(conn)
if dataset!=None:
if dataset not in tableList:
raise BeaconError("dataset %s is not present on this server" % dataset)
tableList = [dataset]
for tableName in tableList:
cur = conn.cursor()
if tableName in NoAltDataSets:
# some datasets don't have alt alleles, e.g. HGMD
sql = "SELECT * from %s WHERE chrom=? AND pos=?" % tableName
cur.execute(sql, (chrom, pos))
else:
sql = "SELECT * from %s WHERE chrom=? AND pos=? AND allele=?" % tableName
cur.execute(sql, (chrom, pos, allele))
row = cur.fetchone()
if row!=None:
return "true"
return "false"
def lookupAlleleJson(chrom, pos, altBases, refBases, reference, dataset):
" call lookupAllele and wrap the result into dictionaries "
chrom, pos, altBases, reference, dataset = checkParams(chrom, pos, altBases, reference, dataset)
exists = lookupAllele(chrom, pos, altBases, reference, dataset)
if chrom=="test" and pos==0:
exists = "true"
query = {
"alternateBases": altBases,
"referenceBases" : refBases,
"chromosome": chrom.replace("chr",""),
"position": pos,
"reference": reference,
"dataset": dataset
}
ret = {"beacon" : getBeaconDesc(), "query" : query, \
"response" : {"exists":exists} }
return ret
def main():
# detect if running under apache or was run from command line
if 'REQUEST_METHOD' in os.environ:
fqdn = socket.getfqdn()
if not (fqdn.startswith("hgw") and fqdn.endswith("ucsc.edu")) \
or fqdn.startswith("hgwdev."):
# enable special CGI error handler not on the RR, but on hgwdev
cgitb.enable()
mainCgi()
else:
mainCommandLine()
def parseArgs():
" parse command line options into args and options "
parser = optparse.OptionParser("""usage: %prog [options] [referenceDb] [datasetName] filename(s) - import VCF, complete genomics or BED files into the beacon database.
- parameter 'datasetName' is optional and defaults to 'defaultDataset'.
- any existing dataset of the same name will be overwritten
- the data is written to beaconData.sqlite. You can use 'sqlite3' to inspect the data file.
- the input file can be gzipped
""")
parser.add_option("-d", "--debug", dest="debug", \
action="store_true", help="show debug messages")
parser.add_option("-p", "--port", dest="port", \
action="store", type="int", help="start development \
server and listen on given port for queries")
parser.add_option("-f", "--format", dest="format", \
action="store", help="format of input file, one of vcf, lovd, \
hgmd, cga (=complete genomics). default %default", \
default = "vcf")
(options, args) = parser.parse_args()
if len(args)==0 and not options.port:
parser.print_help()
sys.exit(0)
return args, options
def dbMakeTable(conn, tableName):
" create an empty table with chrom/pos/allele fields "
conn.execute("DROP TABLE IF EXISTS %s" % tableName)
conn.commit()
_tableDef = (
'CREATE TABLE IF NOT EXISTS %s '
'('
' chrom text,' # chromosome
' pos int,' # start position, 0-based
' allele text' # alternate allele, can also be IATG = insertion of ATG or D15 = deletion of 15 bp
')')
conn.execute(_tableDef % tableName)
conn.commit()
#' PRIMARY KEY (chrom, pos, allele) '
def dbFileName(refDb):
" return name of database file "
dbDir = dirname(__file__) # directory where script is located
if hostName.endswith("ucsc.edu"): # data is not in CGI directory at UCSC
dbDir = "/gbdb/hg19/beacon/"
# sqlite database
dbName = "beaconData.%s.sqlite" % refDb
dbPath = join(dbDir, dbName)
return dbPath
def dbOpen(refDb, mustExist=False):
" open the sqlite db and return a DB connection object "
dbName = dbFileName(refDb)
if not isfile(dbName) and mustExist:
return None
conn = sqlite3.Connection(dbName)
return conn
def dbListTables(conn):
" return list of tables in sqlite db "
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
rows = cursor.fetchall()
tables = []
for row in rows:
tables.append(row[0])
return tables
def dbQuery(conn, query, params):
cursor = conn.cursor()
if params==None:
cursor.execute(query)
else:
cursor.execute(query, params)
return cursor.fetchall()
def readAllelesVcf(ifh):
""" read alleles in VCF file
return a list of chrom, pos, allele tuples
"""
doneData = set() # copy of all data, to check for duplicates
rows = []
skipCount = 0
emptyCount = 0
gc.disable()
for line in ifh:
if line.startswith("#"):
continue
fields = string.split(line.rstrip("\n"), "\t", maxsplit=5)
chrom, pos, varId, ref, alt = fields[:5]
if chrom.startswith("chr"):
chrom = chrom.replace("chr","")
pos = int(pos)-1 # VCF is 1-based, beacon is 0-based
if alt==".":
emptyCount += 1
continue
refIsOne = len(ref)==1
altIsOne = len(alt)==1
if refIsOne and altIsOne:
# single bp subst
beaconAllele = alt
elif not refIsOne and altIsOne:
# deletion
beaconAllele = "D"+str(len(ref)-1) # skip first nucleotide, VCF always adds one nucleotide
pos += 1
elif refIsOne and not altIsOne:
# insertion
beaconAllele = "I"+alt[1:]
pos += 1
elif not refIsOne and not altIsOne:
skipCount +=1
else:
print "Error: invalid VCF fields:", fields
sys.exit(1)
if len(rows) % 500000 == 0:
print "Read %d rows..." % len(rows)
dataRow = (chrom, pos, beaconAllele)
if dataRow in doneData:
continue
rows.append( dataRow )
doneData.add( dataRow )
print "skipped %d VCF lines with empty ALT alleles" % emptyCount
print "skipped %d VCF lines with both ALT and REF alleles len!=1, cannot encode as beacon queries" % skipCount
return rows
def readAllelesLovd(ifh):
""" read the LOVD bed file and return in format (chrom, pos, altAllele)
This function is only used internally at UCSC.
"""
alleles = []
count = 0
skipCount = 0
for line in ifh:
if line.startswith("chrom"):
continue
chrom, start, end, desc = line.rstrip("\n").split("\t")[:4]
if desc[-2]==">":
mutDesc = desc[-3:]
ref, _, alt = mutDesc
assert(len(mutDesc)==3)
elif desc.endswith("del"):
alt = "D"+str(int(end)-int(start))
else:
skipCount += 1
continue
chrom = chrom.replace("chr", "")
start = int(start)
alleles.append( (chrom, start, alt) )
print "read %d alleles, skipped %d non-SNV or del alleles" % (len(alleles), skipCount)
return list(set(alleles))
def readAllelesHgmd(ifh):
""" read the HGMD bed file and return in format (chrom, pos, altAllele).
This function is only used internally at UCSC.
"""
# chr1 2338004 2338005 PEX10:CM090797 0 2338004 2338005 PEX10 CM090797 substitution
alleles = []
count = 0
skipCount = 0
for line in ifh:
fields = line.rstrip("\n").split("\t")
chrom, start, end = fields[:3]
desc = fields[10]
start = int(start)
end = int(end)
if desc=="substitution":
assert(end-start==1)
alt = "*"
else:
skipCount += 1
continue
chrom = chrom.replace("chr", "")
alleles.append( (chrom, start, alt) )
print "read %d alleles, skipped %d non-SNV alleles" % (len(alleles), skipCount)
return list(set(alleles))
def readAllelesCga(ifh):
""" read a CGA variant file and return in format (chrom, pos, altAllele).
See http://blog.personalgenomes.org/2014/05/30/pgp-harvard-data-in-google-cloud-storage/
"""
# 5 2 all chr1 11085 11109 ref = =
# 300 2 1 chr1 22157 22158 snp A G 80 80 VQHIGH dbsnp.80:rs370187
alleles = []
count = 0
skipCount = 0
for line in ifh:
if line.startswith("#") or len(line)==1:
continue
fields = line.rstrip("\n").split("\t")
if fields[6]!="snp":
skipCount += 1
continue
chrom = fields[3].replace("chr", "")
start = int(fields[4])
end = int(fields[4])
ref = fields[7]
alt = fields[8]
alleles.append( (chrom, start, alt) )
print "read %d alleles, skipped %d non-SNP alleles" % (len(alleles), skipCount)
return sorted(list(set(alleles)))
def readAllelesBed(ifh):
""" read a bed file with the format chrom, start, end, allele
e.g. "chr1 889637 889638 C"
"""
alleles = []
count = 0
skipCount = 0
for line in ifh:
fields = line.rstrip("\n").split("\t")
chrom, start, end, alt = fields[:4]
start = int(start)
end = int(end)
if (end-start)!=1:
skipCount += 1
continue
chrom = chrom.replace("chr", "")
alleles.append( (chrom, start, alt) )
print "read %d alleles, skipped %d alleles with length <> 1-bp" % (len(alleles), skipCount)
return list(set(alleles))
def iterChunks(seq, size):
" yields chunks of at most size elements from seq "
for pos in range(0, len(seq), size):
yield seq[pos:pos + size]
def printTime(time1, time2, rowCount):
timeDiff = time2 - time1
print "Time: %f secs for %d rows, %d rows/sec" % (timeDiff, rowCount, rowCount/timeDiff)
def importFiles(refDb, fileNames, datasetName, format):
""" open the sqlite db, create a table datasetName and write the data in fileName into it """
conn = dbOpen(refDb)
dbMakeTable(conn, datasetName)
# try to make sqlite writes as fast as possible
conn.execute("PRAGMA synchronous=OFF")
conn.execute("PRAGMA count_changes=OFF") # http://blog.quibb.org/2010/08/fast-bulk-inserts-into-sqlite/
conn.execute("PRAGMA cache_size=800000") # http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html
conn.execute("PRAGMA journal_mode=OFF") # http://www.sqlite.org/pragma.html#pragma_journal_mode
conn.execute("PRAGMA temp_store=memory")
conn.commit()
# see http://stackoverflow.com/questions/1711631/improve-insert-per-second-performance-of-sqlite
# for background why I do it like this
print "Reading files %s into database table %s" % (",".join(fileNames), datasetName)
rowCount = 0
startTime = time.time()
alleles = []
for fileName in fileNames:
if fileName.endswith(".gz"):
ifh = gzip.open(fileName)
else:
ifh = open(fileName)
if format=="vcf":
alleles.extend(readAllelesVcf(ifh))
elif format=="lovd":
alleles.extend(readAllelesLovd(ifh))
elif format=="hgmd":
alleles.extend(readAllelesHgmd(ifh))
elif format=="cga":
alleles.extend(readAllelesCga(ifh))
elif format=="bed":
alleles.extend(readAllelesBed(ifh))
# remove duplicates and sort again
if len(fileNames)!=1:
alleles = list(set(alleles))
alleles.sort()
loadTime = time.time()
printTime(startTime, loadTime, len(alleles))
print "Loading alleles into database %s" % dbFileName(refDb)
for rows in iterChunks(alleles, 50000):
sql = "INSERT INTO %s (chrom, pos, allele) VALUES (?,?,?)" % datasetName
conn.executemany(sql, rows)
conn.commit()
rowCount += len(rows)
insertTime = time.time()
printTime(loadTime, insertTime, len(alleles))
print "Indexing database table"
conn.execute("CREATE UNIQUE INDEX '%s_index' ON '%s' ('chrom', 'pos', 'allele')" % \
(datasetName, datasetName))
indexTime = time.time()
printTime(insertTime, indexTime, len(alleles))
# define this class only if cherryPy is installed, as otherwise the @ line
# will trigger an error
if cherryPyLoaded:
class DevServer(object):
@cherrypy.expose
def query(self, chromosome=None, position=None, referenceBases=None, alternateBases=None, reference=None, dataset=None, format=None, allele=None):
if allele!=None:
alternateBases = allele
return beaconQuery(chromosome, position, referenceBases, alternateBases, reference, dataset, format)
@cherrypy.expose
def info(self):
return makeJson(beaconInfo())
def startDevServer(port):
" start the development webserver "
if not cherryPyLoaded:
print("You are trying to start the development webserver but the cherryPy directory cannot be found.")
print("You have to re-download or copy the beacon directory again from github or your source to this directory and include the cherryPy/ subdirectory.")
sys.exit(1)
cherrypy.config.update({'server.socket_port': port})
cherrypy.quickstart(DevServer())
sys.exit(0)
def mainCommandLine():
" main function if called from command line "
args, options = parseArgs()
if options.port:
startDevServer(options.port)
refDb = args[0]
datasetName = args[1]
fileNames = args[2:]
if len(args)<3:
print("You need to specify at least an assembly, a datasetName and one fileName to import")
sys.exit(1)
if refDb not in getBeaconRefs():
print ("The reference assembly '%s' is not valid." % refDb)
print ("Please specify one of these reference assemblies:")
print (",".join(getBeaconRefs()))
sys.exit(1)
importFiles(refDb, fileNames, datasetName, options.format)
def beaconQuery(chrom, pos, refBases, altBases, reference, dataset, format):
""" query the beacon, returns a JSON or text string """
if chrom==None and pos==None and altBases==None:
return makeHelp()
try:
ret = lookupAlleleJson(chrom, pos, altBases, refBases, reference, dataset)
if format=="text":
return ret["response"]["exists"]
else:
return makeJson(ret)
except BeaconError, ex:
return jsonErrMsg(ex.msg)
def mainCgi():
print "Content-Type: text/html\n"
url = os.environ["REQUEST_URI"]
parsedUrl = urlparse.urlparse(url)
# get CGI parameters
form = cgi.FieldStorage()
# react based on symlink that was used to call this script
page = parsedUrl[2].split("/")[-1] # last part of path is REST endpoint
if page=="info":
print makeJson(beaconInfo())
sys.exit(0)
hgBotDelay()
chrom = form.getfirst("chromosome")
pos = form.getfirst("position")
refBases = form.getfirst("referenceBases")
altBases = form.getfirst("alternateBases")
reference = form.getfirst("reference")
dataset = form.getfirst("dataset")
format = form.getfirst("format")
print beaconQuery(chrom, pos, refBases, altBases, reference, dataset, format)
if __name__=="__main__":
# deactivate this on the RR, but useful for debugging: prints a http header
# on errors
main()