This repository has been archived by the owner on Mar 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
run_quiver.py
420 lines (359 loc) · 15.3 KB
/
run_quiver.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
from falcon_kit import run_support as support
from pypeflow.simple_pwatcher_bridge import (
PypeLocalFile, makePypeLocalFile, fn,
PypeTask,
PypeProcWatcherWorkflow, MyFakePypeThreadTaskBase)
from falcon_kit.FastaReader import FastaReader
import glob
import json
import logging
import os
import pprint
import re
import sys
import time
import ConfigParser
LOG = logging.getLogger(__name__)
def system(call, check=False):
LOG.debug('$(%s)' %repr(call))
rc = os.system(call)
msg = 'Call %r returned %d.' % (call, rc)
if rc:
LOG.warning(msg)
if check:
raise Exception(msg)
else:
LOG.debug(msg)
return rc
def mkdir(d):
if not os.path.isdir(d):
os.makedirs(d)
def task_track_reads(self):
input_bam_fofn = fn(self.input_bam_fofn)
job_done = fn(self.job_done)
work_dir = os.getcwd()
basedir = '../..' # assuming we are in ./4-quiver/reads/
script_fn = 'track_reads_h.sh'
# For now, in/outputs are in various directories, by convention.
script = """\
set -vex
trap 'touch {job_done}.exit' EXIT
hostname
date
cd {basedir}
fc_get_read_hctg_map.py
fc_rr_hctg_track.py
fc_select_reads_from_bam.py {input_bam_fofn}
date
cd {work_dir}
touch {job_done}
""".format(**locals())
with open(script_fn,'w') as script_file:
script_file.write(script)
self.generated_script_fn = script_fn
def task_run_quiver(self):
ref_fasta = fn(self.ref_fasta)
read_bam = fn(self.read_bam)
cns_fasta = fn(self.cns_fasta)
cns_fastq = fn(self.cns_fastq)
job_done = fn(self.job_done)
job_uid = self.parameters['job_uid']
ctg_id = self.parameters['ctg_id']
smrt_bin = self.parameters['smrt_bin']
samtools = os.path.join(smrt_bin, 'samtools')
pbalign = os.path.join(smrt_bin, 'pbalign')
makePbi = os.path.join(smrt_bin, 'makePbi')
variantCaller = os.path.join(smrt_bin, 'variantCaller')
script_fn = 'cns_%s.sh' % (ctg_id)
script = """\
set -vex
trap 'touch {job_done}.exit' EXIT
hostname
date
{samtools} faidx {ref_fasta}
{pbalign} --tmpDir=/localdisk/scratch/ --nproc=24 --minAccuracy=0.75 --minLength=50\
--minAnchorSize=12 --maxDivergence=30 --concordant --algorithm=blasr\
--algorithmOptions=--useQuality --maxHits=1 --hitPolicy=random --seed=1\
{read_bam} {ref_fasta} aln-{ctg_id}.bam
({variantCaller} --algorithm=arrow -x 5 -X 120 -q 20 -j 24 -r {ref_fasta} aln-{ctg_id}.bam\
-o {cns_fasta} -o {cns_fastq}) || echo quvier failed
date
touch {job_done}
""".format(**locals())
with open(script_fn,'w') as script_file:
script_file.write(script)
self.generated_script_fn = script_fn
def rm(f):
system('rm -f {}'.format(f))
def touch(f):
system('touch {}'.format(f))
def task_cns_zcat(self):
gathered_p_ctg_fn = fn(self.gathered_p_ctg)
gathered_h_ctg_fn = fn(self.gathered_h_ctg)
cns_p_ctg_fasta_fn = fn(self.cns_p_ctg_fasta)
cns_p_ctg_fastq_fn = fn(self.cns_p_ctg_fastq)
cns_h_ctg_fasta_fn = fn(self.cns_h_ctg_fasta)
cns_h_ctg_fastq_fn = fn(self.cns_h_ctg_fastq)
job_done_fn = fn(self.job_done)
rm(cns_p_ctg_fasta_fn)
touch(cns_p_ctg_fasta_fn)
rm(cns_p_ctg_fastq_fn)
touch(cns_p_ctg_fastq_fn)
with open(gathered_p_ctg_fn) as ifs:
for line in ifs:
cns_fasta_fn, cns_fastq_fn = line.split()
system('zcat {cns_fasta_fn} >> {cns_p_ctg_fasta_fn}'.format(**locals()))
system('zcat {cns_fastq_fn} >> {cns_p_ctg_fastq_fn}'.format(**locals()))
# comment out this for now for recovering purpose
#with open(gathered_p_ctg_fn) as ifs:
# for line in ifs:
# cns_fasta_fn, cns_fastq_fn = line.split()
# rm(cns_fasta_fn)
# rm(cns_fasta_fn)
rm(cns_h_ctg_fasta_fn)
touch(cns_h_ctg_fasta_fn)
rm(cns_h_ctg_fastq_fn)
touch(cns_h_ctg_fastq_fn)
with open(gathered_h_ctg_fn) as ifs:
for line in ifs:
cns_fasta_fn, cns_fastq_fn = line.split()
system('zcat {cns_fasta_fn} >> {cns_h_ctg_fasta_fn}'.format(**locals()))
system('zcat {cns_fastq_fn} >> {cns_h_ctg_fastq_fn}'.format(**locals()))
# comment out this for now for recovering purpose
#with open(gathered_h_ctg_fn) as ifs:
# for line in ifs:
# cns_fasta_fn, cns_fastq_fn = line.split()
# rm(cns_fasta_fn)
# rm(cns_fasta_fn)
touch(job_done_fn)
def task_scatter_quiver(self):
p_ctg_fn = fn(self.p_ctg_fa)
h_ctg_fn = fn(self.h_ctg_fa)
out_json = fn(self.scattered_quiver_json)
track_reads_h_done_fn = fn(self.track_reads_h_done)
bam_dir = os.path.dirname(track_reads_h_done_fn)
config = self.parameters['config']
ref_seq_data = {}
# I think this will crash if the file is empty. Maybe that is ok.
p_ctg_fa = FastaReader(p_ctg_fn)
ctg_types = {}
for r in p_ctg_fa:
rid = r.name.split()[0]
ref_seq_data[rid] = r.sequence
ctg_types[rid] = 'p'
# I think this will crash if the file is empty. Maybe that is ok.
h_ctg_fa = FastaReader(h_ctg_fn)
for r in h_ctg_fa:
rid = r.name.split()[0]
ref_seq_data[rid] = r.sequence
ctg_types[rid] = 'h'
ctg_ids = sorted(ref_seq_data.keys())
#p_ctg_out=[]
#h_ctg_out=[]
#job_done_plfs = {}
jobs = []
for ctg_id in ctg_ids:
sequence = ref_seq_data[ctg_id]
m_ctg_id = ctg_id.split('-')[0]
wd = os.path.join(os.getcwd(), m_ctg_id)
ref_fasta = os.path.join(wd, '{ctg_id}_ref.fa'.format(ctg_id = ctg_id))
read_bam = os.path.join(bam_dir, '{ctg_id}.bam'.format(ctg_id = ctg_id))
#cns_fasta = makePypeLocalFile(os.path.join(wd, 'cns-{ctg_id}.fasta.gz'.format(ctg_id = ctg_id)))
#cns_fastq = makePypeLocalFile(os.path.join(wd, 'cns-{ctg_id}.fastq.gz'.format(ctg_id = ctg_id)))
#job_done = makePypeLocalFile(os.path.join(wd, '{ctg_id}_quiver_done'.format(ctg_id = ctg_id)))
if os.path.exists(read_bam):
# *.sam are created in task_track_reads, fc_select_reads_from_bam.py
# Network latency should not matter because we have already waited for the 'done' file.
mkdir(wd)
if not os.path.exists(ref_fasta):
# TODO(CD): Up to 50MB of seq data. Should do this on remote host.
# See https://github.com/PacificBiosciences/FALCON_unzip/issues/59
with open(ref_fasta,'w') as f:
print >>f, '>'+ctg_id
print >>f, sequence
new_job = {}
new_job['ctg_id'] = ctg_id
new_job['ctg_types'] = ctg_types
new_job['smrt_bin'] = config['smrt_bin']
new_job['sge_option'] = config['sge_quiver']
new_job['ref_fasta'] = ref_fasta
new_job['read_bam'] = read_bam
jobs.append(new_job)
open(out_json, 'w').write(json.dumps(jobs))
def create_quiver_jobs(wf, scattered_quiver_plf):
scattered_quiver_fn = fn(scattered_quiver_plf)
jobs = json.loads(open(scattered_quiver_fn).read())
#ctg_ids = sorted(jobs['ref_seq_data'])
p_ctg_out=[]
h_ctg_out=[]
job_done_plfs = {}
for job in jobs:
ctg_id = job['ctg_id']
ctg_types = job['ctg_types']
smrt_bin = job['smrt_bin']
sge_option = job['sge_option']
ref_fasta = makePypeLocalFile(job['ref_fasta'])
read_bam = makePypeLocalFile(job['read_bam'])
m_ctg_id = ctg_id.split('-')[0]
wd = os.path.join(os.getcwd(), './4-quiver/', m_ctg_id)
#ref_fasta = makePypeLocalFile(os.path.join(wd, '{ctg_id}_ref.fa'.format(ctg_id = ctg_id)))
#read_bam = makePypeLocalFile(os.path.join(os.getcwd(), './4-quiver/reads/' '{ctg_id}.sam'.format(ctg_id = ctg_id)))
cns_fasta = makePypeLocalFile(os.path.join(wd, 'cns-{ctg_id}.fasta.gz'.format(ctg_id = ctg_id)))
cns_fastq = makePypeLocalFile(os.path.join(wd, 'cns-{ctg_id}.fastq.gz'.format(ctg_id = ctg_id)))
job_done = makePypeLocalFile(os.path.join(wd, '{ctg_id}_quiver_done'.format(ctg_id = ctg_id)))
if os.path.exists(fn(read_bam)): # TODO(CD): Ask Jason what we should do if missing SAM.
if ctg_types[ctg_id] == 'p':
p_ctg_out.append( (fn(cns_fasta), fn(cns_fastq)) )
elif ctg_types[ctg_id] == 'h':
h_ctg_out.append( (fn(cns_fasta), fn(cns_fastq)) )
else:
LOG.warning('Type is {!r}, not "p" or "h". Why are we running Quiver?'.format(ctg_types[ctg_id]))
parameters = {
'job_uid':'q-'+ctg_id,
'ctg_id': ctg_id,
'smrt_bin': smrt_bin,
'sge_option': sge_option,
}
make_quiver_task = PypeTask(inputs = {'ref_fasta': ref_fasta, 'read_bam': read_bam,
'scattered_quiver': scattered_quiver_plf,
},
outputs = {'cns_fasta': cns_fasta, 'cns_fastq': cns_fastq, 'job_done': job_done},
parameters = parameters,
)
quiver_task = make_quiver_task(task_run_quiver)
wf.addTask(quiver_task)
job_done_plfs['{}'.format(ctg_id)] = job_done
return p_ctg_out, h_ctg_out, job_done_plfs
def task_gather_quiver(self):
"""We wrote the "gathered" files during task construction.
"""
job_done_fn = fn(self.job_done)
touch(job_done_fn)
def main(argv=sys.argv):
global LOG
LOG = support.setup_logger(None)
if len(sys.argv) < 2:
print>>sys.stderr, 'you need to provide a configuration file to specific a couple cluster running environment'
sys.exit(1)
config_fn = sys.argv[1]
config_absbasedir = os.path.dirname(os.path.abspath(config_fn))
config = ConfigParser.ConfigParser()
config.read(config_fn)
job_type = 'SGE'
if config.has_option('General', 'job_type'):
job_type = config.get('General', 'job_type')
job_queue = 'default'
if config.has_option('General', 'job_queue'):
job_queue = config.get('General', 'job_queue')
pwatcher_type = 'fs_based'
if config.has_option('General', 'pwatcher_type'):
pwatcher_type = config.get('General', 'pwatcher_type')
sge_track_reads = ' -pe smp 12 -q bigmem'
if config.has_option('Unzip', 'sge_track_reads'):
sge_track_reads = config.get('Unzip', 'sge_track_reads')
sge_quiver = ' -pe smp 24 -q bigmem '
if config.has_option('Unzip', 'sge_quiver'):
sge_quiver = config.get('Unzip', 'sge_quiver')
smrt_bin = '/mnt/secondary/builds/full/3.0.0/prod/smrtanalysis_3.0.0.153854/smrtcmds/bin/'
if config.has_option('Unzip', 'smrt_bin'):
smrt_bin = config.get('Unzip', 'smrt_bin')
input_bam_fofn = 'input_bam.fofn'
if config.has_option('Unzip', 'input_bam_fofn'):
input_bam_fofn = config.get('Unzip', 'input_bam_fofn')
if not os.path.isabs(input_bam_fofn):
input_bam_fofn = os.path.join(config_absbasedir, input_bam_fofn)
quiver_concurrent_jobs = 8
if config.has_option('Unzip', 'quiver_concurrent_jobs'):
quiver_concurrent_jobs = config.getint('Unzip', 'quiver_concurrent_jobs')
config = {'job_type': job_type,
'job_queue': job_queue,
'sge_quiver': sge_quiver,
'sge_track_reads': sge_track_reads,
'input_bam_fofn': input_bam_fofn,
'pwatcher_type': pwatcher_type,
'smrt_bin': smrt_bin}
LOG.info('config={}'.format(pprint.pformat(config)))
#support.job_type = 'SGE' #tmp hack until we have a configuration parser
wf = PypeProcWatcherWorkflow(
max_jobs=quiver_concurrent_jobs,
job_type=config['job_type'],
job_queue=config.get('job_queue'),
sge_option=config.get('sge_option'),
watcher_type=config.get('pwatcher_type'),
#watcher_directory=config.get('pwatcher_directory', 'mypwatcher'),
use_tmpdir=config.get('use_tmpdir'),
)
abscwd = os.path.abspath('.')
parameters = {
'sge_option': config['sge_track_reads'],
}
input_bam_fofn_fn = config['input_bam_fofn']
input_bam_fofn_plf = makePypeLocalFile(input_bam_fofn_fn)
hasm_done_plf = makePypeLocalFile('./3-unzip/1-hasm/hasm_done') # by convention
track_reads_h_done_plf = makePypeLocalFile('./4-quiver/reads/track_reads_h_done')
make_track_reads_task = PypeTask(inputs = {
'input_bam_fofn': input_bam_fofn_plf,
'hasm_done': hasm_done_plf},
outputs = {'job_done': track_reads_h_done_plf},
parameters = parameters,
)
track_reads_task = make_track_reads_task(task_track_reads)
wf.addTask(track_reads_task)
scattered_quiver_plf = makePypeLocalFile('4-quiver/quiver_scatter/scattered.json')
parameters = {
'config': config,
}
make_task = PypeTask(
inputs = {
'p_ctg_fa': makePypeLocalFile('3-unzip/all_p_ctg.fa'),
'h_ctg_fa': makePypeLocalFile('3-unzip/all_h_ctg.fa'),
'track_reads_h_done': track_reads_h_done_plf,
},
outputs = {
'scattered_quiver_json': scattered_quiver_plf,
},
parameters = parameters,
)
wf.addTask(make_task(task_scatter_quiver))
wf.refreshTargets()
p_ctg_out, h_ctg_out, job_done_plfs = create_quiver_jobs(wf, scattered_quiver_plf)
gathered_p_ctg_plf = makePypeLocalFile('4-quiver/cns_gather/p_ctg.txt')
gathered_h_ctg_plf = makePypeLocalFile('4-quiver/cns_gather/h_ctg.txt')
gather_done_plf = makePypeLocalFile('4-quiver/cns_gather/job_done')
mkdir('4-quiver/cns_gather')
with open(fn(gathered_p_ctg_plf), 'w') as ifs:
for cns_fasta_fn, cns_fastq_fn in sorted(p_ctg_out):
ifs.write('{} {}\n'.format(cns_fasta_fn, cns_fastq_fn))
with open(fn(gathered_h_ctg_plf), 'w') as ifs:
for cns_fasta_fn, cns_fastq_fn in sorted(h_ctg_out):
ifs.write('{} {}\n'.format(cns_fasta_fn, cns_fastq_fn))
make_task = PypeTask(
inputs = job_done_plfs,
outputs = {
'job_done': gather_done_plf,
},
parameters = {},
)
wf.addTask(make_task(task_gather_quiver))
wf.refreshTargets()
cns_p_ctg_fasta_plf = makePypeLocalFile('4-quiver/cns_output/cns_p_ctg.fasta')
cns_p_ctg_fastq_plf = makePypeLocalFile('4-quiver/cns_output/cns_p_ctg.fastq')
cns_h_ctg_fasta_plf = makePypeLocalFile('4-quiver/cns_output/cns_h_ctg.fasta')
cns_h_ctg_fastq_plf = makePypeLocalFile('4-quiver/cns_output/cns_h_ctg.fastq')
zcat_done_plf = makePypeLocalFile('4-quiver/cns_output/job_done')
make_task = PypeTask(
inputs = {
'gathered_p_ctg': gathered_p_ctg_plf,
'gathered_h_ctg': gathered_h_ctg_plf,
'gather_done': gather_done_plf,
},
outputs = {
'cns_p_ctg_fasta': cns_p_ctg_fasta_plf,
'cns_p_ctg_fastq': cns_p_ctg_fastq_plf,
'cns_h_ctg_fasta': cns_h_ctg_fasta_plf,
'cns_h_ctg_fastq': cns_h_ctg_fastq_plf,
'job_done': zcat_done_plf,
},
)
wf.addTask(make_task(task_cns_zcat))
wf.refreshTargets()