/
demux_utils.py
379 lines (304 loc) · 11.7 KB
/
demux_utils.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
#!/usr/bin/env python
"""
Some utilities used in demux.py for demultiplexing.
"""
# py2/3 compat
try:
from itertools import izip, islice
except ImportError:
from itertools import islice
izip = zip
import os
import gzip
import pickle
from collections import Counter
from loguru import logger
import numpy as np
class BarMatch:
"""
Assign reads to samples based on barcodes and writes stats to
a pickled dict object.
This class is created and run inside the barmatch function() that
is run on remote engines for parallelization. It processes a single
large fastq file. It assigns reads from multiple barcodes to the
same sample name if -technical-replicates.
"""
def __init__(self, data, ftuple, longbar, cutters, matchdict, fidx):
# store attrs
self.data = data
self.longbar = longbar
self.cutters = cutters
self.ftuple = ftuple
self.matchdict = matchdict
self.fidx = fidx
# when to write to disk
self.chunksize = int(1e6)
self.epid = os.getpid()
self.filestat = np.zeros(3, dtype=int)
# store all barcodes observed
self.barhits = {}
for barc in self.matchdict:
self.barhits[barc] = 0
# store reads and bars matched to samples
# store reads per sample (group technical replicates)
self.read1s = {}
self.read2s = {}
self.dbars = {}
self.samplehits = {}
for sname in self.data.barcodes:
if "-technical-replicate-" in sname:
sname = sname.rsplit("-technical-replicate", 1)[0]
self.samplehits[sname] = 0
self.read1s[sname] = []
self.read2s[sname] = []
self.dbars[sname] = set()
# store counts of what didn't match to samples
self.misses = {}
self.misses['_'] = 0
# get the barcode matching function
if self.longbar[1] == 'same':
if self.data.params.datatype == '2brad':
self.demux = getbarcode1
else:
self.demux = getbarcode2
else:
self.demux = getbarcode3
# file i/o handles
self.ofile1 = None
self.ofile2 = None
self.quarts = None
def run(self):
"""
1. Open generators that pull in 4 lines at a time (fastq)
2.
"""
self.open_read_generators()
pkl = self.assign_reads()
self.close_read_generators()
return pkl
def open_read_generators(self):
"""
Gzips are always bytes so let's use rb to make unzipped also bytes.
"""
# get file type
if self.ftuple[0].endswith(".gz"):
self.ofile1 = gzip.open(self.ftuple[0], 'rb')
else:
self.ofile1 = open(self.ftuple[0], 'rb')
# create iterators
fr1 = iter(self.ofile1)
quart1 = izip(fr1, fr1, fr1, fr1)
# create second read iterator for paired data
if self.ftuple[1]:
if self.ftuple[0].endswith(".gz"):
self.ofile2 = gzip.open(self.ftuple[1], 'rb')
else:
self.ofile2 = open(self.ftuple[1], 'rb')
# create iterators
fr2 = iter(self.ofile2)
quart2 = izip(fr2, fr2, fr2, fr2)
self.quarts = izip(quart1, quart2)
else:
self.quarts = izip(quart1, iter(int, 1))
def close_read_generators(self):
"""
Close the file handles that were opened as generators.
"""
self.ofile1.close()
if self.ftuple[1]:
self.ofile2.close()
def assign_reads(self):
"""
Assign reads to samples using barcode matching and the reads
to fastq files. The statistics are stored in a dictionary which
is pickled, and the tmp filename is returned.
"""
while 1:
# read in four lines of data and increase counter
try:
read1, read2 = next(self.quarts)
read1 = list(read1)
self.filestat[0] += 1
except StopIteration:
break
# i7 barcodes (get from name string instead of sequence)
if self.data.hackersonly.demultiplex_on_i7_tags:
barcode = read1[0].decode().rsplit(":", 1)[-1].split("+")[0]
else:
# COMBINATORIAL BARCODES (BCODE1+BCODE2)
if '3rad' in self.data.params.datatype:
barcode1 = find3radbcode(self.cutters, self.longbar, read1)
barcode2 = find3radbcode(self.cutters, self.longbar, read2)
barcode = barcode1 + "+" + barcode2
# USE BARCODE PARSER: length or splitting
else:
# Parse barcode. Uses the parsing function selected above.
barcode = self.demux(self.cutters, read1, self.longbar)
# ensure barcode is string
try:
barcode = barcode.decode()
except AttributeError:
pass
# find if it matches
sname_match = self.matchdict.get(barcode)
if sname_match:
# add to observed set of bars
self.dbars[sname_match].add(barcode)
self.filestat[1:] += 1
self.samplehits[sname_match] += 1
self.barhits[barcode] += 1
if barcode in self.barhits:
self.barhits[barcode] += 1
else:
self.barhits[barcode] = 1
# trim off barcode
lenbar1 = len(barcode)
if '3rad' in self.data.params.datatype:
## Iff 3rad trim the len of the first barcode
lenbar1 = len(barcode1)
lenbar2 = len(barcode2)
# no trim on i7 demux
if self.data.hackersonly.demultiplex_on_i7_tags:
lenbar1 = lenbar2 = 0
# for 2brad we trim the barcode AND the synthetic overhang
# The `+1` is because it trims the newline
if self.data.params.datatype == '2brad':
overlen = len(self.cutters[0][0]) + lenbar1 + 1
read1[1] = read1[1][:-overlen] + b"\n"
read1[3] = read1[3][:-overlen] + b"\n"
else:
read1[1] = read1[1][lenbar1:]
read1[3] = read1[3][lenbar1:]
# Trim barcode off R2 and append. Only 3rad datatype
# pays the cpu cost of splitting R2
if '3rad' in self.data.params.datatype:
read2 = list(read2)
read2[1] = read2[1][lenbar2:]
read2[3] = read2[3][lenbar2:]
# append to sorted reads list
self.read1s[sname_match].append(b"".join(read1).decode())
if 'pair' in self.data.params.datatype:
self.read2s[sname_match].append(b"".join(read2).decode())
else:
self.misses["_"] += 1
if barcode:
self.filestat[1] += 1
# Write to each sample file (pid's have different handles)
if not self.filestat[0] % int(1e6):
# write reads to file
write_to_file(self.data, self.read1s, 1, self.epid)
if 'pair' in self.data.params.datatype:
write_to_file(self.data, self.read2s, 2, self.epid)
# clear out lits of sorted reads
for sname in self.data.barcodes:
if "-technical-replicate-" in sname:
sname = sname.rsplit("-technical-replicate", 1)[0]
self.read1s[sname] = []
self.read2s[sname] = []
## write the remaining reads to file
write_to_file(self.data, self.read1s, 1, self.epid)
if 'pair' in self.data.params.datatype:
write_to_file(self.data, self.read2s, 2, self.epid)
## return stats in saved pickle b/c return_queue is too small
## and the size of the match dictionary can become quite large
samplestats = [self.samplehits, self.barhits, self.misses, self.dbars]
pklname = os.path.join(
self.data.dirs.fastqs,
"tmpstats_{}_{}.pkl".format(self.epid, self.fidx))
with open(pklname, 'wb') as wout:
pickle.dump([self.filestat, samplestats], wout)
logger.debug("dumped stats to {}".format(pklname))
return pklname
def getbarcode1(cutters, read1, longbar):
"find barcode for 2bRAD data"
#+1 is for the \n at the end of the sequence line
lencut = len(cutters[0][0]) + 1
return read1[1][:-lencut][-longbar[0]:]
def getbarcode2(_, read1, longbar):
"finds barcode for invariable length barcode data"
return read1[1][:longbar[0]]
def getbarcode3(cutters, read1, longbar):
"find barcode sequence in the beginning of read"
## default barcode string
for cutter in cutters[0]:
## If the cutter is unambiguous there will only be one.
if not cutter:
continue
# bytes-strings!
search = read1[1][:int(longbar[0] + len(cutter) + 1)]
try:
search = search.decode()
except (AttributeError, TypeError):
pass
try:
cutter = cutter.decode()
except (AttributeError, TypeError):
pass
try:
barcode = search.rsplit(cutter, 1)
except (AttributeError, TypeError):
barcode = search.decode().rsplit(cutter, 1)
if len(barcode) > 1:
return barcode[0]
## No cutter found
return barcode[0]
def find3radbcode(cutters, longbar, read):
"find barcode sequence in the beginning of read"
# default barcode string
for ambigcuts in cutters:
for cutter in ambigcuts:
# If the cutter is unambiguous there will only be one.
if not cutter:
continue
search = read[1][:int(longbar[0] + len(cutter) + 1)]
splitsearch = search.decode().rsplit(cutter, 1)
if len(splitsearch) > 1:
return splitsearch[0]
# No cutter found
return splitsearch[0]
def write_to_file(data, dsort, read, pid):
"""
Writes sorted data to tmp files
"""
if read == 1:
rrr = "R1"
else:
rrr = "R2"
# appends to file for each sample, avoids parallel fighting by using
# pid assigned file handle.
for sname in dsort:
# file out handle
handle = os.path.join(
data.dirs.fastqs,
"tmp_{}_{}_{}.fastq".format(sname, rrr, pid))
# append to this sample name
with open(handle, 'a') as out:
out.write("".join(dsort[sname]))
logger.debug("appending to {}".format(handle))
class Stats:
"""
Used inside BarMatch to store stats nicely.
"""
def __init__(self):
# stats for each raw input file
self.perfile = {}
# stats for each sample
self.fdbars = {}
self.fsamplehits = Counter()
self.fbarhits = Counter()
self.fmisses = Counter()
def fill_from_pickle(self, pkl, handle):
"""
...
"""
# load in stats pickle
with open(pkl, 'rb') as infile:
filestats, samplestats = pickle.load(infile)
## pull new stats
self.perfile[handle] += filestats
## update sample stats
samplehits, barhits, misses, dbars = samplestats
self.fsamplehits.update(samplehits)
self.fbarhits.update(barhits)
self.fmisses.update(misses)
self.fdbars.update(dbars)