-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunAlbacore.py
executable file
·377 lines (328 loc) · 13.7 KB
/
runAlbacore.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
#!/home/sbsuser/.edm/envs/python3/bin/python3
import sys
import os
import re
from random import shuffle
from subprocess import Popen, PIPE
import getopt
import shutil
import h5py
import json
os.environ["HDF5_USE_FILE_LOCKING"] = "FALSE" #caused error w/o this
vpython = '/home/sbsuser/.edm/envs/albacore2.3.4/bin/python'
albacore = vpython + ' /home/sbsuser/.edm/envs/albacore2.3.4/bin/'
albacoreVersion = '2.3.4'
pwd = os.getcwd()
mask = 0o755 #mkdir mask
def usage() :
print("""
To run basecalling:
runAlbacore.py [-abD] [-j n] [-k kit] [-f flowcell_type]
Must be called inside a run directory. Fast5 files will be searched
recursively. Input and output are partitioned into n segments in the
scratch directory.
-j number of jobs to use (default 40)
-D use 1D^2 chemistry
-b use the barcode keyword
-a get flowcell and kit from fast5 file
-f flowcell type (must specify kit too)
-k kit used in sequencing (must specify flowcell too)
Output fastq is located under the stcratch/out directory. A RunInfo json
is also created with all the experiment's details.
To collect results:
runAlbacore.py [-z ] -P
-z compress merged fastq
Will merge fastq and summary files into one file. It also produces
MinionQC for each summary file.
""")
def doBaseCalling(useFast5Info,flowcellType,kit,barcode,D2,chunks) :
#get a list of all the fast5 files
cmd = "lfs find %s -type f -name '*.fast5' 2> /dev/null"%pwd
p = Popen(cmd ,shell=True, stdout=PIPE)
(output, error) = p.communicate()
p.wait()
allFast5 = output.decode('utf-8').split('\n')[:-1]
#include any fast5.tmp files in the list
cmd = "lfs find %s -type f -name '*.fast5.tmp' 2> /dev/null"%pwd
p = Popen(cmd ,shell=True, stdout=PIPE)
(output, error) = p.communicate()
p.wait()
allFast5 += output.decode().split('\n')[:-1]
#initialize values
flowcell = None
start = None
pc = None
runNumber = None
etype = None
minionId = None
minknowV = None
#read experiment info form a fast5 file
f = h5py.File(allFast5[0],'r')
topGroups = list(f.keys())
if ( 'UniqueGlobalKey' in topGroups ) :
globalKey = 'UniqueGlobalKey' #single read fast5
else :
globalKey = list(f.keys())[0] #multi read fast5
flowcellType_fast5 = f['/%s/context_tags/'%globalKey].attrs['flowcell_type'].decode().upper()
kit_fast5 = f['/%s/context_tags/'%globalKey].attrs['sequencing_kit'].decode().upper()
flowcell = f['/%s/tracking_id/'%globalKey].attrs['flow_cell_id'].decode().upper()
start = f['/%s/tracking_id/'%globalKey].attrs['exp_start_time'].decode()
etype = f['/%s/context_tags/'%globalKey].attrs['experiment_type'].decode()
deviceType = f['/%s/tracking_id/'%globalKey].attrs['device_type'].decode()
deviceId = f['/%s/tracking_id/'%globalKey].attrs['device_id'].decode()
minknowV = f['/%s/tracking_id/'%globalKey].attrs['version'].decode()
if ( D2 ) :
chemistry = '1D^2'
else :
chemistry = '1D'
#store all the run parameters in a json
runInfo = { 'flowcell' : flowcell, 'flowcellType' : flowcellType_fast5 , 'kit': kit_fast5 , 'startTime' : start, 'albacoreVersion' : albacoreVersion , 'pc' : pc , 'runNumber' : runNumber, 'barcoded' : barcode, 'experimentType' : etype, 'instrumentType' : deviceType, 'instrumentId' : deviceId, 'minknowCoreVersion' : minknowV, 'chemistry' : chemistry }
f = open('./RunInfo','w')
json.dump(runInfo,f)
f.close()
if ( flowcell == None ) :
print("Flowcell name is not defined in fast5, using None !")
if ( flowcellType_fast5 == '' or kit_fast5 == '') :
exit("Couldn't read run information from fast5 file (flowcell type %s, kit %s)!"%(flowcellType_fast5, kit_fast5) )
if ( useFast5Info ) :
flowcellType= flowcellType_fast5
kit = kit_fast5
else :
if ( flowcellType != flowcellType_fast5 or kit != kit_fast5 ) :
print("Warning specified flowcell %s and kit %s dont match fast5 info ( %s %s"%(flowcellType,kit,flowcellType_fast5,kit_fast5) )
#create the scratch directory tree ( if previous run is found remove them)
# ./scratch/out/??/ for outputs
# ./scratch/in/??/ for inputs
for i in range(chunks) :
rlabel = "%02d"%i
rout = "./scratch/out/%s"%(rlabel)
if ( os.path.exists(rout) ) : shutil.rmtree(rout)
os.makedirs(rout, mode = mask)
rin = "./scratch/in/%s"%(rlabel)
if ( os.path.exists(rin ) ) : shutil.rmtree(rin)
os.makedirs(rin, mode = mask)
#create the symlinks
ichunk = 0
cycles = 0
for ifile in allFast5 :
ifileName = ifile.split('/')[-1]
ifileName = ifileName.replace('.fast5.tmp','.fast5')
indir = "./scratch/in/%02d/"%(ichunk)
src = ifile
dst = indir + ifileName
try :
os.symlink(src, dst)
except :
continue
ichunk += 1
if (ichunk == chunks ) :
cycles += 1
ichunk = 0
#choose basecaller
if ( D2 == True ) :
basecaller = 'full_1dsq_basecaller.py'
else :
basecaller = 'read_fast5_basecaller.py'
#prepare the job array
outfile = open('job.cmd','w')
outfile.write(
"""#!/bin/bash
# @ output = out.%a.log
# @ error = err.%a.log
# @ total_tasks = 1
# @ cpus_per_task = 4
# @ wall_clock_limit = 12:59:00
""")
outfile.write("# @ initialdir = .\n")
outfile.write("# @ job_name = %s\n"%(flowcell))
outfile.write("# @ array = 0-%s\n\n"%(chunks-1))
outfile.write("set -e\n")
for ichunk in range(0,chunks) :
indir = "./scratch/in/%02d"%(ichunk)
outdir = "./scratch/out/%02d"%(ichunk)
cmd = "if [ $SLURM_ARRAY_TASK_ID -eq %s ]; then\n"%(ichunk )
cmd +=" export PYTHONPATH='';time %s/%s"%(albacore,basecaller)
cmd += " -r --flowcell %s --kit %s --output_format fastq --input %s --save_path %s -t 4 --disable_filtering --disable_pings"%(flowcellType,kit,indir,outdir)
if ( barcode ) :
cmd += " --barcoding\n"
else :
cmd += "\n"
cmd += "fi\n"
outfile.write(cmd)
outfile.close()
launch = '/opt/perf/bin/mnsubmit job.cmd'
p = Popen(launch, shell=True, stdout=PIPE, stderr=PIPE)
p.wait()
out = p.stdout.read().decode()
err = p.stderr.read().decode()
if ('ERROR' in err) :
print("!! Error submitting job array to cluster (%s)"%(err))
raise Exception("Error submitting job array to cluster")
print(out)
#merge the resulting fastq and summary files from Albacore basecalling
#make MinionQC plots for each summary file
#compress the merged fastqs
def doPost(pigz) :
#use this pigz
pigz = '/apps/PIGZ/2.3.1/bin/pigz'
#barcode names in the LIMS
ONT2LIMS = {
'barcode01' : 'NB01',
'barcode02' : 'NB02',
'barcode03' : 'NB03',
'barcode04' : 'NB04',
'barcode05' : 'NB05',
'barcode06' : 'NB06',
'barcode07' : 'NB07',
'barcode08' : 'NB08',
'barcode09' : 'NB09',
'barcode10' : 'NB10',
'barcode11' : 'NB11',
'barcode12' : 'NB12',
'barcode13' : 'NB13',
'barcode14' : 'NB14',
'barcode15' : 'NB15',
'barcode16' : 'NB16',
'barcode17' : 'NB17',
'barcode18' : 'NB18',
'barcode19' : 'NB19',
'barcode20' : 'NB20',
'barcode21' : 'NB21',
'barcode22' : 'NB22',
'barcode23' : 'NB23',
'barcode24' : 'NB24',
'unclassified' : 'unclassified'
}
#look for the RunInfo file generated by the basecaller script
if ( not os.path.isfile('./RunInfo') ) :
sys.exit( 'File RunInfo not found! Must run basecalling script to generate it.\n')
f= open('./RunInfo','r')
runInfo = json.load(f)
f.close()
#check the barcodes
if ( runInfo['barcoded'] ) :
cmd = "lfs find ./scratch -type d -name 'barcode*' 2> /dev/null "
p = Popen(cmd ,shell=True, stdout=PIPE)
(output, error) = p.communicate()
p.wait()
fout = output.decode().split('\n')[:-1]
barcodes = set()
for iout in fout :
ibar = iout.split('/')[-1]
if ( ibar not in ONT2LIMS ) : continue #barcode must be in the LIMS otherwise ignore
barcodes.add( ibar )
#setup script
outfile = open('.' + '/post.cmd','w')
outfile.write(
"""#!/bin/bash
# @ output = post.out
# @ error = post.err
# @ total_tasks = 1
# @ cpus_per_task = 4
# @ wall_clock_limit = 02:59:00
""")
outfile.write("# @ initialdir = .\n")
outfile.write("# @ job_name = %s_%s_post\n"%(runInfo['flowcell'],1 ))
outfile.write("\n")
outfile.write("module purge\n")
outfile.write("module load gcc/6.3.0\n")
outfile.write("module load R/3.5.0\n")
outfile.write("export R_LIBS_USER=\"/home/sbsuser/MinION/R\"\n\n")
outfile.write("set -e\n\n")
#merge all the fastq files (exclude 1D2 reads)
if ( runInfo['barcoded'] ) :
for ibarcode in ( list(barcodes) + ['unclassified'] ) :
fliName = "%s_%s_%s"%(runInfo['flowcell'],runInfo['runNumber'], ONT2LIMS[ibarcode])
fastqFile = "%s/%s_%s_%s.fastq"%('.',runInfo['flowcell'],runInfo['runNumber'], ONT2LIMS[ibarcode] )
outfile.write("lfs find %s -name '*.fastq' | grep -v '/1dsq_analysis/' | grep '/%s/' | xargs -i cat {} > %s\n"%('.'+"/scratch/out",ibarcode,fastqFile) )
else :
fliName = "%s_%s_%s"%(runInfo['flowcell'],runInfo['runNumber'], '0')
fastqFile = "%s/%s_%s_0.fastq"%('.',runInfo['flowcell'],runInfo['runNumber'])
outfile.write("lfs find %s -name '*.fastq' | grep -v '/1dsq_analysis/' | xargs -i cat {} > %s\n"%('.'+"/scratch/out",fastqFile) )
#merge all the fastq files for 1D2 reads
if ( runInfo['chemistry'] == '1D^2' ) :
if ( not os.path.exists('./1dsq_analysis') ) : os.makedirs('./1dsq_analysis')
fastqFile = "%s/%s_%s_0.fastq"%('./1dsq_analysis',runInfo['flowcell'],runInfo['runNumber'])
outfile.write("lfs find %s -name '*.fastq' | grep '/1dsq_analysis/' | xargs -i cat {} > %s\n"%('.'+"/scratch/out",fastqFile) )
#merge all the sequencing summary files (exclude 1D2 reads)
if ( runInfo['barcoded'] ) :
for ibarcode in ( list(barcodes) + ['unclassified'] ) :
outfile.write("lfs find %s/scratch/out -name 'sequencing_summary.txt' | grep -v '/1dsq_analysis/' | head -1 | xargs head -1 > %s/sequencing_summary.%s.txt\n"%('.','.', ONT2LIMS[ibarcode]))
outfile.write("lfs find %s/scratch/out -name 'sequencing_summary.txt' | grep -v '/1dsq_analysis/' | xargs -i awk \'$20 == \"%s\"\' {} >> %s/sequencing_summary.%s.txt\n"%('.',ibarcode,'.', ONT2LIMS[ibarcode]))
#generate MinionQC plots
outfile.write("Rscript /home/sbsuser/MinION/minion_qc-1.3.0/MinionQC.R -f %s -i %s -o %s/qc_plots/%s\n"%(fliName,'.'+'/sequencing_summary.%s.txt'%ONT2LIMS[ibarcode],'.', ONT2LIMS[ibarcode] ))
else :
outfile.write("lfs find %s/scratch/out -name 'sequencing_summary.txt' | grep -v '/1dsq_analysis/' | head -1 | xargs head -1 > %s/sequencing_summary.0.txt\n"%('.','.'))
outfile.write("lfs find %s/scratch/out -name 'sequencing_summary.txt' | grep -v '/1dsq_analysis/' | xargs -i tail -n+2 {} >> %s/sequencing_summary.0.txt\n"%('.','.'))
outfile.write("Rscript /home/sbsuser/MinION/minion_qc-1.3.0/MinionQC.R -f %s -i %s -o %s/qc_plots/0\n"%(fliName,'.'+'/sequencing_summary.0.txt','.'))
#merge all the sequencing summary files for 1D2 reads
if ( runInfo['chemistry'] == '1D^2' ) :
outfile.write("lfs find %s/scratch/out -name 'sequencing*summary.txt' | grep '/1dsq_analysis/' | head -1 | xargs head -1 > %s/sequencing_summary.txt\n"%('.','1dsq_analysis'))
outfile.write("lfs find %s/scratch/out -name 'sequencing*summary.txt' | grep '/1dsq_analysis/' | xargs -i tail -n+2 {} >> %s/sequencing_summary.txt\n"%('.','1dsq_analysis'))
#compress all the merged fastq files
if ( zz ) :
outfile.write("%s -p4 *.fastq\n"%pigz)
if ( runInfo['chemistry'] == '1D^2' ) :
outfile.write("%s -p4 ./1dsq_analysis/*.fastq\n"%pigz)
#touch post done to show we completed successfully
outfile.write("touch post.done\n\n")
outfile.close()
launch = ['/opt/perf/bin/mnsubmit', '.' + '/post.cmd' ]
p = Popen(launch, stdout=PIPE, stderr=PIPE)
p.wait()
out = p.stdout.read().decode()
err = p.stderr.read().decode()
if ('ERROR' in err) :
print("!! Error submitting job array to cluster (%s)"%(err))
raise Exception("Error submitting job array to cluster")
print(out)
try:
opts, args = getopt.getopt(sys.argv[1:],"k:f:j:abDPz", ["help"])
except getopt.GetoptError as err:
# print help information and exit
print(str(err))
usage()
exit()
kit = None
flowcellType = None
barcode = False
useFast5Info = False
D2 = False
chunks = 40
post = False
zz = False
for iopt,iarg in opts :
if iopt in ("-h", "--help"):
usage()
sys.exit()
if iopt == "-j" :
chunks = int(iarg)
if iopt == "-b" :
barcode = True
if iopt == "-D" :
D2 = True
if iopt == "-f" :
flowcellType = iarg
if iopt == "-k":
kit = iarg
if iopt == "-a" :
useFast5Info = True
if iopt == "-P" :
post = True
if iopt == "-z" :
zz = True
if ( post ) :
doPost(zz)
sys.exit(0)
if ( kit == None and flowcellType == None and useFast5Info == False) :
usage()
exit()
if ( ( kit != None or flowcellType != None) and useFast5Info == True ) :
print("cant specify option -a and manually select flowcell and kit")
usage()
exit()
if ( ( kit == None or flowcellType == None) and useFast5Info == False ) :
print("must specify both flowcell and kit")
usage()
exit()
doBaseCalling(useFast5Info,flowcellType,kit,barcode,D2,chunks)