-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbeacon.py
executable file
·269 lines (224 loc) · 8.21 KB
/
beacon.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
#!flask/bin/python
'''
The MIT License
Copyright 2014 DNAstack.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
from flask import Flask, jsonify, request
import logging
from beacon2ga4gh import setup_ga4gh_client, check_reference_set, search_variants, fill_beacon
"""
If we want to add Oauth2 support then see the code example in this other beacon on top of
GA4GH example https://github.com/Genecloud/simplebeacon/blob/master/beacon_rp.py
"""
app = Flask(__name__)
#global GA4GH client lib
cl=""
########### QueryResource for beacon details ###############
# required field(s): allele, chromosome, position, reference
QueryResource = {
"allele": "C",
"chromosome": "22",
"position": 17669305,
"reference": "GRCh37",
'dataset_id': ""
}
################### Beacon details #########################
BeaconDataset = {
'id': u'',
'name': u'',
'description': u'',
'assemblyId': u'',
'createDateTime': u'',
'updateDateTime': u'',
'version':u'', #version of the beacon
'variantCount': -1,
'callCount': -1,
'sampleCount': -1,
'externalUrl': u'',
'info': u''
}
BeaconOrganization = {
'id': u'',
'name': u'',
'apiVersion': u'0.3',
'description': u'',
'address': u'',
'welcomeUrl': u'',
'contactUrl': u'',
'logoUrl': u'',
'info': u''
}
# required field(s): id, name, organization, api
Beacon = {
'id': u'',
'name': u'',
'apiVersion': u'0.3',
'BeaconOrganization': [
BeaconOrganization
],
'description': u'',
'version':u'', #version of the beacon
'welconeUrl': u'',
'alternativeUrl': u'',
'createDateTime': u'',
'updateDateTime': u'',
'datasets': [
BeaconDataset
],
'queries': [
QueryResource # Examples of interesting queries
],
'info': u''
}
# --------------- Information endpoint (end) ----------------------#
# info function
@app.route('/beacon/info', methods=['GET'])
def info():
return jsonify(Beacon)
# query function
@app.route('/beacon/query', methods=['GET'])
def query():
global cl
BeaconAlleleRequest = {
'referenceName': u'',
'start': u'',
'referenceBases': u'',
'alternateBases': u'',
'assemblyId': '',
'datasetIds': [],
'includeDatasetResponse': False,
}
BeaconDatasetAlleleResponse = {
'datasetId': u'',
'exists': u'',
'error': u'',
'frequency': u'',
'variantCount': -1,
'callCount': -1,
'sampleCount': -1,
'note': u'',
'externalUrl': u'',
'info': u''
}
BeaconAlleleResponse = {
'beaconId': u'',
'exists': False,
'error': u'',
'alleleRequest': [
BeaconAlleleRequest
],
'datasetAlleleResponses': [
#BeaconDatasetAlleleResponse
]
}
############# ErrorResource for response #################
# required field(s): name
ErrorResource = {
'name': u'error name/code',
'description': u'error message'
}
# parse query
BeaconAlleleRequest['referenceName'] = request.args.get('referenceName')
BeaconAlleleRequest['start'] = long(request.args.get('start'))
BeaconAlleleRequest['referenceBases'] = request.args.get('referenceBases')
BeaconAlleleRequest['alternateBases'] = request.args.get('alternateBases')
BeaconAlleleRequest['assemblyId'] = request.args.get('assemblyId')
#BeaconAlleleRequest['includeDatasetResponse'] = request.args.get('includeDatasetResponse')
logging.debug(BeaconAlleleRequest)
# search for the reference first
# search variant set
if not check_reference_set(cl, BeaconAlleleRequest['assemblyId']):
ErrorResource['description'] = 'Unknown assembly ID'
ErrorResource['name'] = 'Incomplete Query'
raise IncompleteQuery('IncompleteQuery', status_code=410, ErrorResource=ErrorResource, query=BeaconAlleleRequest,
beacon_id=Beacon["id"])
# make sure the array is cleared before each call to the search
BeaconAlleleResponse['datasetAlleleResponses'] = []
logging.debug('Starting with resonse{}'.format(BeaconAlleleResponse))
search_variants(cl, BeaconAlleleRequest, BeaconAlleleResponse)
if BeaconAlleleRequest['referenceName'] is None \
or BeaconAlleleRequest['start'] is None \
or BeaconAlleleRequest['alternateBases'] is None \
or BeaconAlleleRequest['assemblyId'] is None:
ErrorResource['description'] = 'Required parameters are missing'
ErrorResource['name'] = 'Incomplete Query'
raise IncompleteQuery('IncompleteQuery', status_code=410, ErrorResource=ErrorResource, query=BeaconAlleleRequest,
beacon_id=Beacon["id"])
# --------------------------------------------------------------#
# fill in the rest of the response:
BeaconAlleleResponse['beaconId'] = Beacon['id']
return jsonify({"response": BeaconAlleleResponse, "beacon": Beacon['id']})
class IncompleteQuery(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None, ErrorResource=None, query=None, beacon_id=None):
BeaconAlleleRequest = {
'referenceName': u'',
'start': u'',
'referenceBases': u'',
'alternateBases': u'',
'assemblyId': '',
'datasetIds': [],
'includeDatasetResponse': False,
}
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
self.ErrorResource = ErrorResource
self.query = BeaconAlleleRequest
self.beacon_id = Beacon['id']
def to_dict(self):
BeaconAlleleRequest = {
'referenceName': u'',
'start': u'',
'referenceBases': u'',
'alternateBases': u'',
'assemblyId': '',
'datasetIds': [],
'includeDatasetResponse': False,
}
rv = dict(self.payload or ())
rv["beacon"] = Beacon
rv["query"] = BeaconAlleleRequest
rv['error'] = self.ErrorResource
return rv
# info function
@app.route('/beacon/', methods=['GET'])
def welcome():
welcome_message = "Welcome to the Beacon service for the Australian Genomics Health Alliance - Somatic GA4GH server. Here is a sample query that can be made against this server (schema version 0.3)."
url="http://130.56.244.144:5000/beacon/query?referenceName=22&start=17669305&alternateBases=C&assemblyId=GRCh37"
return jsonify({"Greeting": welcome_message, "QueryResource": QueryResource, "URL": url})
# required parameters missing
@app.errorhandler(IncompleteQuery)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
return response
# page not found
@app.errorhandler(404)
def not_found(error):
return 'Page not found (Bad URL)', 404
def main():
global cl
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', filename='gb.log', level=logging.DEBUG)
logging.debug('Beacon starting')
cl = setup_ga4gh_client()
fill_beacon(cl, Beacon)
app.run(host='10.0.0.3', port=5001, threaded=True)
if __name__ == '__main__':
main()