-
Notifications
You must be signed in to change notification settings - Fork 54
/
lookups.py
327 lines (267 loc) · 10 KB
/
lookups.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
import re
from utils import *
SEARCH_LIMIT = 10000
def get_gene(db, gene_id):
return db.genes.find_one({'gene_id': gene_id}, fields={'_id': False})
def get_gene_by_name(db, gene_name):
# try gene_name field first
gene = db.genes.find_one({'gene_name': gene_name}, fields={'_id': False})
if gene:
return gene
# if not, try gene['other_names']
return db.genes.find_one({'other_names': gene_name}, fields={'_id': False})
def get_transcript(db, transcript_id):
transcript = db.transcripts.find_one({'transcript_id': transcript_id}, fields={'_id': False})
if not transcript:
return None
transcript['exons'] = get_exons_in_transcript(db, transcript_id)
return transcript
def get_raw_variant(db, xpos, ref, alt, get_id=False):
return db.variants.find_one({'xpos': xpos, 'ref': ref, 'alt': alt}, fields={'_id': get_id})
def get_variant(db, xpos, ref, alt):
variant = get_raw_variant(db, xpos, ref, alt, False)
if variant is None or 'rsid' not in variant:
return variant
if variant['rsid'] == '.' or variant['rsid'] is None:
rsid = db.dbsnp.find_one({'xpos': xpos})
if rsid:
variant['rsid'] = 'rs%s' % rsid['rsid']
return variant
def get_variants_by_rsid(db, rsid):
if not rsid.startswith('rs'):
return None
try:
int(rsid.lstrip('rs'))
except Exception, e:
return None
variants = list(db.variants.find({'rsid': rsid}, fields={'_id': False}))
add_consequence_to_variants(variants)
return variants
def get_variants_from_dbsnp(db, rsid):
if not rsid.startswith('rs'):
return None
try:
rsid = int(rsid.lstrip('rs'))
except Exception, e:
return None
position = db.dbsnp.find_one({'rsid': rsid})
if position:
variants = list(db.variants.find({'xpos': {'$lte': position['xpos'], '$gte': position['xpos']}}, fields={'_id': False}))
if variants:
add_consequence_to_variants(variants)
return variants
return []
def get_coverage_for_bases(db, xstart, xstop=None):
"""
Get the coverage for the list of bases given by xstart->xstop, inclusive
Returns list of coverage dicts
xstop can be None if just one base, but you'll still get back a list
"""
if xstop is None:
xstop = xstart
coverages = {
doc['xpos']: doc for doc in db.base_coverage.find(
{'xpos': {'$gte': xstart, '$lte': xstop}},
fields={'_id': False}
)
}
ret = []
for i in range(xstart, xstop+1):
if i in coverages:
ret.append(coverages[i])
else:
ret.append({'xpos': i, 'pos': xpos_to_pos(i)})
for item in ret:
item['has_coverage'] = 'mean' in item
del item['xpos']
return ret
def get_coverage_for_transcript(db, xstart, xstop=None):
"""
:param db:
:param genomic_coord_to_exon:
:param xstart:
:param xstop:
:return:
"""
coverage_array = get_coverage_for_bases(db, xstart, xstop)
# only return coverages that have coverage (if that makes any sense?)
# return coverage_array
covered = [c for c in coverage_array if c['has_coverage']]
for c in covered:
del c['has_coverage']
return covered
def get_constraint_for_transcript(db, transcript):
return db.constraint.find_one({'transcript': transcript}, fields={'_id': False})
def get_exons_cnvs(db, transcript_name):
return list(db.cnvs.find({'transcript': transcript_name}, fields={'_id': False}))
def get_cnvs(db, gene_name):
return list(db.cnvgenes.find({'gene': gene_name}, fields={'_id': False}))
def get_awesomebar_suggestions(g, query):
"""
This generates autocomplete suggestions when user
query is the string that user types
If it is the prefix for a gene, return list of gene names
"""
regex = re.compile('^' + re.escape(query), re.IGNORECASE)
results = [r for r in g.autocomplete_strings if regex.match(r)][:20]
return results
# 1:1-1000
R1 = re.compile(r'^(\d+|X|Y|M|MT)\s*:\s*(\d+)-(\d+)$')
R2 = re.compile(r'^(\d+|X|Y|M|MT)\s*:\s*(\d+)$')
R3 = re.compile(r'^(\d+|X|Y|M|MT)$')
# R4 = re.compile(r'^(\d+|X|Y|M|MT)\s*[-:]\s*(\d+)-([ATCG]+)-([ATCG]+)$')
R4 = re.compile(r'^\s*(\d+|X|Y|M|MT)\s*[-:]\s*(\d+)[-:\s]*([ATCG]+)\s*[-:/]\s*([ATCG]+)\s*$')
def get_awesomebar_result(db, query):
"""
Similar to the above, but this is after a user types enter
We need to figure out what they meant - could be gene, variant, region
Return tuple of (datatype, identifier)
Where datatype is one of 'gene', 'variant', or 'region'
And identifier is one of:
- ensembl ID for gene
- variant ID string for variant (eg. 1-1000-A-T)
- region ID string for region (eg. 1-1000-2000)
Follow these steps:
- if query is an ensembl ID, return it
- if a gene symbol, return that gene's ensembl ID
- if an RSID, return that variant's string
Finally, note that we don't return the whole object here - only it's identifier.
This could be important for performance later
"""
query = query.strip()
print 'Query: %s' % query
# Variant
variant = get_variants_by_rsid(db, query.lower())
if variant:
if len(variant) == 1:
return 'variant', variant[0]['variant_id']
else:
return 'dbsnp_variant_set', variant[0]['rsid']
variant = get_variants_from_dbsnp(db, query.lower())
if variant:
return 'variant', variant[0]['variant_id']
# variant = get_variant(db, )
# TODO - https://github.com/brettpthomas/exac_browser/issues/14
gene = get_gene_by_name(db, query)
if gene:
return 'gene', gene['gene_id']
# From here out, all should be uppercase (gene, tx, region, variant_id)
query = query.upper()
gene = get_gene_by_name(db, query)
if gene:
return 'gene', gene['gene_id']
# Ensembl formatted queries
if query.startswith('ENS'):
# Gene
gene = get_gene(db, query)
if gene:
return 'gene', gene['gene_id']
# Transcript
transcript = get_transcript(db, query)
if transcript:
return 'transcript', transcript['transcript_id']
# From here on out, only region queries
if query.startswith('CHR'):
query = query.lstrip('CHR')
# Region
m = R1.match(query)
if m:
if int(m.group(3)) < int(m.group(2)):
return 'region', 'invalid'
return 'region', '{}-{}-{}'.format(m.group(1), m.group(2), m.group(3))
m = R2.match(query)
if m:
return 'region', '{}-{}-{}'.format(m.group(1), m.group(2), m.group(2))
m = R3.match(query)
if m:
return 'region', '{}'.format(m.group(1))
m = R4.match(query)
if m:
return 'variant', '{}-{}-{}-{}'.format(m.group(1), m.group(2), m.group(3), m.group(4))
return 'not_found', query
def get_genes_in_region(db, chrom, start, stop):
"""
Genes that overlap a region
"""
xstart = get_xpos(chrom, start)
xstop = get_xpos(chrom, stop)
genes = db.genes.find({
'xstart': {'$lte': xstop},
'xstop': {'$gte': xstart},
}, fields={'_id': False})
return list(genes)
def get_variants_in_region(db, chrom, start, stop):
"""
Variants that overlap a region
Unclear if this will include CNVs
"""
xstart = get_xpos(chrom, start)
xstop = get_xpos(chrom, stop)
variants = list(db.variants.find({
'xpos': {'$lte': xstop, '$gte': xstart}
}, fields={'_id': False}, limit=SEARCH_LIMIT))
add_consequence_to_variants(variants)
for variant in variants:
remove_extraneous_information(variant)
return list(variants)
def get_metrics(db, variant):
if 'allele_count' not in variant or variant['allele_num'] == 0:
return None
metrics = {}
for metric in METRICS:
metrics[metric] = db.metrics.find_one({'metric': metric}, fields={'_id': False})
metric = None
if variant['allele_count'] == 1:
metric = 'singleton'
elif variant['allele_count'] == 2:
metric = 'doubleton'
else:
for af in AF_BUCKETS:
if float(variant['allele_count'])/variant['allele_num'] < af:
metric = af
break
if metric is not None:
metrics['Site Quality'] = db.metrics.find_one({'metric': 'binned_%s' % metric}, fields={'_id': False})
return metrics
def remove_extraneous_information(variant):
del variant['genotype_depths']
del variant['genotype_qualities']
del variant['transcripts']
del variant['genes']
del variant['orig_alt_alleles']
del variant['xpos']
del variant['xstart']
del variant['xstop']
del variant['site_quality']
del variant['vep_annotations']
def get_variants_in_gene(db, gene_id):
"""
"""
variants = []
for variant in db.variants.find({'genes': gene_id}, fields={'_id': False}):
variant['vep_annotations'] = [x for x in variant['vep_annotations'] if x['Gene'] == gene_id]
add_consequence_to_variant(variant)
remove_extraneous_information(variant)
variants.append(variant)
return variants
def get_transcripts_in_gene(db, gene_id):
"""
"""
return list(db.transcripts.find({'gene_id': gene_id}, fields={'_id': False}))
def get_variants_in_transcript(db, transcript_id):
"""
"""
variants = []
for variant in db.variants.find({'transcripts': transcript_id}, fields={'_id': False}):
variant['vep_annotations'] = [x for x in variant['vep_annotations'] if x['Feature'] == transcript_id]
add_consequence_to_variant(variant)
remove_extraneous_information(variant)
variants.append(variant)
return variants
def get_exons_in_transcript(db, transcript_id):
# return sorted(
# [x for x in
# db.exons.find({'transcript_id': transcript_id}, fields={'_id': False})
# if x['feature_type'] != 'exon'],
# key=lambda k: k['start'])
return sorted(list(db.exons.find({'transcript_id': transcript_id, 'feature_type': { "$in": ['CDS', 'UTR', 'exon'] }}, fields={'_id': False})), key=lambda k: k['start'])