Repository navigation
Expand file tree
/
Copy pathgemini_load.py
More file actions
executable file
·454 lines (365 loc) · 14.1 KB
/
Copy pathgemini_load.py
File metadata and controls
executable file
·454 lines (365 loc) · 14.1 KB
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
#!/usr/bin/env python
# native Python imports
import os.path
import shutil
import sys
import sqlite3
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
import annotations
import subprocess
from cluster_helper.cluster import cluster_view
import database as gemini_db
from gemini_load_chunk import GeminiLoader
import gemini_annotate
import uuid
import time
import datetime
def load(parser, args):
if (args.db is None or args.vcf is None):
parser.print_help()
exit("ERROR: load needs both a VCF file and a database file\n")
annos = annotations.get_anno_files( args )
# force skipping CADD and GERP if the data files have not been installed
if args.skip_cadd is False:
if 'cadd_score' not in annos:
sys.stderr.write("\nCADD scores are not being loaded because the"
" annotation file could not be found.\n"
"`Run gemini update --dataonly --extra cadd_score`"
" to install the annotation file.\n\n")
args.skip_cadd = True
else:
sys.stderr.write("CADD scores are being loaded (to skip use:--skip-cadd).\n")
if args.skip_gerp_bp is False:
if 'gerp_bp' not in annos:
sys.stderr.write("\nGERP per bp is not being loaded because the annotation file"
" could not be found.\n Run `gemini update --dataonly --extra gerp_bp`"
" to install the annotation file.\n\n")
args.skip_gerp_bp = True
else:
sys.stderr.write("GERP per bp is being loaded (to skip use:--skip-gerp-bp).\n")
# collect of the the add'l annotation files
annotations.load_annos( args )
if args.dbtype == "postgresql":
conn = psycopg2.connect(dbname='postgres', host='localhost')
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
c = conn.cursor()
# This doesn't seem to work. Why?
#c.execute('DROP DATABASE ' + 'gemini_test')
#c.execute('CREATE DATABASE ' + 'gemini_test')
import database_postgresql
database_postgresql.drop_tables(c)
database_postgresql.create_tables(c)
database_postgresql.create_sample_table(c, args)
conn.commit()
conn.close()
if args.scheduler:
load_ipython(args)
elif args.cores > 1:
load_multicore(args)
else:
load_singlecore(args)
def load_singlecore(args):
# create a new gemini loader and populate
# the gemini db and files from the VCF
gemini_loader = GeminiLoader(args)
gemini_loader.store_resources()
gemini_loader.store_version()
gemini_loader.populate_from_vcf()
if not args.skip_gene_tables and not args.test_mode:
gemini_loader.update_gene_table()
if not args.no_genotypes and not args.no_load_genotypes:
gemini_loader.store_sample_gt_counts()
gemini_annotate.add_extras(args.db, [args.db])
if not args.test_mode:
gemini_loader.build_indices_and_disconnect()
def load_multicore(args):
grabix_file = bgzip(args.vcf)
chunks = load_chunks_multicore(grabix_file, args)
if args.dbtype == "sqlite":
merge_chunks_multicore(chunks, args.db)
gemini_annotate.add_extras(args.db, chunks)
def load_ipython(args):
grabix_file = bgzip(args.vcf)
with cluster_view(*get_ipython_args(args)) as view:
chunks = load_chunks_ipython(grabix_file, args, view)
merge_chunks_ipython(chunks, args.db, view)
gemini_annotate.add_extras(args.db, chunks)
def merge_chunks(chunks, db):
cmd = get_merge_chunks_cmd(chunks, db)
print "Merging chunks."
subprocess.check_call(cmd, shell=True)
cleanup_temp_db_files(chunks)
return db
def get_merge_chunks_cmd(chunks, db):
chunk_names = ""
for chunk in chunks:
chunk_names += " --chunkdb " + chunk
return "gemini merge_chunks {chunk_names} --db {db}".format(**locals())
def merge_chunks_ipython(chunks, db, view):
if len(chunks) == 1:
shutil.move(chunks[0], db)
return db
else:
sub_merges = get_chunks_to_merge(chunks)
tmp_dbs = get_temp_dbs(len(sub_merges), os.path.dirname(sub_merges[0][0]))
view.map(merge_chunks, sub_merges, tmp_dbs)
merge_chunks_ipython(tmp_dbs, db, view)
def merge_chunks_multicore(chunks, db):
if len(chunks) <= 1:
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
print st, "indexing final database."
shutil.move(chunks[0], db)
main_conn = sqlite3.connect(db)
main_conn.isolation_level = None
main_curr = main_conn.cursor()
main_curr.execute('PRAGMA synchronous = OFF')
main_curr.execute('PRAGMA journal_mode=MEMORY')
gemini_db.create_indices(main_curr)
main_conn.commit()
main_curr.close()
return db
else:
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
print st, "merging", len(chunks), "chunks."
procs = []
sub_merges = get_chunks_to_merge(chunks)
tmp_dbs = get_temp_dbs(len(sub_merges), os.path.dirname(sub_merges[0][0]))
for sub_merge, tmp_db in zip(sub_merges, tmp_dbs):
cmd = get_merge_chunks_cmd(sub_merge, tmp_db)
procs.append(subprocess.Popen(cmd, shell=True))
wait_until_finished(procs)
cleanup_temp_db_files(chunks)
merge_chunks_multicore(tmp_dbs, db)
def get_chunks_to_merge(chunks):
sublist = list_to_sublists(chunks, 2)
if len(sublist[-1]) > 1:
return sublist
else:
sublist[-2].extend(sublist[-1])
return sublist[:-1]
def list_to_sublists(l, n):
""" convert list l to sublists of length n """
return [l[i:i+n] for i in xrange(0, len(l), n)]
def get_temp_dbs(n, tmp_dir):
return [os.path.join(tmp_dir, str(uuid.uuid4())) + ".db" for _ in xrange(n)]
def get_chunk_name(chunk):
return "--chunkdb " + chunk
def load_chunks_multicore(grabix_file, args):
cores = args.cores
# specify the PED file if given one
ped_file = ""
if args.ped_file is not None:
ped_file = "-p " + args.ped_file
# specify the annotation type if given one
anno_type = ""
if args.anno_type is not None:
anno_type = "-t " + args.anno_type
dbtype = ""
if args.dbtype is not None:
dbtype = "--dbtype " + args.dbtype
no_genotypes = ""
if args.no_genotypes is True:
no_genotypes = "--no-genotypes"
no_load_genotypes = ""
if args.no_load_genotypes is True:
no_load_genotypes = "--no-load-genotypes"
skip_gerp_bp = ""
if args.skip_gerp_bp is True:
skip_gerp_bp = "--skip-gerp-bp"
skip_gene_tables = ""
if args.skip_gene_tables is True:
skip_gene_tables = "--skip-gene-tables"
skip_cadd = ""
if args.skip_cadd is True:
skip_cadd = "--skip-cadd"
test_mode = ""
if args.test_mode is True:
test_mode = "--test-mode"
passonly = ""
if args.passonly is True:
passonly = "--passonly"
skip_info_string = ""
if args.skip_info_string is True:
skip_info_string = "--skip-info-string"
submit_command = "{cmd}"
vcf, _ = os.path.splitext(grabix_file)
chunk_steps = get_chunk_steps(grabix_file, args)
chunk_vcfs = []
chunk_dbs = []
procs = []
for chunk_num, chunk in chunk_steps:
start, stop = chunk
print "Loading chunk " + str(chunk_num) + "."
gemini_load = gemini_pipe_load_cmd().format(**locals())
procs.append(subprocess.Popen(submit_command.format(cmd=gemini_load),
shell=True))
chunk_vcf = vcf + ".chunk" + str(chunk_num)
chunk_vcfs.append(chunk_vcf)
chunk_dbs.append(chunk_vcf + ".db")
wait_until_finished(procs)
print "Done loading {0} variants in {1} chunks.".format(stop, chunk_num+1)
return chunk_dbs
def load_chunks_ipython(grabix_file, args, view):
# specify the PED file if given one
ped_file = ""
if args.ped_file is not None:
ped_file = "-p " + args.ped_file
# specify the annotation type if given one
anno_type = ""
if args.anno_type is not None:
anno_type = "-t " + args.anno_type
dbtype = ""
if args.dbtype is not None:
dbtype = "--dbtype " + args.dbtype
no_genotypes = ""
if args.no_genotypes is True:
no_genotypes = "--no-genotypes"
no_load_genotypes = ""
if args.no_load_genotypes is True:
no_load_genotypes = "--no-load-genotypes"
skip_gerp_bp = ""
8000
div>
if args.skip_gerp_bp is True:
skip_gerp_bp = "--skip-gerp-bp"
skip_gene_tables = ""
if args.skip_gene_tables is True:
skip_gene_tables = "--skip-gene-tables"
skip_cadd = ""
if args.skip_cadd is True:
skip_cadd = "--skip-cadd"
test_mode = ""
if args.test_mode is True:
test_mode = "--test-mode"
passonly = ""
if args.passonly is True:
passonly = "--passonly"
skip_info_string = ""
if args.skip_info_string is True:
skip_info_string = "--skip-info-string"
vcf, _ = os.path.splitext(grabix_file)
chunk_steps = get_chunk_steps(grabix_file, args)
total_chunks = len(chunk_steps)
scheduler, queue, cores = get_ipython_args(args)
load_args = {"ped_file": ped_file,
"anno_type": anno_type,
"vcf": vcf,
"grabix_file": grabix_file,
"no_genotypes": no_genotypes,
"no_load_genotypes": no_load_genotypes,
"skip_gerp_bp": skip_gerp_bp,
"skip_gene_tables": skip_gene_tables,
"skip_cadd": skip_cadd,
"test_mode": test_mode,
"passonly": passonly,
"skip_info_string": skip_info_string}
chunk_dbs = view.map(load_chunk, chunk_steps, [load_args] * total_chunks)
print "Done loading variants in {0} chunks.".format(total_chunks)
return chunk_dbs
def load_chunk(chunk_step, kwargs):
chunk_num, chunk = chunk_step
start, stop = chunk
args = combine_dicts(locals(), kwargs)
gemini_load = gemini_pipe_load_cmd().format(**args)
subprocess.check_call(gemini_load, shell=True)
chunk_db = args["vcf"] + ".chunk" + str(chunk_num) + ".db"
return chunk_db
def wait_until_finished(procs):
[p.wait() for p in procs]
def cleanup_temp_db_files(chunk_dbs):
for chunk_db in chunk_dbs:
os.remove(chunk_db)
def gemini_pipe_load_cmd():
grabix_cmd = "grabix grab {grabix_file} {start} {stop}"
gemini_load_cmd = ("gemini load_chunk -v - {anno_type} {dbtype} {ped_file}"
" {no_genotypes} {no_load_genotypes} {no_genotypes}"
" {skip_gerp_bp} {skip_gene_tables} {skip_cadd}"
" {passonly} {skip_info_string} {test_mode}"
" -o {start} {vcf}.chunk{chunk_num}.db")
return " | ".join([grabix_cmd, gemini_load_cmd])
def get_chunk_steps(grabix_file, args):
index_file = grabix_index(grabix_file)
num_lines = get_num_lines(index_file)
chunk_size = int(num_lines) / int(args.cores)
print "Breaking {0} into {1} chunks.".format(grabix_file, args.cores)
starts = []
stops = []
for chunk in range(0, int(args.cores)):
start = (chunk * chunk_size) + 1
stop = start + chunk_size - 1
# make sure the last chunk covers the remaining lines
if chunk >= (args.cores - 1) and stop < num_lines:
stop = num_lines
starts.append(start)
stops.append(stop)
return list(enumerate(zip(starts, stops)))
def get_num_lines(index_file):
with open(index_file) as index_handle:
index_handle.next()
num_lines = int(index_handle.next().strip())
print "Loading %d variants." % (num_lines)
return num_lines
def grabix_index(fname):
if not which("grabix"):
print_cmd_not_found_and_exit("grabix")
index_file = fname + ".gbi"
if file_exists(index_file):
return index_file
print "Indexing {0} with grabix.".format(fname)
subprocess.check_call("grabix index {fname}".format(fname=fname), shell=True)
return index_file
def bgzip(fname):
if not which("bgzip"):
print_cmd_not_found_and_exit("bgzip")
if is_gz_file(fname):
return fname
vcf_time = os.path.getmtime(fname)
bgzip_file = fname + ".gz"
if not file_exists(bgzip_file) or \
(file_exists(bgzip_file) and os.path.getmtime(bgzip_file) < vcf_time):
print "Bgzipping {0} into {1}.".format(fname, fname + ".gz")
subprocess.check_call("bgzip -c {fname} > \
{fname}.gz".format(fname=fname),
shell=True)
elif file_exists(bgzip_file) and os.path.getmtime(bgzip_file) > vcf_time:
print "Loading with existing bgzip ({0}) version of {1}.".format(fname + ".gz", fname)
return bgzip_file
def is_gz_file(fname):
_, ext = os.path.splitext(fname)
if ext == ".gz":
return True
else:
return False
def get_submit_command(args):
return "{cmd}"
def file_exists(fname):
"""Check if a file exists and is non-empty.
"""
return os.path.exists(fname) and os.path.getsize(fname) > 0
def which(program):
""" returns the path to an executable or None if it can't be found
http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
"""
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
def combine_dicts(d1, d2):
return dict(d1.items() + d2.items())
def get_ipython_args(args):
return (args.scheduler, args.queue, args.cores)
def print_cmd_not_found_and_exit(cmd):
sys.stderr.write("Cannot find {cmd}, install it or put it in your "
"path.".format(cmd=cmd))
exit(1)
def use_scheduler(args):
return bool(args.scheduler)