forked from aryeelab/umi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
demultiplex.py
173 lines (154 loc) · 6.71 KB
/
demultiplex.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
from __future__ import print_function
import os
import re
import gzip
import itertools
import argparse
import time
import logging
import sys
__author__ = 'Martin Aryee'
logger = logging.getLogger('root')
#args = {'out_dir':'/PHShome/ma695/tmp', 'min_reads':10}
#base = '/data/joung/sequencing_bcl/131007_M01326_0075_000000000-A6B33/Data/Intensities/BaseCalls'
#args['read1'] = os.path.join(base, 'Undetermined_S0_L001_R1_001.fastq.gz')
#args['read2'] = os.path.join(base, 'Undetermined_S0_L001_R2_001.fastq.gz')
#args['index1'] = os.path.join(base, 'Undetermined_S0_L001_I1_001.fastq.gz')
#args['index2'] = os.path.join(base, 'Undetermined_S0_L001_I2_001.fastq.gz')
def fq(file):
if re.search('.gz$', file):
fastq = gzip.open(file, 'rb')
else:
fastq = open(file, 'r')
with fastq as f:
while True:
l1 = f.readline()
if not l1:
break
l2 = f.readline()
l3 = f.readline()
l4 = f.readline()
yield [l1, l2, l3, l4]
def get_sample_id(i1, i2, sample_names):
seq1 = i1[1]
seq2 = i2[1]
sample_barcode = seq1[1:8] + seq2[1:8]
if sample_barcode in sample_names:
return sample_names[sample_barcode]
else:
return sample_barcode
def demultiplex(read1, read2, index1, index2, sample_barcodes, out_dir, min_reads=10000):
if not os.path.exists(out_dir):
os.makedirs(out_dir)
if type(sample_barcodes) != dict:
sample_names = {}
if not sample_barcodes==None:
for line in open(sample_barcodes, 'r'):
fields = line.strip().split('\t')
if len(fields)==2:
sampleid, barcode = fields
sample_names[barcode] = sampleid
else:
sample_names = sample_barcodes
outfiles_r1 = {}
outfiles_r2 = {}
outfiles_i1 = {}
outfiles_i2 = {}
total_count = 0
count = {}
buffer_r1 = {}
buffer_r2 = {}
buffer_i1 = {}
buffer_i2 = {}
zip_func = itertools.izip if sys.version_info[0] < 3 else zip
#it = itertools.izip(fq(args['read1']), fq(args['read2']), fq(args['index1']), fq(args['index2']))
#for r1,r2,i1,i2 in itertools.islice(it, 0, 100):
start = time.time()
for r1,r2,i1,i2 in zip_func(fq(read1), fq(read2), fq(index1), fq(index2)):
total_count += 1
if total_count % 1000000 == 0:
logger.info("Processed %d reads in %.1f minutes.", total_count, (time.time()-start)/60)
sample_id = get_sample_id(i1, i2, sample_names)
# Increment read count and create output buffers if this is a new sample barcode
if not count.has_key(sample_id):
count[sample_id] = 0
buffer_r1[sample_id] = []
buffer_r2[sample_id] = []
buffer_i1[sample_id] = []
buffer_i2[sample_id] = []
count[sample_id] += 1
# Write the reads to file or to sample-specific output buffers if we haven't
# reached min_reads
# The buffers are used to avoid writing fastqs for sample barcodes with very few reads.
if count[sample_id] < min_reads:
buffer_r1[sample_id].append(r1)
buffer_r2[sample_id].append(r2)
buffer_i1[sample_id].append(i1)
buffer_i2[sample_id].append(i2)
elif count[sample_id] == min_reads:
outfiles_r1[sample_id] = open(os.path.join(out_dir, '%s.r1.fastq' % sample_id), 'w')
outfiles_r2[sample_id] = open(os.path.join(out_dir, '%s.r2.fastq' % sample_id), 'w')
outfiles_i1[sample_id] = open(os.path.join(out_dir, '%s.i1.fastq' % sample_id), 'w')
outfiles_i2[sample_id] = open(os.path.join(out_dir, '%s.i2.fastq' % sample_id), 'w')
# Spill the buffers to sample-specific fastqs
for record in buffer_r1[sample_id] + r1:
outfiles_r1[sample_id].write(''.join(record))
for record in buffer_r2[sample_id] + r2:
outfiles_r2[sample_id].write(''.join(record))
for record in buffer_i1[sample_id] + i1:
outfiles_i1[sample_id].write(''.join(record))
for record in buffer_i2[sample_id] + i2:
outfiles_i2[sample_id].write(''.join(record))
del buffer_r1[sample_id]
del buffer_r2[sample_id]
del buffer_i1[sample_id]
del buffer_i2[sample_id]
else:
for line in r1:
print (line, file=outfiles_r1[sample_id], end="")
for line in r2:
print (line, file=outfiles_r2[sample_id], end="")
for line in i1:
print (line, file=outfiles_i1[sample_id], end="")
for line in i2:
print (line, file=outfiles_i2[sample_id], end="")
# Write remaining buffered reads to a single fastq.
# (These reads correspond to barcodes that were seen less than min_reads times)
undetermined_r1 = open(os.path.join(out_dir, 'undetermined.r1.fastq'), 'w')
undetermined_r2 = open(os.path.join(out_dir, 'undetermined.r2.fastq'), 'w')
undetermined_i1 = open(os.path.join(out_dir, 'undetermined.i1.fastq'), 'w')
undetermined_i2 = open(os.path.join(out_dir, 'undetermined.i2.fastq'), 'w')
for sample_id in buffer_r1.keys():
for record in buffer_r1[sample_id]:
undetermined_r1.write(''.join(record))
for record in buffer_r2[sample_id]:
undetermined_r2.write(''.join(record))
for record in buffer_i1[sample_id]:
undetermined_i1.write(''.join(record))
for record in buffer_i2[sample_id]:
undetermined_i2.write(''.join(record))
# Close files
for sample_id in outfiles_r1:
outfiles_r1[sample_id].close()
outfiles_r2[sample_id].close()
outfiles_i1[sample_id].close()
outfiles_i2[sample_id].close()
undetermined_r1.close()
undetermined_r2.close()
undetermined_i1.close()
undetermined_i2.close()
num_fastqs = len([v for k,v in count.iteritems() if v>=min_reads])
logger.info('Wrote FASTQs for the %d sample barcodes out of %d with at least %d reads.', num_fastqs, len(count), min_reads)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--read1', required=True)
parser.add_argument('--read2', required=True)
parser.add_argument('--index1', required=True)
parser.add_argument('--index2', required=True)
parser.add_argument('--min_reads', type=int, default=10000)
parser.add_argument('--sample_barcodes')
parser.add_argument('--out_dir', default='.')
args = vars(parser.parse_args())
demultiplex(args['read1'], args['read2'], args['index1'], args['index2'], args['sample_barcodes'], args['out_dir'], min_reads=args['min_reads'])
if __name__ == '__main__':
main()