-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathtigmint_molecule.py
executable file
·299 lines (268 loc) · 11.7 KB
/
tigmint_molecule.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
#!/usr/bin/env python3
"""
Group linked reads into molecules.
@author: Justin Chu and Shaun Jackman
"""
import os
import argparse
import statistics
import sys
import pysam
from enum import Enum
class FileFormat(Enum):
"""File format"""
BED = 1
TSV = 2
class Molecule:
"""A molecule of linked reads"""
def __init__(
self, rname, start, end, \
new_molec_id, barcode, count, \
mapq_median, as_median, nm_median):
self.rname = rname
self.start = start
self.end = end
self.barcode = barcode
self.new_molec_id = new_molec_id
self.count = count
self.mapq_median = mapq_median
self.as_median = as_median
self.nm_median = nm_median
def print_bed(self, file):
"""Print this molecule to a BED file"""
print(
self.rname, self.start, self.end,
self.barcode,
self.count,
sep="\t", file=file)
def print_tsv(self, file):
"""Print this molecule to a TSV file"""
print(
self.rname, self.start, self.end, self.end - self.start,
self.barcode, self.new_molec_id,
self.count,
self.mapq_median, self.as_median, self.nm_median,
sep="\t", file=file)
def print_molecule(self, file, output_format):
"""Print this molecule to a file"""
if output_format == FileFormat.BED:
self.print_bed(file)
if output_format == FileFormat.TSV:
self.print_tsv(file)
class MolecIdentifier:
"""Group molecules into barcodes"""
def __init__(self):
"""Constructor, identifies molecules based on inter-arrival time threshold."""
self.opt = None
def run(self):
"""Group molecules into barcodes"""
self.parse_arguments()
samfile = pysam.AlignmentFile(self.opt.in_bam_filename, "rb")
if self.opt.out_bam_filename:
out_bam_file = pysam.AlignmentFile(self.opt.out_bam_filename, "wb", template=samfile)
else:
out_bam_file = None
if self.opt.out_molecules_filename:
out_molecules_file = open(self.opt.out_molecules_filename, "w")
else:
out_molecules_file = sys.stdout
if self.opt.output_format == FileFormat.TSV:
print(
"Rname\tStart\tEnd\tSize\tBX\tMI\tReads\tMapq_median\tAS_median\tNM_median",
file=out_molecules_file)
prev_barcode = None
prev_chr = None
cur_reads = []
new_molec_id = 0
for read in samfile:
barcode = None
if read.is_unmapped \
or read.is_supplementary \
or read.mapping_quality < self.opt.min_mapq \
or read.has_tag("NM") and read.get_tag("NM") >= self.opt.max_nm:
continue
if read.has_tag("AS") \
and read.get_tag("AS") < self.opt.min_as_ratio * read.query_length:
continue
if not read.has_tag("BX"):
if out_bam_file:
out_bam_file.write(read)
continue
barcode = read.get_tag("BX")
if prev_chr is None or prev_barcode is None:
prev_barcode = barcode
prev_chr = read.reference_id
if prev_barcode != barcode or read.reference_id != prev_chr:
prev_val = 0
prev_read = cur_reads[0]
prev_val1 = 0
prev_val2 = 0
start = cur_reads[0].pos
rname = cur_reads[0].reference_name
mapqs = []
scores = []
nms = []
count = 0
for cur_read in cur_reads:
value = cur_read.pos
abs_dist = value - prev_val
mapqs.append(cur_read.mapping_quality)
if cur_read.has_tag("AS"):
scores.append(cur_read.get_tag("AS"))
if cur_read.has_tag("NM"):
nms.append(cur_read.get_tag("NM"))
# Check if molecules should be terminated
if abs_dist > self.opt.max_dist and prev_val > 0:
end = prev_read.reference_end
# Find distance from nearest read
molec = Molecule(rname, start, end, \
new_molec_id, prev_barcode, count, \
statistics.median(mapqs), \
statistics.median(scores) if scores else "NA", \
statistics.median(nms) if nms else "NA")
if prev_read.is_reverse:
prev_val2 = value
prev_val1 = 0
else:
prev_val1 = value
prev_val2 = 0
start = value
if count >= self.opt.min_reads and molec.end - molec.start >= self.opt.min_size:
molec.print_molecule(out_molecules_file, self.opt.output_format)
new_molec_id += 1
if self.opt.out_bam_filename:
cur_read.set_tag("MI", new_molec_id)
out_bam_file.write(cur_read)
mapqs = []
scores = []
nms = []
mapqs.append(cur_read.mapping_quality)
if cur_read.has_tag("AS"):
scores.append(cur_read.get_tag("AS"))
if cur_read.has_tag("NM"):
nms.append(cur_read.get_tag("NM"))
prev_val = value
count = 0
continue
else:
if self.opt.out_bam_filename:
cur_read.set_tag("MI", new_molec_id)
out_bam_file.write(cur_read)
# Inter arrival time is distance between read of the same direction
inter_arrival = 0
if cur_read.is_reverse:
if prev_val2 == 0:
prev_val2 = value
prev_val = value
count += 1
continue
else:
inter_arrival = value - prev_val2
prev_val2 = value
else:
if prev_val1 == 0:
prev_val1 = value
prev_val = value
count += 1
continue
else:
inter_arrival = value - prev_val1
prev_val1 = value
if inter_arrival > 0:
count += 1
prev_val = value
prev_read = cur_read
end = prev_read.reference_end
molec = Molecule(rname, start, end, \
new_molec_id, prev_barcode, count, \
statistics.median(mapqs), \
statistics.median(scores) if scores else "NA", \
statistics.median(nms) if nms else "NA")
if count >= self.opt.min_reads and molec.end - molec.start >= self.opt.min_size:
molec.print_molecule(out_molecules_file, self.opt.output_format)
new_molec_id += 1
cur_reads = []
cur_reads.append(read)
prev_barcode = barcode
prev_chr = read.reference_id
# Clean up
samfile.close()
if out_molecules_file != sys.stdout:
out_molecules_file.close()
if out_bam_file != None:
out_bam_file.close()
def get_dist(self):
"""Read calculated dist from parameter file."""
if os.access(self.opt.param_file, os.F_OK):
if os.access(self.opt.param_file, os.R_OK):
with open(self.opt.param_file) as param_file:
for line in param_file:
line_content = line.strip().split("\t")
if line_content[0].startswith("read_p"):
return int(line_content[1])
print("tigmint-molecule: calculated max_dist parameter not found in parameter file '%'" % self.opt.param_file, file=sys.stderr)
sys.exit(1)
else:
print("tigmint-molecule: parameter file '%s' cannot be read" % self.opt.param_file, file=sys.stderr)
sys.exit(1)
else:
print("tigmint-molecule: parameter file '%s' cannot be read" % self.opt.param_file, file=sys.stderr)
sys.exit(1)
def parse_arguments(self):
"""Parse the command line arguments."""
parser = argparse.ArgumentParser(
description="Group linked reads into molecules. "
"Read a SAM/BAM file and output a TSV file. "
"The SAM/BAM file must be sorted by BX tag and then by position.")
parser.add_argument(
'--version', action='version', version='tigmint-molecule 1.2.5')
parser.add_argument(
metavar="BAM", dest="in_bam_filename",
help="Input BAM file sorted by BX tag then position, - for stdin")
parser.add_argument(
"-o", "--output", dest="out_molecules_filename",
help="Output TSV file [stdout]",
metavar="FILE")
parser.add_argument(
"-w", "--out-bam", dest="out_bam_filename",
help="Output BAM file with MI tags (optional)",
metavar="FILE")
parser.add_argument(
"--bed", action="store_const", dest="output_format", const=FileFormat.BED,
default=FileFormat.BED,
help="Output in BED format [default]")
parser.add_argument(
"--tsv", action="store_const", dest="output_format", const=FileFormat.TSV,
help="Output in TSV format")
parser.add_argument(
"-d", "--dist", dest="max_dist", type=int, default=50000,
help="Maximum distance between reads in the same molecule [50000]",
metavar="N")
parser.add_argument(
"-m", "--reads", dest="min_reads", type=int, default=4,
help="Minimum number of reads per molecule (duplicates are filtered out) [4]",
metavar="N")
parser.add_argument(
"-q", "--mapq", dest="min_mapq", type=int, default=0,
help="Minimum mapping quality [0]",
metavar="N")
parser.add_argument(
"-a", "--as-ratio", dest="min_as_ratio", type=float, default=0.65,
help="Minimum ratio of alignment score (AS) over read length [0.65]",
metavar="N")
parser.add_argument(
"-n", "--nm", dest="max_nm", type=int, default=5,
help="Maximum number of mismatches (NM) [5]",
metavar="N")
parser.add_argument(
"-s", "--size", dest="min_size", type=int, default=2000,
help="Minimum molecule size [2000]",
metavar="N")
parser.add_argument(
"-p", "--params", dest="param_file", type=str, default=None)
self.opt = parser.parse_args()
# Use calculated max dist if parameter file is provided
if self.opt.param_file:
self.opt.max_dist = self.get_dist()
if __name__ == '__main__':
MolecIdentifier().run()