This repository has been archived by the owner on Aug 6, 2024. It is now read-only.
forked from konradjk/exac_browser
-
Notifications
You must be signed in to change notification settings - Fork 1
/
exac.py
executable file
·1427 lines (1219 loc) · 62.5 KB
/
exac.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
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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python2
import itertools
import glob
import sqlite3
import time
from collections import defaultdict, OrderedDict
from os.path import basename
from multiprocessing import Process
import pymongo
import pysam
import gzip
from subprocess import check_output
from parsing import *
import logging
import lookups
import socket
from os import environ
from utils import *
from flask import Response
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash, jsonify, send_from_directory
from flask.ext.compress import Compress
from flask.ext.runner import Runner
from flask_errormail import mail_on_500
from werkzeug.contrib.cache import SimpleCache
logging.getLogger().addHandler(logging.StreamHandler())
logging.getLogger().setLevel(logging.INFO)
hostname = socket.gethostname()
is_local = 'local' in hostname or 'Home' in hostname or environ.get('PYTHONUNBUFFERED')
is_chara = 'chara' in hostname
is_rask = 'rask' in hostname
ADMINISTRATORS = (
'vladislav.sav@gmail.com',
# 'exac.browser.errors@gmail.com',
)
app = Flask(__name__)
mail_on_500(app, ADMINISTRATORS)
Compress(app)
app.config['COMPRESS_DEBUG'] = True
cache = SimpleCache()
EXAC_FILES_DIRECTORY = '../exac_data/'
REGION_LIMIT = 1E5
EXON_PADDING = 50
# Load default config and override config from an environment variable
app.config.update(dict(
DB_HOST='localhost',
DB_PORT=27017,
DB_NAME='exac',
DEBUG=True,
SECRET_KEY='development key',
LOAD_DB_PARALLEL_PROCESSES = 12, # contigs assigned to threads, so good to make this a factor of 24 (eg. 2,3,4,6,8)
FEATURES_FILE=os.path.join(os.path.dirname(__file__), EXAC_FILES_DIRECTORY, '%s', 'ensembl.bed.gz'),
CANONICAL_TRANSCRIPT_FILE=os.path.join(os.path.dirname(__file__), EXAC_FILES_DIRECTORY, '%s', 'canonical_transcripts_ensembl.txt.gz'),
OMIM_FILE=os.path.join(os.path.dirname(__file__), EXAC_FILES_DIRECTORY, '%s', 'omim_info.txt.gz'),
SITES_VCF_DIRS=os.path.join(os.path.dirname(__file__), EXAC_FILES_DIRECTORY, '%s', 'vardict', '%s'),
SITES_VCFS=os.path.join(os.path.dirname(__file__), EXAC_FILES_DIRECTORY, '%s', 'vardict', '%s', '*.vcf.gz'),
POPULATION_COVERAGE_FILES=os.path.join(os.path.dirname(__file__), EXAC_FILES_DIRECTORY, '%s', 'population_data', 'coverage', 'Panel.*.coverage.txt.gz'),
BASE_COVERAGE_DIRS=os.path.join(os.path.dirname(__file__), EXAC_FILES_DIRECTORY, '%s', 'coverage', '%s', '*/'),
BASE_COVERAGE_FILES=os.path.join(os.path.dirname(__file__), EXAC_FILES_DIRECTORY, '%s', 'coverage', '%s', '%s', 'chr*.txt.gz'),
PROJECT_BASE_COVERAGE_DIRS=os.path.join(os.path.dirname(__file__), EXAC_FILES_DIRECTORY, '%s', 'coverage', '*/'),
PROJECT_BASE_COVERAGE_FILES=os.path.join(os.path.dirname(__file__), EXAC_FILES_DIRECTORY, '%s', 'coverage', '%s', 'chr*.txt.gz'),
FILTERED_REGIONS_FILES=os.path.join(os.path.dirname(__file__), EXAC_FILES_DIRECTORY, '%s', 'coverage', '%s', 'low_panel_coverage.*.bed.gz'),
DBNSFP_FILE=os.path.join(os.path.dirname(__file__), EXAC_FILES_DIRECTORY, 'dbNSFP2.6_gene.gz'),
CONSTRAINT_FILE=os.path.join(os.path.dirname(__file__), EXAC_FILES_DIRECTORY, 'forweb_cleaned_exac_r03_march16_z_data_pLI_CNV-final.txt.gz'),
MNP_FILE=os.path.join(os.path.dirname(__file__), EXAC_FILES_DIRECTORY, 'MNPs_NotFiltered_ForBrowserRelease.txt.gz'),
CNV_FILE=os.path.join(os.path.dirname(__file__), EXAC_FILES_DIRECTORY, 'exac-gencode-exon.cnt.final.pop3'),
CNV_GENE_FILE=os.path.join(os.path.dirname(__file__), EXAC_FILES_DIRECTORY, 'exac-final-cnvs.gene.rank'),
# How to get a dbsnp142.txt.bgz file:
# wget ftp://ftp.ncbi.nlm.nih.gov/snp/organisms/human_9606_b142_GRCh37p13/database/organism_data/b142_SNPChrPosOnRef_105.bcp.gz
# zcat b142_SNPChrPosOnRef_105.bcp.gz | awk '$3 != ""' | perl -pi -e 's/ +/\t/g' | sort -k2,2 -k3,3n | bgzip -c > dbsnp142.txt.bgz
# tabix -s 2 -b 3 -e 3 dbsnp142.txt.bgz
DBSNP_FILE=os.path.join(os.path.dirname(__file__), EXAC_FILES_DIRECTORY, 'dbsnp142.txt.bgz'),
READ_VIZ_DIR=os.path.join(os.path.dirname(__file__), EXAC_FILES_DIRECTORY, '%s', 'combined_bams', '%s'),
READ_VIZ_DIR_HTML=os.path.join('/%s', 'combined_bams', '%s'),
))
GENE_CACHE_DIR = os.path.join(os.path.dirname(__file__), 'gene_cache')
# GENES_TO_CACHE = {l.strip('\n') for l in open(os.path.join(os.path.dirname(__file__), 'genes_to_cache.txt'))}
def connect_db():
"""
Connects to the specific database.
"""
client = pymongo.MongoClient(host=app.config['DB_HOST'], port=app.config['DB_PORT'])
return client[app.config['DB_NAME']]
def parse_tabix_file_subset(tabix_filenames, subset_i, subset_n, record_parser, proc_name=None, canonical_transcripts=None,
sample_name=None):
"""
Returns a generator of parsed record objects (as returned by record_parser) for the i'th out n subset of records
across all the given tabix_file(s). The records are split by files and contigs within files, with 1/n of all contigs
from all files being assigned to this the i'th subset.
Args:
tabix_filenames: a list of one or more tabix-indexed files. These will be opened using pysam.Tabixfile
subset_i: zero-based number
subset_n: total number of subsets
record_parser: a function that takes a file-like object and returns a generator of parsed records
"""
start_time = time.time()
open_tabix_files = [pysam.Tabixfile(tabix_filename) for tabix_filename in tabix_filenames]
tabix_file_contig_pairs = [(tabix_file, contig) for tabix_file in open_tabix_files for contig in tabix_file.contigs]
tabix_file_contig_subset = tabix_file_contig_pairs[subset_i : : subset_n] # get every n'th tabix_file/contig pair
short_filenames = ", ".join(map(os.path.basename, tabix_filenames))
num_file_contig_pairs = len(tabix_file_contig_subset)
print (((proc_name + ': ') if proc_name else '') + "Loading subset %(subset_i)s of %(subset_n)s total:" +
" %(num_file_contig_pairs)s contigs from %(short_filenames)s") % locals()
counter = 0
for tabix_file, contig in tabix_file_contig_subset:
header_iterator = tabix_file.header
records_iterator = tabix_file.fetch(contig, 0, 10**9, multiple_iterators=True)
for parsed_record in record_parser(itertools.chain(header_iterator, records_iterator), canonical_transcripts, sample_name):
counter += 1
yield parsed_record
if counter % 100000 == 0:
seconds_elapsed = int(time.time()-start_time)
print (((proc_name + ': ') if proc_name else '') + ("Loaded %(counter)s records from subset %(subset_i)s of %(subset_n)s from %(short_filenames)s "
"(%(seconds_elapsed)s seconds)") % locals())
print (((proc_name + ': ') if proc_name else '') + "Finished loading subset %(subset_i)s from" +
" %(short_filenames)s (%(counter)s records)") % locals()
def load_coverage(coverage_files, i, n, coverage_db):
coverage_generator = parse_tabix_file_subset(coverage_files, i, n, get_base_coverage_from_file,
proc_name='Base coverage')
try:
coverage_db.insert(coverage_generator, w=0)
except pymongo.errors.InvalidOperation:
pass # handle error when coverage_generator is empty
def load_population_coverage():
full_db = get_db()
procs = []
for genome in ['hg19', 'hg38']:
full_db[genome].population_coverage.drop()
print("Dropped db.population_coverage for " + genome)
# load coverage first; variant info will depend on coverage
full_db[genome].population_coverage.ensure_index('xpos')
coverage_files = glob.glob(app.config['POPULATION_COVERAGE_FILES'] % genome)
num_procs = app.config['LOAD_DB_PARALLEL_PROCESSES'] / 2
# random.shuffle(app.config['BASE_COVERAGE_FILES'])
for i in range(num_procs):
p = Process(target=load_coverage, args=(coverage_files, i, num_procs, full_db[genome].population_coverage))
p.start()
procs.append(p)
return procs
def _load_one(procs, samples_count, coverage_files, coverage):
# load coverage first; variant info will depend on coverage
coverage.ensure_index('xpos')
num_procs = app.config['LOAD_DB_PARALLEL_PROCESSES']
num_procs = max(1, num_procs / samples_count)
for i in range(num_procs):
p = Process(target=load_coverage, args=(coverage_files, i, num_procs, coverage))
p.start()
procs.append(p)
return procs
def load_base_coverage(project_name=None, genome=None):
full_db = get_db()
if project_name:
projects = [get_one_project(full_db, project_name, genome)]
else:
projects = get_projects(full_db)
procs = []
for project_name, genome in projects:
db = full_db[get_project_key(project_name, genome)]
db.samples.drop()
db.base_coverage.drop()
print("Dropped db.base_coverage for " + project_name)
project_coverage_files = glob.glob(app.config['PROJECT_BASE_COVERAGE_FILES'] % (genome, project_name))
project_procs = _load_one(procs, 1, project_coverage_files, db.base_coverage)
[p.join() for p in project_procs]
sample_dirs = glob.glob(app.config['BASE_COVERAGE_DIRS'] % (genome, project_name))
for idx, sample_dir in enumerate(sample_dirs):
path, sample_name = os.path.split(os.path.dirname(sample_dir))
coverage_files = glob.glob(app.config['BASE_COVERAGE_FILES'] % (genome, project_name, sample_name))
sample_procs = []
if coverage_files:
db[idx].base_coverage.drop()
print("Dropped db.base_coverage for " + sample_name + " in " + project_name)
db.samples.insert({'name': sample_name, 'idx': idx})
sample_procs = _load_one(sample_procs, 1, coverage_files, db[idx].base_coverage)
[p.join() for p in sample_procs]
return procs
#print 'Done loading coverage. Took %s seconds' % int(time.time() - start_time)
def load_variants_file(project_name=None, genome=None):
def load_variants(sites_file, i, n, db, canonical_transcripts, sample_name=None):
variants_generator = parse_tabix_file_subset([sites_file], i, n, get_variants_from_sites_vcf,
canonical_transcripts=canonical_transcripts, proc_name='Variants', sample_name=sample_name)
try:
db.variants.insert(variants_generator, w=0)
except pymongo.errors.InvalidOperation:
pass # handle error when variant_generator is empty
full_db = get_db()
if project_name:
projects = [get_one_project(full_db, project_name, genome)]
else:
full_db.projects.drop()
for genome in 'hg19', 'hg38':
project_vcf_dirs = glob.glob(app.config['SITES_VCF_DIRS'] % (genome, '*'))
project_names = [basename(vcf_dir)[0] for vcf_dir in project_vcf_dirs]
if project_names:
full_db.projects.insert({'name': project_name, 'genome': genome} for project_name in project_names)
projects = get_projects(full_db)
procs = []
for project_name, genome in projects:
db = full_db[get_project_key(project_name, genome)]
db.variants.drop()
db.combined_variants.drop()
print("Dropped db.variants for " + project_name)
# grab variants from sites VCF
db.variants.ensure_index('sample_name')
db.variants.ensure_index('xpos')
db.variants.ensure_index('xstart')
db.variants.ensure_index('xstop')
db.variants.ensure_index('rsid')
db.variants.ensure_index('genes')
db.variants.ensure_index('transcripts')
db.combined_variants.ensure_index('xpos')
db.combined_variants.ensure_index('genes')
db.combined_variants.ensure_index('transcripts')
sample_vcfs = glob.glob(app.config['SITES_VCFS'] % (genome, project_name))
if len(sample_vcfs) == 0:
print("No vcf file found for " + project_name)
continue
min_af, act_min_af = get_filtering_params(gzip.open(sample_vcfs[0]))
db.filt_params.drop()
db.filt_params.insert({'min_af': min_af * 100, 'act_min_af': act_min_af * 100})
canonical_transcripts = defaultdict()
with gzip.open(app.config['CANONICAL_TRANSCRIPT_FILE'] % genome) as canonical_transcript_file:
for gene, transcript in get_canonical_transcripts(canonical_transcript_file):
canonical_transcripts[gene] = transcript
num_procs = app.config['LOAD_DB_PARALLEL_PROCESSES']
num_procs = max(1, num_procs / len(projects))
for sample_vcf in sample_vcfs:
procs = []
sample_name = basename(sample_vcf).split('-vardict')[0]
for i in range(num_procs):
p = Process(target=load_variants, args=(sample_vcf, i, num_procs, db, canonical_transcripts, sample_name))
p.start()
procs.append(p)
[p.join() for p in procs]
sample_names = lookups.get_project_samples(full_db, project_name, genome)
var_positions = set()
for v in db.variants.find():
var_positions.add(v['xpos'])
for xpos in var_positions:
pos_variants = list(db.variants.find({'xpos': xpos}))
alt_values = set(variant['alt'] for variant in pos_variants)
for alt in alt_values:
alt_variants = [variant for variant in pos_variants if variant['alt'] == alt]
variant = {
'chrom': alt_variants[0]['chrom'],
'pos': alt_variants[0]['pos'],
'xpos': xpos,
'ref': alt_variants[0]['ref'],
'alt': alt,
'variant_id': alt_variants[0]['variant_id'],
'genes': alt_variants[0]['genes'],
'transcripts': alt_variants[0]['transcripts'],
'vep_annotations': alt_variants[0]['vep_annotations'],
'filter': 'PASS' if any(var['filter'] == 'PASS' for var in alt_variants) else 'REJECT'
}
combined_variant = lookups.combine_variants(variant, alt_variants, sample_names)
db.combined_variants.insert(combined_variant)
return procs
#print 'Done loading variants. Took %s seconds' % int(time.time() - start_time)
def wc(fpath):
cat = 'cat' if not fpath.endswith('.gz') else 'gunzip -c'
return int(check_output(cat + ' ' + fpath + ' | grep -v ^# | wc -l', shell=True).split()[0])
def load_evaluate_capture_data(project_name=None, genome=None):
def load_regions(project_files, proc_index_, num_procs_, db_):
regions_generator = parse_tabix_file_subset(project_files, proc_index_, num_procs_, get_regions,
proc_name='Evaluate capture regions')
try:
db_.filtered_regions.insert(regions_generator, w=0)
except pymongo.errors.InvalidOperation:
pass # handle error when variant_generator is empty
start_time = time.time()
full_db = get_db()
if project_name:
projects = [get_one_project(full_db, project_name, genome)]
else:
projects = get_projects(full_db)
procs = []
for project_name, genome in projects:
db = full_db[get_project_key(project_name, genome)]
db.filtered_regions.drop()
db.filtered_regions.ensure_index('start')
regions_fpaths = glob.glob(app.config['FILTERED_REGIONS_FILES'] % (genome, project_name))
regions_by_lines_num = dict((fpath, wc(fpath)) for fpath in regions_fpaths)
regions_fpaths = [fpath for fpath in regions_fpaths if 0 < regions_by_lines_num[fpath]]
if regions_fpaths:
good_regions_fpaths = [fpath for fpath in regions_fpaths if regions_by_lines_num[fpath] < 300]
if not good_regions_fpaths:
good_regions_fpaths = [min(regions_fpaths, key=lambda _fp: regions_by_lines_num[_fp])]
num_procs = app.config['LOAD_DB_PARALLEL_PROCESSES']
num_procs = max(1, num_procs / len(projects))
print 'Loaded regions files: ' + ', '.join(good_regions_fpaths) + ', loading in ' + str(num_procs) + ' procs'
for i in range(num_procs):
p = Process(target=load_regions, args=(good_regions_fpaths, i, num_procs, db))
p.start()
procs.append(p)
print('Done loading capture evaluating info. Took %s seconds' % int(time.time() - start_time))
return procs
'''
def load_constraint_information():
db = get_db()
db.constraint.drop()
print 'Dropped db.constraint.'
start_time = time.time()
with gzip.open(app.config['CONSTRAINT_FILE']) as constraint_file:
for transcript in get_constraint_information(constraint_file):
db.constraint.insert(transcript, w=0)
db.constraint.ensure_index('transcript')
print 'Done loading constraint info. Took %s seconds' % int(time.time() - start_time)
def load_mnps():
db = get_db()
start_time = time.time()
db.variants.ensure_index('has_mnp')
print 'Done indexing.'
while db.variants.find_and_modify({'has_mnp' : True}, {'$unset': {'has_mnp': '', 'mnps': ''}}):
pass
print 'Deleted MNP data.'
with gzip.open(app.config['MNP_FILE']) as mnp_file:
for mnp in get_mnp_data(mnp_file):
variant = lookups.get_raw_variant(db, mnp['xpos'], mnp['ref'], mnp['alt'], True)
db.variants.find_and_modify({'_id': variant['_id']}, {'$set': {'has_mnp': True}, '$push': {'mnps': mnp}}, w=0)
db.variants.ensure_index('has_mnp')
print 'Done loading MNP info. Took %s seconds' % int(time.time() - start_time)'''
def load_gene_models():
full_db = get_db()
for genome in 'hg19', 'hg38':
db = full_db[genome]
db.genes.drop()
db.transcripts.drop()
db.exons.drop()
print('Dropped db.genes, db.transcripts, and db.exons for ' + genome)
start_time = time.time()
canonical_transcripts = {}
with gzip.open(app.config['CANONICAL_TRANSCRIPT_FILE'] % genome) as canonical_transcript_file:
for gene, transcript in get_canonical_transcripts(canonical_transcript_file):
canonical_transcripts[gene] = transcript
omim_annotations = {}
'''with gzip.open(app.config['OMIM_FILE'] % genome) as omim_file:
for fields in get_omim_associations(omim_file):
if fields is None:
continue
gene, transcript, accession, description = fields
omim_annotations[gene] = (accession, description)
dbnsfp_info = {}
with gzip.open(app.config['DBNSFP_FILE'] % genome) as dbnsfp_file:
for dbnsfp_gene in get_dbnsfp_info(dbnsfp_file):
other_names = [other_name.upper() for other_name in dbnsfp_gene['gene_other_names']]
dbnsfp_info[dbnsfp_gene['ensembl_gene']] = (dbnsfp_gene['gene_full_name'], other_names)'''
print('Done loading metadata. Took %s seconds' % int(time.time() - start_time))
# grab genes from GTF
start_time = time.time()
with gzip.open(app.config['FEATURES_FILE'] % genome) as features_file:
for gene in get_genes_from_features(features_file):
gene_id = gene['gene_id']
if gene_id not in canonical_transcripts or gene['transcript_id'] != canonical_transcripts[gene_id]:
continue
gene['canonical_transcript'] = canonical_transcripts[gene_id]
if gene_id in omim_annotations:
gene['omim_accession'] = omim_annotations[gene_id][0]
gene['omim_description'] = omim_annotations[gene_id][1]
'''if gene_id in dbnsfp_info:
gene['full_gene_name'] = dbnsfp_info[gene_id][0]
gene['other_names'] = dbnsfp_info[gene_id][1]'''
db.genes.insert(gene, w=0)
print('Done loading genes. Took %s seconds' % int(time.time() - start_time))
start_time = time.time()
db.genes.ensure_index('gene_id')
db.genes.ensure_index('gene_name_upper')
db.genes.ensure_index('gene_name')
db.genes.ensure_index('other_names')
db.genes.ensure_index('xstart')
db.genes.ensure_index('xstop')
print('Done indexing gene table. Took %s seconds' % int(time.time() - start_time))
# and now transcripts
start_time = time.time()
with gzip.open(app.config['FEATURES_FILE'] % genome) as features_file:
db.transcripts.insert((transcript for transcript in get_transcripts_from_features(features_file)), w=0)
print('Done loading transcripts. Took %s seconds' % int(time.time() - start_time))
start_time = time.time()
db.transcripts.ensure_index('transcript_id')
db.transcripts.ensure_index('gene_id')
print('Done indexing transcript table. Took %s seconds' % int(time.time() - start_time))
# Building up gene definitions
start_time = time.time()
with gzip.open(app.config['FEATURES_FILE'] % genome) as features_file:
db.exons.insert((exon for exon in get_exons_from_features(features_file)), w=0)
print('Done loading exons. Took %s seconds' % int(time.time() - start_time))
start_time = time.time()
db.exons.ensure_index('exon_id')
db.exons.ensure_index('transcript_id')
db.exons.ensure_index('gene_id')
print('Done indexing exon table. Took %s seconds' % int(time.time() - start_time))
return []
def load_cnv_models():
db = get_db()
db.cnvs.drop()
print('Dropped db.cnvs.')
start_time = time.time()
with open(app.config['CNV_FILE']) as cnv_txt_file:
for cnv in get_cnvs_from_txt(cnv_txt_file):
db.cnvs.insert(cnv, w=0)
#progress.update(gtf_file.fileobj.tell())
#progress.finish()
print('Done loading CNVs. Took %s seconds' % int(time.time() - start_time))
def drop_cnv_genes():
db = get_db()
start_time = time.time()
db.cnvgenes.drop()
def load_cnv_genes():
db = get_db()
start_time = time.time()
with open(app.config['CNV_GENE_FILE']) as cnv_gene_file:
for cnvgene in get_cnvs_per_gene(cnv_gene_file):
db.cnvgenes.insert(cnvgene, w=0)
#progress.update(gtf_file.fileobj.tell())
#progress.finish()
print('Done loading CNVs in genes. Took %s seconds' % int(time.time() - start_time))
def load_dbsnp_file():
db = get_db()
def load_dbsnp(dbsnp_file, i, n, db):
if os.path.isfile(dbsnp_file + ".tbi"):
dbsnp_record_generator = parse_tabix_file_subset([dbsnp_file], i, n, get_snp_from_dbsnp_file,
proc_name='dbSNP file')
try:
db.dbsnp.insert(dbsnp_record_generator, w=0)
except pymongo.errors.InvalidOperation:
pass # handle error when coverage_generator is empty
else:
with gzip.open(dbsnp_file) as f:
db.dbsnp.insert((snp for snp in get_snp_from_dbsnp_file(f)), w=0)
db.dbsnp.drop()
db.dbsnp.ensure_index('rsid')
db.dbsnp.ensure_index('xpos')
start_time = time.time()
dbsnp_file = app.config['DBSNP_FILE']
print("Loading dbsnp from %s" % dbsnp_file)
if os.path.isfile(dbsnp_file + ".tbi"):
num_procs = app.config['LOAD_DB_PARALLEL_PROCESSES']
else:
# see if non-tabixed .gz version exists
if os.path.isfile(dbsnp_file):
print(("WARNING: %(dbsnp_file)s.tbi index file not found. Will use single thread to load dbsnp."
"To create a tabix-indexed dbsnp file based on UCSC dbsnp, do: \n"
" wget http://hgdownload.soe.ucsc.edu/goldenPath/hg19/database/snp141.txt.gz \n"
" gzcat snp141.txt.gz | cut -f 1-5 | bgzip -c > snp141.txt.bgz \n"
" tabix -0 -s 2 -b 3 -e 4 snp141.txt.bgz") % locals())
num_procs = 1
else:
raise Exception("dbsnp file %s(dbsnp_file)s not found." % locals())
procs = []
for i in range(num_procs):
p = Process(target=load_dbsnp, args=(dbsnp_file, i, num_procs, db))
p.start()
procs.append(p)
return procs
#print 'Done loading dbSNP. Took %s seconds' % int(time.time() - start_time)
#start_time = time.time()
#db.dbsnp.ensure_index('rsid')
#print 'Done indexing dbSNP table. Took %s seconds' % int(time.time() - start_time)
def load_db():
"""
Load the database
"""
# Initialize database
# Don't need to explicitly create tables with mongo, just indices
confirm = raw_input('This will drop the database and reload. Are you sure you want to continue? [no] ')
if not confirm.startswith('y'):
print('Exiting...')
sys.exit(1)
all_procs = []
for load_function in [load_variants_file, load_base_coverage, load_evaluate_capture_data, load_gene_models,
load_population_coverage]: # CNV: load_cnv_models, load_cnv_genes,
procs = load_function()
all_procs.extend(procs)
print("Started %s processes to run %s" % (len(procs), load_function.__name__))
[p.join() for p in all_procs]
# print('Done! Loading MNPs...')
# load_mnps()
print('Done! Creating cache...')
create_cache()
print('Done!')
def delete_project(project_name, genome, silent=False):
full_db = get_db()
full_db[get_project_key(project_name, genome)].drop()
full_db.projects.remove({'name': project_name, 'genome': genome})
if not silent:
print(project_name + ' was deleted from the database')
print('Refreshing cache...')
create_cache()
if not silent:
print('Done!')
def add_project(project_name, genome):
delete_project(project_name, genome, silent=True)
all_procs = []
full_db = get_db()
full_db.projects.insert({'name': project_name, 'genome': genome})
print('Adding ' + project_name + ' to the database')
for load_function in [load_evaluate_capture_data, load_base_coverage, load_variants_file]:
procs = load_function(project_name, genome)
all_procs.extend(procs)
print("Started %s processes to run %s" % (len(procs), load_function.__name__))
[p.join() for p in all_procs]
print('Done! Creating cache...')
create_cache()
precalculate_metrics(project_name=project_name, genome=genome)
print('Done!')
def save_autocomplete_data(autocomplete_strings, output_fpath):
f = open(os.path.join(os.path.dirname(__file__), output_fpath), 'w')
for s in sorted(autocomplete_strings):
f.write(s+'\n')
f.close()
def create_cache():
"""
This is essentially a compile step that generates all cached resources.
Creates files like autocomplete_entries.txt
Should be run on every redeploy.
"""
# create autocomplete_entries.txt
autocomplete_strings = []
full_db = get_db()
projects = get_projects(full_db)
for genome in 'hg19', 'hg38':
for gene in full_db[genome].genes.find():
autocomplete_strings.append(gene['gene_name'])
if 'other_names' in gene:
autocomplete_strings.extend(gene['other_names'])
save_autocomplete_data(set(autocomplete_strings), genome + '_autocomplete_strings.txt')
save_autocomplete_data([project_name for (project_name, project_genome) in projects], 'autocomplete_projects.txt')
'''
# create static gene pages for genes in
if not os.path.exists(GENE_CACHE_DIR):
os.makedirs(GENE_CACHE_DIR)
# get list of genes ordered by num_variants
for gene_id in GENES_TO_CACHE:
try:
page_content = get_gene_page_content(gene_id)
except Exception as e:
print e
continue
f = open(os.path.join(GENE_CACHE_DIR, '{}.html'.format(gene_id)), 'w')
f.write(page_content)
f.close()'''
def precalculate_metrics(project_name=None, genome=None):
import numpy
full_db = get_db()
if project_name:
projects = [get_one_project(full_db, project_name, genome)]
else:
projects = get_projects(full_db)
for project_name, genome in projects:
db = full_db[get_project_key(project_name, genome)]
print('Reading %s variants for %s...' % (db.variants.count(), project_name))
metrics = defaultdict(list)
binned_metrics = defaultdict(list)
progress = 0
start_time = time.time()
for variant in db.variants.find(projection=['quality_metrics', 'site_quality', 'allele_num', 'allele_count']):
for metric, value in variant['quality_metrics'].iteritems():
metrics[metric].append(float(value))
if 'site_quality' in variant:
qual = float(variant['site_quality'])
metrics['site_quality'].append(qual)
'''if variant['allele_num'] == 0: continue
if variant['allele_count'] == 1:
binned_metrics['singleton'].append(qual)
elif variant['allele_count'] == 2:
binned_metrics['doubleton'].append(qual)
else:
for af in AF_BUCKETS:
if float(variant['allele_count'])/variant['allele_num'] < af:
binned_metrics[af].append(qual)
break'''
progress += 1
if not progress % 100000:
print('Read %s variants. Took %s seconds' % (progress, int(time.time() - start_time)))
print('Done reading variants. Dropping metrics database... ')
db.metrics.drop()
print('Dropped metrics database. Calculating metrics...')
for metric in metrics:
bin_range = None
data = map(numpy.log, metrics[metric]) if metric == 'DP' else metrics[metric]
if metric == 'FS':
bin_range = (0, 20)
elif metric == 'VQSLOD':
bin_range = (-20, 20)
elif metric == 'InbreedingCoeff':
bin_range = (0, 1)
if bin_range is not None:
data = [x if (x > bin_range[0]) else bin_range[0] for x in data]
data = [x if (x < bin_range[1]) else bin_range[1] for x in data]
hist = numpy.histogram(data, bins=40, range=bin_range)
edges = hist[1]
# mids = [(edges[i]+edges[i+1])/2 for i in range(len(edges)-1)]
lefts = [edges[i] for i in range(len(edges)-1)]
db.metrics.insert({
'metric': metric,
'mids': lefts,
'hist': list(hist[0])
})
for metric in binned_metrics:
hist = numpy.histogram(map(numpy.log, binned_metrics[metric]), bins=40)
edges = hist[1]
mids = [(edges[i]+edges[i+1])/2 for i in range(len(edges)-1)]
db.metrics.insert({
'metric': 'binned_%s' % metric,
'mids': mids,
'hist': list(hist[0])
})
db.metrics.ensure_index('metric')
print('Done pre-calculating metrics!')
def get_db():
"""
Opens a new database connection if there is none yet for the
current application context.
"""
if not hasattr(g, 'db_conn'):
g.db_conn = connect_db()
return g.db_conn
def check_project_exists(project_name):
full_db = get_db()
project = lookups.get_project_by_project_name(full_db, project_name)
if not project:
abort(404)
def check_sample_exists(genome, project_name, sample_name):
full_db = get_db()
sample_names = lookups.get_project_samples(full_db, project_name, genome)
if not sample_names or sample_name not in sample_names:
abort(404)
# @app.teardown_appcontext
# def close_db(error):
# """Closes the database again at the end of the request."""
# if hasattr(g, 'db_conn'):
# g.db_conn.close()
@app.route('/')
def homepage():
return render_template('homepage.html')
@app.route('/<project_genome>/<project_name>/')
def project_page(project_name, project_genome):
check_project_exists(project_name)
db = get_db()
sample_names = lookups.get_project_samples(db, project_name, project_genome)
filtered_regions = lookups.get_filtered_regions_in_project(db, project_name, project_genome)
depth_thresholds = sorted(list(set([r['depth_threshold'] for r in filtered_regions])), key=natural_key)
t = render_template(
'project_page.html',
project_name=project_name,
genome=project_genome,
sample_names=sample_names,
filtered_regions=filtered_regions,
filtered_regions_json=JSONEncoder().encode(filtered_regions),
depth_thresholds=depth_thresholds,
)
return t
@app.route('/<project_genome>/<project_name>/<sample_name>/')
def sample_page(sample_name, project_name, project_genome):
check_sample_exists(project_genome, project_name, sample_name)
db = get_db()
sample_names = lookups.get_project_samples(db, project_name, project_genome)
variants = lookups.get_sample_variants(db, project_name, project_genome, sample_name, filter_unknown=True)
filt_params = lookups.get_project_filt_params(db, project_name, project_genome)
t = render_template(
'sample_page.html',
project_name=project_name,
genome=project_genome,
sample_names=sample_names,
sample_name=sample_name if sample_name else '',
sample_variants=variants,
sample_variants_json=JSONEncoder().encode(variants),
min_af=filt_params['min_af'],
act_min_af=filt_params['act_min_af']
)
return t
@app.route('/<project_genome>/<project_name>/autocomplete/<query>')
def awesome_autocomplete(query, project_name, project_genome):
if not hasattr(g, 'autocomplete_strings'):
g.autocomplete_strings = dict()
for genome in 'hg19', 'hg38':
g.autocomplete_strings[genome] = [s.strip() for s in open(os.path.join(os.path.dirname(__file__), genome + '_autocomplete_strings.txt'))]
suggestions = lookups.get_awesomebar_suggestions(g.autocomplete_strings[project_genome], query)
return Response(json.dumps([{'value': s} for s in suggestions]), mimetype='application/json')
@app.route('/autocomplete_project/')
def show_all_projects():
if not hasattr(g, 'autocomplete_projects'):
g.autocomplete_projects = [s.strip() for s in open(os.path.join(os.path.dirname(__file__), 'autocomplete_projects.txt'))]
suggestions = g.autocomplete_projects
return Response(json.dumps([{'value': s} for s in suggestions]), mimetype='application/json')
@app.route('/autocomplete_project/<query>')
def awesome_project_autocomplete(query):
if not hasattr(g, 'autocomplete_projects'):
g.autocomplete_projects = [s.strip() for s in open(os.path.join(os.path.dirname(__file__), 'autocomplete_projects.txt'))]
suggestions = lookups.get_awesomebar_suggestions(g.autocomplete_projects, query)
return Response(json.dumps([{'value': s} for s in suggestions]), mimetype='application/json')
@app.route('/<project_genome>/<project_name>/<sample_name>/awesome')
def awesome(project_genome, sample_name, project_name):
db = get_db()
query = request.args.get('query')
datatype, identifier = lookups.get_awesomebar_result(db, project_name, project_genome, sample_name, query)
print("Searched for %s: %s" % (datatype, identifier))
if datatype == 'gene':
return redirect('/{}/{}/{}/gene/{}'.format(project_genome, project_name, sample_name, identifier))
elif datatype == 'transcript':
return redirect('/{}/{}/{}/transcript/{}'.format(project_genome, project_name, sample_name, identifier))
elif datatype == 'variant':
return redirect('/{}/{}/{}/variant/{}'.format(project_genome, project_name, sample_name, identifier))
elif datatype == 'region':
return redirect('/{}/{}/{}/region/{}'.format(project_genome, project_name, sample_name, identifier))
elif datatype == 'dbsnp_variant_set':
return redirect('/{}/{}/{}/dbsnp/{}'.format(project_genome, project_name, sample_name, identifier))
elif datatype == 'error':
return redirect('/{}/{}/{}/error/{}'.format(project_genome, project_name, sample_name, identifier))
elif datatype == 'not_found':
return redirect('/{}/{}/{}/not_found/{}'.format(project_genome, project_name, sample_name, identifier))
else:
raise Exception
@app.route('/<project_genome>/<project_name>/awesome')
def awesome_project(project_genome, project_name):
db = get_db()
query = request.args.get('query')
datatype, identifier = lookups.get_awesomebar_result(db, project_name, project_genome, None, query)
print("Searched for %s: %s" % (datatype, identifier))
if datatype == 'gene':
return redirect('/{}/{}/gene/{}'.format(project_genome, project_name, identifier))
elif datatype == 'transcript':
return redirect('/{}/{}/transcript/{}'.format(project_genome, project_name, identifier))
elif datatype == 'variant':
return redirect('/{}/{}/variant/{}'.format(project_genome, project_name, identifier))
elif datatype == 'region':
return redirect('/{}/{}/region/{}'.format(project_genome, project_name, identifier))
elif datatype == 'dbsnp_variant_set':
return redirect('/{}/{}/dbsnp/{}'.format(project_genome, project_name, identifier))
elif datatype == 'error':
return redirect('/{}/{}/error/{}'.format(project_genome, project_name, identifier))
elif datatype == 'not_found':
return redirect('/{}/{}/not_found/{}'.format(project_genome, project_name, identifier))
else:
raise Exception
@app.route('/awesomeproject')
def awesomeproject():
db = get_db()
query = request.args.get('query')
project = lookups.get_project_by_project_name(db, query)
if project:
return redirect('/{}/{}'.format(project['genome'], project['name']))
return redirect('/not_found/{}'.format(query))
@app.route('/<project_genome>/<project_name>/variant/<variant_str>')
def variant_page_project(project_name, project_genome, variant_str):
return variant_page(project_name, project_genome, sample_name=None, variant_str=variant_str)
@app.route('/<project_genome>/<project_name>/<sample_name>/variant/<variant_str>')
def variant_page(project_name, project_genome, sample_name, variant_str):
check_project_exists(project_name)
db = get_db()
sample_names = lookups.get_project_samples(db, project_name, project_genome)
try:
chrom, pos, ref, alt = variant_str.split('-')
pos = int(pos)
# pos, ref, alt = get_minimal_representation(pos, ref, alt)
xpos = get_xpos(chrom, pos)
variant = lookups.get_variant(db, project_name, project_genome, xpos, ref, alt)
if variant is None:
variant = {
'chrom': chrom,
'pos': pos,
'xpos': xpos,
'ref': ref,
'alt': alt
}
consequences = OrderedDict()
if 'vep_annotations' in variant:
add_consequence_to_variant(variant)
variant['vep_annotations'] = remove_extraneous_vep_annotations(variant['vep_annotations'])
variant['vep_annotations'] = order_vep_by_csq(variant['vep_annotations']) # Adds major_consequence
for annotation in variant['vep_annotations']:
annotation['HGVS'] = get_proper_hgvs(annotation)
consequences.setdefault(annotation['major_consequence'], {}).setdefault(annotation['Gene_Name'], []).append(annotation)
base_coverage = lookups.get_coverage_for_bases(db, xpos, xpos + len(ref) - 1, project_name, project_genome, sample_name)
any_covered = any([x['has_coverage'] for x in base_coverage])
metrics = lookups.get_metrics(db, project_name, project_genome, variant)
igv_genes_path = ''
if project_genome == 'hg19':
igv_genes_path = '//igv.broadinstitute.org/annotations/hg19/genes/gencode.v18.collapsed.bed'
igv_genes_index = igv_genes_path + '.idx'
elif project_genome == 'hg38':
igv_genes_path = '//igv.broadinstitute.org/annotations/hg38/genes/gencode.v24.annotation.sorted.gtf.gz'
igv_genes_index = igv_genes_path + '.tbi'
# check the appropriate sqlite db to get the *expected* number of
# available bams and *actual* number of available bams for this variant
sqlite_db_path = os.path.join(
app.config["READ_VIZ_DIR"],
"combined_bams",
chrom,
"combined_chr%s_%03d.db" % (chrom, pos % 1000))
logging.info(sqlite_db_path)
try:
read_viz_db = sqlite3.connect(sqlite_db_path)
if chrom in ('X', 'Y'):
n_het = read_viz_db.execute("select n_expected_samples, n_available_samples from t "
"where chrom=? and pos=? and ref=? and alt=? and het_or_hom_or_hemi=?", (chrom, pos, ref, alt, 'het')).fetchone()
n_hom = read_viz_db.execute("select n_expected_samples, n_available_samples from t "
"where chrom=? and pos=? and ref=? and alt=? and het_or_hom_or_hemi=?", (chrom, pos, ref, alt, 'hom')).fetchone()
n_hemi = read_viz_db.execute("select n_expected_samples, n_available_samples from t "
"where chrom=? and pos=? and ref=? and alt=? and het_or_hom_or_hemi=?", (chrom, pos, ref, alt, 'hemi')).fetchone()
else:
n_het = read_viz_db.execute("select n_expected_samples, n_available_samples from t "
"where chrom=? and pos=? and ref=? and alt=? and het_or_hom=?", (chrom, pos, ref, alt, 'het')).fetchone()
n_hom = read_viz_db.execute("select n_expected_samples, n_available_samples from t "
"where chrom=? and pos=? and ref=? and alt=? and het_or_hom=?", (chrom, pos, ref, alt, 'hom')).fetchone()
n_hemi = None
read_viz_db.close()
except Exception, e:
logging.debug("Error when accessing sqlite db: %s - %s", sqlite_db_path, e)
n_het = n_hom = n_hemi = None
read_viz_dict = {
'het': {'n_expected': n_het[0] if n_het is not None and n_het[0] is not None else -1, 'n_available': n_het[1] if n_het and n_het[1] else 0,},
'hom': {'n_expected': n_hom[0] if n_hom is not None and n_hom[0] is not None else -1, 'n_available': n_hom[1] if n_hom and n_hom[1] else 0,},
'hemi': {'n_expected': n_hemi[0] if n_hemi is not None and n_hemi[0] is not None else -1, 'n_available': n_hemi[1] if n_hemi and n_hemi[1] else 0,},
}
for het_or_hom_or_hemi in ('het', 'hom', 'hemi'):
#read_viz_dict[het_or_hom_or_hemi]['some_samples_missing'] = (read_viz_dict[het_or_hom_or_hemi]['n_expected'] > 0) and (read_viz_dict[het_or_hom_or_hemi]['n_expected'] - read_viz_dict[het_or_hom_or_hemi]['n_available'] > 0)
read_viz_dict[het_or_hom_or_hemi]['all_samples_missing'] = (read_viz_dict[het_or_hom_or_hemi]['n_expected'] != 0) and (read_viz_dict[het_or_hom_or_hemi]['n_available'] == 0)
read_viz_dict[het_or_hom_or_hemi]['readgroups'] = [
'%(chrom)s-%(pos)s-%(ref)s-%(alt)s_%(het_or_hom_or_hemi)s%(i)s' % locals()
for i in range(read_viz_dict[het_or_hom_or_hemi]['n_available'])
] #eg. '1-157768000-G-C_hom1',
read_viz_dict[het_or_hom_or_hemi]['urls'] = [
os.path.join('combined_bams', chrom, 'combined_chr%s_%03d.bam' % (chrom, pos % 1000))
for i in range(read_viz_dict[het_or_hom_or_hemi]['n_available'])
]
chrom = chrom.replace('chr', '')
bam_fpath = os.path.join(
app.config["READ_VIZ_DIR_HTML"] % (project_genome, project_name),
"%s-" % chrom)
read_group = None
sample_names = [sample for idx, sample in enumerate(variant['sample_names'])
if variant['sample_data'][idx]]
if sample_name:
sample_names.insert(0, sample_names.pop(sample_names.index(sample_name)))
if 'transcripts' in variant and variant['transcripts']:
for transcript_id in variant['transcripts']:
transcript_exons = lookups.get_exons_in_transcript(db, project_genome, transcript_id)
for idx, exon in enumerate(transcript_exons):
if exon['start'] <= pos <= exon['stop']:
start, end = exon['start'], exon['stop']
transcript = sorted(variant['transcripts'])[0]
read_group = '{chrom}-{transcript}-{idx}-'.format(**locals())
break
if read_group:
break
if not read_group:
read_group = '%(chrom)s-%(pos)s-%(ref)s-%(alt)s-' % locals()
print('Rendering variant: %s' % variant_str)
return render_template(