simplesam 0.1.4.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
#!python
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
import argparse
|
|
5
|
+
try:
|
|
6
|
+
from importlib.metadata import version
|
|
7
|
+
except ImportError:
|
|
8
|
+
import pkg_resources
|
|
9
|
+
version = lambda name: pkg_resources.get_distribution(name).version
|
|
10
|
+
|
|
11
|
+
__version__ = "unknown"
|
|
12
|
+
try:
|
|
13
|
+
__version__ = version("simplesam")
|
|
14
|
+
except Exception:
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
from collections import deque
|
|
18
|
+
from collections import Counter
|
|
19
|
+
from collections import OrderedDict
|
|
20
|
+
|
|
21
|
+
class Extractor(OrderedDict):
|
|
22
|
+
|
|
23
|
+
def __missing__(self, pos):
|
|
24
|
+
value = (self.sam, deque(), deque())
|
|
25
|
+
self[pos] = value
|
|
26
|
+
return value
|
|
27
|
+
|
|
28
|
+
def update(self, sam, min_qual):
|
|
29
|
+
self.sam = sam
|
|
30
|
+
g = sam.pos
|
|
31
|
+
for i, (seq, qual) in enumerate(zip(sam.gapped('seq', '-'), sam.gapped('qual', '~'))):
|
|
32
|
+
if qual > min_qual:
|
|
33
|
+
self[g + i][1].append(seq)
|
|
34
|
+
self[g + i][2].append(qual)
|
|
35
|
+
|
|
36
|
+
def clear(self, stop=None):
|
|
37
|
+
for pos in sorted(k for k in self.keys() if stop is not None and k < stop):
|
|
38
|
+
sam, seq, qual = self.pop(pos)
|
|
39
|
+
ref = sam.parse_md()[sam.index_of(pos)]
|
|
40
|
+
try:
|
|
41
|
+
s, q = zip(*[(s, q) for s, q in zip(seq, qual) if s != ref])
|
|
42
|
+
except ValueError:
|
|
43
|
+
s, q = ([], [])
|
|
44
|
+
yield (sam.rname, str(pos), ref, str(len(seq) - len(s)), str(len(s)), ''.join(s), ''.join(q))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def pileup(args):
|
|
48
|
+
from simplesam import Reader
|
|
49
|
+
|
|
50
|
+
e = Extractor()
|
|
51
|
+
bases = ('A', 'C', 'T', 'G', 'N', '-')
|
|
52
|
+
stats = dict([('A', Counter()), ('C', Counter()), ('T', Counter()), ('G', Counter()), ('N', Counter()), ('-', Counter())])
|
|
53
|
+
with Reader(args.bam) as bam:
|
|
54
|
+
for read in bam:
|
|
55
|
+
if not read.mapped:
|
|
56
|
+
continue
|
|
57
|
+
if read.duplicate:
|
|
58
|
+
continue
|
|
59
|
+
if read.secondary:
|
|
60
|
+
continue
|
|
61
|
+
for line in e.clear(stop=read.pos):
|
|
62
|
+
if args.counts:
|
|
63
|
+
args.pileup.write('\t'.join(line) + '\t' + '\t'.join([str(line[5].count(c)) for c in bases]) + '\n')
|
|
64
|
+
else:
|
|
65
|
+
args.pileup.write('\t'.join(line) + '\n')
|
|
66
|
+
if args.stats:
|
|
67
|
+
stats[line[2]][line[2]] += int(line[3])
|
|
68
|
+
stats[line[2]].update(line[5])
|
|
69
|
+
e.update(read, '!')
|
|
70
|
+
|
|
71
|
+
for line in e.clear():
|
|
72
|
+
if args.counts:
|
|
73
|
+
args.pileup.write('\t'.join(line) + '\t' + '\t'.join([str(line[5].count(c)) for c in bases]) + '\n')
|
|
74
|
+
else:
|
|
75
|
+
args.pileup.write('\t'.join(line) + '\n')
|
|
76
|
+
if args.stats:
|
|
77
|
+
stats[line[2]][line[2]] += int(line[3])
|
|
78
|
+
stats[line[2]].update(line[5])
|
|
79
|
+
|
|
80
|
+
if args.stats:
|
|
81
|
+
for ref, counts in sorted(stats.items()):
|
|
82
|
+
for base in bases:
|
|
83
|
+
ref_count = counts[ref]
|
|
84
|
+
base_count = counts[base]
|
|
85
|
+
try:
|
|
86
|
+
percent_base = base_count / sum(counts.values())
|
|
87
|
+
except ZeroDivisionError:
|
|
88
|
+
percent_base = 0.
|
|
89
|
+
args.stats.write('{ref}\t{base}\t{ref_count}\t{base_count}\t{percent_base:.4%}\n'.format(**locals()))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def main():
|
|
93
|
+
parser = argparse.ArgumentParser(prog='pileup', description="generate a simple pileup-like file from a sorted/indexed BAM file")
|
|
94
|
+
parser.add_argument('--version', action='version', version="%(prog)s version {0}".format(__version__))
|
|
95
|
+
|
|
96
|
+
parser.add_argument('bam', type=argparse.FileType('r'), help="sorted/indexed BAM file ")
|
|
97
|
+
parser.add_argument('pileup', type=argparse.FileType('w'), help="pileup output file")
|
|
98
|
+
parser.add_argument('-c', '--counts', action='store_true', default=False, help="display counts for A/C/T/G/N/- separately (default: %(default)s)")
|
|
99
|
+
parser.add_argument('-i', '--stats', type=argparse.FileType('w'), help="tabulate mismatches to output file")
|
|
100
|
+
parser.set_defaults(func=pileup)
|
|
101
|
+
|
|
102
|
+
args = parser.parse_args()
|
|
103
|
+
args.func(args)
|
|
104
|
+
|
|
105
|
+
if __name__ == "__main__":
|
|
106
|
+
main()
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: simplesam
|
|
3
|
+
Version: 0.1.4.2
|
|
4
|
+
Summary: Simple pure Python SAM parser and objects for working with SAM records
|
|
5
|
+
Home-page: http://mattshirley.com
|
|
6
|
+
Author: Matthew Shirley
|
|
7
|
+
Author-email: mdshw5@gmail.com
|
|
8
|
+
License: MIT
|
|
9
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Natural Language :: English
|
|
14
|
+
Classifier: Operating System :: Unix
|
|
15
|
+
Classifier: Programming Language :: Python :: 2.7
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Requires-Dist: six
|
|
20
|
+
Requires-Dist: ordereddict
|
|
21
|
+
Dynamic: author
|
|
22
|
+
Dynamic: author-email
|
|
23
|
+
Dynamic: classifier
|
|
24
|
+
Dynamic: home-page
|
|
25
|
+
Dynamic: license
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
Dynamic: requires-dist
|
|
28
|
+
Dynamic: summary
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
simplesam.py,sha256=KqFUomcrbXnIWhZbxU0l7ohUrwefjP_McFR9nfNj3d4,22085
|
|
2
|
+
simplesam-0.1.4.2.data/scripts/pileup.py,sha256=3QIPfFK2NBSGWOFO3WM_vFgU5zAfZyWYO5QcwvP1IKI,3377
|
|
3
|
+
simplesam-0.1.4.2.dist-info/licenses/LICENSE,sha256=pCsN93T0ni0IlTgLHy1Iv97Lk6pUw54Z9Do2igAROVA,1072
|
|
4
|
+
simplesam-0.1.4.2.dist-info/METADATA,sha256=nqPUXlD_iXDxlM-mHx7kX3l7I4mH8GQa5R5H-eoBLnA,894
|
|
5
|
+
simplesam-0.1.4.2.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
6
|
+
simplesam-0.1.4.2.dist-info/top_level.txt,sha256=EwDP5hHNMiwdnWgfDoe5GrqH0jmNAXN5w3qpomtOb_w,10
|
|
7
|
+
simplesam-0.1.4.2.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2018 Matthew Shirley
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
simplesam
|
simplesam.py
ADDED
|
@@ -0,0 +1,617 @@
|
|
|
1
|
+
# pylint: disable=E1101, dangerous-default-value
|
|
2
|
+
"""
|
|
3
|
+
Classes to handle alignments in the SAM format.
|
|
4
|
+
|
|
5
|
+
Reader -> Sam -> Writer
|
|
6
|
+
|
|
7
|
+
"""
|
|
8
|
+
import sys
|
|
9
|
+
try:
|
|
10
|
+
from collections import OrderedDict
|
|
11
|
+
except ImportError: #python 2.6 or 3.6+
|
|
12
|
+
if sys.version_info >= (3,6):
|
|
13
|
+
OrderedDict = dict
|
|
14
|
+
else:
|
|
15
|
+
from ordereddict import OrderedDict
|
|
16
|
+
|
|
17
|
+
import os
|
|
18
|
+
from itertools import groupby
|
|
19
|
+
from subprocess import Popen, PIPE
|
|
20
|
+
from io import TextIOWrapper
|
|
21
|
+
import re
|
|
22
|
+
from six import PY3, string_types
|
|
23
|
+
try:
|
|
24
|
+
from importlib.metadata import version
|
|
25
|
+
except ImportError:
|
|
26
|
+
from pkg_resources import get_distribution
|
|
27
|
+
version = lambda name: get_distribution(name).version
|
|
28
|
+
|
|
29
|
+
try:
|
|
30
|
+
from multiprocessing.dummy.connection import Connection
|
|
31
|
+
except ImportError: #python2
|
|
32
|
+
from _multiprocessing import Connection
|
|
33
|
+
|
|
34
|
+
__version__ = "unknown"
|
|
35
|
+
try:
|
|
36
|
+
__version__ = version("simplesam")
|
|
37
|
+
except Exception:
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
class DefaultOrderedDict(OrderedDict):
|
|
41
|
+
def __init__(self, default, items=[]):
|
|
42
|
+
super(DefaultOrderedDict, self).__init__(items)
|
|
43
|
+
self._default = default
|
|
44
|
+
|
|
45
|
+
def __missing__(self, key):
|
|
46
|
+
self[key] = value = self._default()
|
|
47
|
+
return value
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class GenomicOrder(object):
|
|
51
|
+
def __gt__(self, other):
|
|
52
|
+
if self.rname != other.rname:
|
|
53
|
+
return self.rname > other.rname
|
|
54
|
+
return self.pos > other.pos
|
|
55
|
+
|
|
56
|
+
def __lt__(self, other):
|
|
57
|
+
if self.rname != other.rname:
|
|
58
|
+
return self.rname < other.rname
|
|
59
|
+
return self.pos < other.pos
|
|
60
|
+
|
|
61
|
+
def __eq__(self, other):
|
|
62
|
+
return self.rname == other.rname and self.pos == other.pos
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class Reader(object):
|
|
66
|
+
""" Read SAM/BAM format file as an iterable. """
|
|
67
|
+
def __init__(self, f, regions=False, kind=None, samtools_path="samtools"):
|
|
68
|
+
ext = None
|
|
69
|
+
self.samtools_path = samtools_path
|
|
70
|
+
self.spool = None # use this to catch alignment during reader scraping
|
|
71
|
+
self.type = 'sam'
|
|
72
|
+
try:
|
|
73
|
+
self._f_name = f.name
|
|
74
|
+
_, ext = os.path.splitext(f.name)
|
|
75
|
+
if f.name == '<stdin>': # stdin stream
|
|
76
|
+
self._sam_init(f)
|
|
77
|
+
elif (ext is not None and ext.lower()) == '.bam' or (kind is not None and kind.lower() == 'bam'):
|
|
78
|
+
self._bam_init(f, regions)
|
|
79
|
+
self.type = 'bam'
|
|
80
|
+
elif (ext is not None and ext.lower()) == '.sam' or (kind is not None and kind.lower() == 'sam'):
|
|
81
|
+
self._sam_init(f)
|
|
82
|
+
else:
|
|
83
|
+
self._sam_init(f)
|
|
84
|
+
if (regions and (ext is not None and ext.lower() != '.bam') and kind is None) or (regions and kind is not None and kind.lower() != 'bam'):
|
|
85
|
+
self.__exit__()
|
|
86
|
+
raise ValueError("Region support requires bam file.")
|
|
87
|
+
except AttributeError:
|
|
88
|
+
self._f_name = None
|
|
89
|
+
if isinstance(f, Connection):
|
|
90
|
+
self._pipe_init(f)
|
|
91
|
+
else:
|
|
92
|
+
self._sam_init(f)
|
|
93
|
+
|
|
94
|
+
def _pipe_init(self, f):
|
|
95
|
+
header = []
|
|
96
|
+
for line in iter(f.recv, ''):
|
|
97
|
+
if line[0] == '@':
|
|
98
|
+
header.append(line.rstrip('\n\r'))
|
|
99
|
+
else:
|
|
100
|
+
self.spool = line
|
|
101
|
+
break
|
|
102
|
+
self.header_as_dict(header)
|
|
103
|
+
self.f = iter(f.recv, '')
|
|
104
|
+
self._conn = 'pipe'
|
|
105
|
+
|
|
106
|
+
def _sam_init(self, f):
|
|
107
|
+
header = []
|
|
108
|
+
self.f = f
|
|
109
|
+
for line in self.f:
|
|
110
|
+
if line[0] == '@':
|
|
111
|
+
header.append(line.rstrip('\n\r'))
|
|
112
|
+
else:
|
|
113
|
+
self.spool = line
|
|
114
|
+
break
|
|
115
|
+
self.header_as_dict(header)
|
|
116
|
+
self._conn = 'file'
|
|
117
|
+
|
|
118
|
+
def _bam_init(self, f, regions):
|
|
119
|
+
pline = [self.samtools_path, 'view', '-H', f.name]
|
|
120
|
+
try:
|
|
121
|
+
p = Popen(pline, bufsize=-1, stdout=PIPE,
|
|
122
|
+
stderr=PIPE)
|
|
123
|
+
except OSError:
|
|
124
|
+
raise OSError('Samtools must be installed for BAM file support!\n')
|
|
125
|
+
self.header_as_dict([line.decode('utf-8').rstrip('\n\r') for line in p.stdout])
|
|
126
|
+
p.wait()
|
|
127
|
+
if regions:
|
|
128
|
+
try:
|
|
129
|
+
open(''.join([f.name, '.bai']))
|
|
130
|
+
except EnvironmentError:
|
|
131
|
+
sys.stderr.write("BAM index not found. Attempting to index file.\n")
|
|
132
|
+
index_p = Popen([self.samtools_path, 'index', f.name], stdout=PIPE, stderr=PIPE)
|
|
133
|
+
|
|
134
|
+
_, err = index_p.communicate()
|
|
135
|
+
if index_p.returncode > 0 or re.search("fail", str(err)):
|
|
136
|
+
raise OSError("Indexing failed. Is the BAM file sorted?\n")
|
|
137
|
+
else:
|
|
138
|
+
sys.stderr.write("Index created successfully.\n")
|
|
139
|
+
pline = [self.samtools_path, 'view', f.name, regions]
|
|
140
|
+
else:
|
|
141
|
+
pline = [self.samtools_path, 'view', f.name]
|
|
142
|
+
self.p = Popen(pline, bufsize=-1, stdout=PIPE,
|
|
143
|
+
stderr=PIPE)
|
|
144
|
+
if PY3:
|
|
145
|
+
self.f = TextIOWrapper(self.p.stdout)
|
|
146
|
+
else:
|
|
147
|
+
self.f = self.p.stdout
|
|
148
|
+
|
|
149
|
+
self._conn = 'proc'
|
|
150
|
+
|
|
151
|
+
def next(self):
|
|
152
|
+
""" Returns the next :class:`.Sam` object """
|
|
153
|
+
try:
|
|
154
|
+
if self.spool: # this will be the first alignment in a SAM file or stream
|
|
155
|
+
line = self.spool.rstrip('\n\r')
|
|
156
|
+
self.spool = None
|
|
157
|
+
else:
|
|
158
|
+
line = next(self.f).rstrip('\n\r')
|
|
159
|
+
if line == '':
|
|
160
|
+
raise StopIteration
|
|
161
|
+
fields = line.split('\t')
|
|
162
|
+
required = fields[:11]
|
|
163
|
+
tags = fields[11:]
|
|
164
|
+
return Sam(*required, tags=tags)
|
|
165
|
+
except StopIteration:
|
|
166
|
+
raise StopIteration
|
|
167
|
+
|
|
168
|
+
def __next__(self):
|
|
169
|
+
return self.next()
|
|
170
|
+
|
|
171
|
+
def __iter__(self):
|
|
172
|
+
return self
|
|
173
|
+
|
|
174
|
+
def __len__(self):
|
|
175
|
+
""" Returns the number of reads in an indexed BAM file.
|
|
176
|
+
Not implemented for SAM files. """
|
|
177
|
+
if self.type != 'bam':
|
|
178
|
+
raise NotImplementedError("len(Reader) is only implemented for BAM files.")
|
|
179
|
+
elif self.type == 'bam':
|
|
180
|
+
return sum(bam_read_count(self._f_name, self.samtools_path))
|
|
181
|
+
|
|
182
|
+
def subsample(self, n):
|
|
183
|
+
""" Returns an interator that draws every nth read from
|
|
184
|
+
the input file. Returns :class:`.Sam`. """
|
|
185
|
+
for i, line in enumerate(self.f):
|
|
186
|
+
if i % n == 0:
|
|
187
|
+
fields = line.split('\t')
|
|
188
|
+
required = fields[:11]
|
|
189
|
+
tags = fields[11:]
|
|
190
|
+
yield Sam(*required, tags=tags)
|
|
191
|
+
|
|
192
|
+
def header_as_dict(self, header):
|
|
193
|
+
""" Parse the header list and return a nested dictionary. """
|
|
194
|
+
self.header = DefaultOrderedDict(OrderedDict)
|
|
195
|
+
for line in header:
|
|
196
|
+
line = line.split('\t')
|
|
197
|
+
key, fields = (line[0], line[1:])
|
|
198
|
+
try:
|
|
199
|
+
self.header[key][fields[0]] = fields[1:]
|
|
200
|
+
except IndexError:
|
|
201
|
+
self.header[key][fields[0]] = ['']
|
|
202
|
+
|
|
203
|
+
@property
|
|
204
|
+
def seqs(self):
|
|
205
|
+
""" Return just the sequence names from the @SQ library as a generator. """
|
|
206
|
+
for key in self.header['@SQ'].keys():
|
|
207
|
+
yield key.split(':')[1]
|
|
208
|
+
|
|
209
|
+
def tile_genome(self, width):
|
|
210
|
+
""" Return a generator of UCSC-style regions tiling ``width``. """
|
|
211
|
+
assert isinstance(width, int)
|
|
212
|
+
for k, v in self.header['@SQ'].items():
|
|
213
|
+
rname = k.split(':')[1]
|
|
214
|
+
seqlength = v[0].split(':')[1]
|
|
215
|
+
for region in tile_region(rname, 1, int(seqlength), width):
|
|
216
|
+
yield region
|
|
217
|
+
|
|
218
|
+
def close(self):
|
|
219
|
+
self.__exit__()
|
|
220
|
+
|
|
221
|
+
def __enter__(self):
|
|
222
|
+
return self
|
|
223
|
+
|
|
224
|
+
def __exit__(self, *args):
|
|
225
|
+
if self._conn == 'file':
|
|
226
|
+
self.f.close()
|
|
227
|
+
if self._conn == 'proc':
|
|
228
|
+
self.f.close()
|
|
229
|
+
self.p.terminate()
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
class Writer(object):
|
|
233
|
+
""" Write SAM/BAM format file from :class:`.Sam` objects. """
|
|
234
|
+
def __init__(self, f, header=None):
|
|
235
|
+
try:
|
|
236
|
+
_, ext = os.path.splitext(f.name)
|
|
237
|
+
if ext == '.bam':
|
|
238
|
+
# Why not just pipe to samtools?
|
|
239
|
+
raise NotImplementedError("Bam writing support is not implemented.\n")
|
|
240
|
+
except AttributeError: # pipe?
|
|
241
|
+
pass
|
|
242
|
+
self.file = f
|
|
243
|
+
if self.file.mode == 'a' and self.file.tell() == 0:
|
|
244
|
+
# We're appending to an empty file. Assume we need a header.
|
|
245
|
+
self._merge_header(header)
|
|
246
|
+
self._header_dict_write()
|
|
247
|
+
elif self.file.mode == 'a' and self.file.tell() > 0:
|
|
248
|
+
if header:
|
|
249
|
+
raise NotImplementedError("Updating headers on existing SAM files is not supported.\n")
|
|
250
|
+
else:
|
|
251
|
+
self._merge_header(header)
|
|
252
|
+
self._header_dict_write()
|
|
253
|
+
|
|
254
|
+
def _merge_header(self, header):
|
|
255
|
+
self.header = DefaultOrderedDict(OrderedDict)
|
|
256
|
+
if not header:
|
|
257
|
+
self.header['@HD']['VN:1.0'] = ['SO:unknown']
|
|
258
|
+
else:
|
|
259
|
+
for key, values in header.items():
|
|
260
|
+
for k, v in values.items():
|
|
261
|
+
self.header[key][k] = v
|
|
262
|
+
|
|
263
|
+
def _header_dict_write(self):
|
|
264
|
+
for key, value in self.header.items():
|
|
265
|
+
for k, v in value.items():
|
|
266
|
+
tags = '\t'.join(v)
|
|
267
|
+
self.file.write('{key}\t{k}\t{tags}\n'.format(**locals()))
|
|
268
|
+
|
|
269
|
+
def write(self, sam):
|
|
270
|
+
""" Write the string representation of the ``sam`` :class:`.Sam` object. """
|
|
271
|
+
self.file.write(str(sam))
|
|
272
|
+
|
|
273
|
+
def close(self):
|
|
274
|
+
self.__exit__()
|
|
275
|
+
|
|
276
|
+
def __enter__(self):
|
|
277
|
+
return self
|
|
278
|
+
|
|
279
|
+
def __exit__(self, *args):
|
|
280
|
+
self.file.close()
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
class Sam(GenomicOrder):
|
|
284
|
+
""" Object representation of a SAM entry. """
|
|
285
|
+
# https://github.com/samtools/hts-specs/blob/da805be01e2ceaaa69fdde9f33c5377bf9ee6369/SAMv1.tex#L383
|
|
286
|
+
# operations that consume the reference
|
|
287
|
+
_cigar_ref = set(('M', 'D', 'N', '=', 'X', 'EQ'))
|
|
288
|
+
# operations that consume the query
|
|
289
|
+
_cigar_query = set(('M', 'I', 'S', '=', 'X', 'EQ'))
|
|
290
|
+
# operations that do not represent an alignment
|
|
291
|
+
_cigar_no_align = set(('H', 'P'))
|
|
292
|
+
_valid_cigar = _cigar_ref | _cigar_query | _cigar_no_align
|
|
293
|
+
# operations that can be represented as aligned to the reference
|
|
294
|
+
_cigar_align = _cigar_ref & _cigar_query
|
|
295
|
+
# operations that only consume the reference
|
|
296
|
+
_cigar_ref_only = _cigar_ref - _cigar_align
|
|
297
|
+
# operations that only consume the query
|
|
298
|
+
_cigar_query_only = _cigar_query - _cigar_align
|
|
299
|
+
|
|
300
|
+
def __init__(self, qname='', flag=4, rname='*', pos=0, mapq=255, cigar='*', rnext='*', pnext=0, tlen=0, seq='*', qual='*', tags=[]):
|
|
301
|
+
self.qname = qname
|
|
302
|
+
self.flag = int(flag)
|
|
303
|
+
self.rname = rname
|
|
304
|
+
self.pos = int(pos)
|
|
305
|
+
self.mapq = int(mapq)
|
|
306
|
+
self.cigar = cigar
|
|
307
|
+
self.rnext = rnext
|
|
308
|
+
self.pnext = int(pnext)
|
|
309
|
+
self.tlen = int(tlen)
|
|
310
|
+
self.seq = seq
|
|
311
|
+
self.qual = qual
|
|
312
|
+
self._tags = tags
|
|
313
|
+
self._cache = dict()
|
|
314
|
+
|
|
315
|
+
def __str__(self):
|
|
316
|
+
""" Returns the string representation of a SAM entry. Correspondes to one line
|
|
317
|
+
in the on-disk format of a SAM file. """
|
|
318
|
+
if self.tags:
|
|
319
|
+
tag_fields = '\t'.join([encode_tag(tag, self.tags[tag]) for tag in sorted(self.tags.keys())])
|
|
320
|
+
else:
|
|
321
|
+
tag_fields = '\t'.join(self._tags)
|
|
322
|
+
return '{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}\t{11}\n'.format(self.qname,
|
|
323
|
+
str(self.flag),
|
|
324
|
+
self.rname,
|
|
325
|
+
str(self.pos),
|
|
326
|
+
str(self.mapq),
|
|
327
|
+
self.cigar,
|
|
328
|
+
self.rnext,
|
|
329
|
+
str(self.pnext),
|
|
330
|
+
str(self.tlen),
|
|
331
|
+
self.seq,
|
|
332
|
+
self.qual,
|
|
333
|
+
tag_fields)
|
|
334
|
+
def __repr__(self):
|
|
335
|
+
return "Sam({0}:{1}:{2})".format(self.rname, self.pos, self.qname)
|
|
336
|
+
|
|
337
|
+
def __len__(self):
|
|
338
|
+
""" Returns the length of the portion of ``self.seq`` aligned to the reference. Unaligned reads will
|
|
339
|
+
have len() == 0. Insertions (I) and soft-clipped portions (S) will not contribute to the aligned length.
|
|
340
|
+
|
|
341
|
+
>>> x = Sam(cigar='8M2I4M1D3M4S')
|
|
342
|
+
>>> len(x)
|
|
343
|
+
16
|
|
344
|
+
"""
|
|
345
|
+
return sum(c[0] for c in self.cigars if c[1] in self._cigar_ref)
|
|
346
|
+
|
|
347
|
+
def __getitem__(self, tag):
|
|
348
|
+
""" Retreives the SAM tag named "tag" as a tuple: (tag_name, data). The
|
|
349
|
+
data type of the tag is interpreted as the proper Python object type.
|
|
350
|
+
|
|
351
|
+
>>> x = Sam(tags=['NM:i:0', 'ZZ:Z:xyz'])
|
|
352
|
+
>>> x['NM']
|
|
353
|
+
0
|
|
354
|
+
>>> x['ZZ']
|
|
355
|
+
'xyz'
|
|
356
|
+
"""
|
|
357
|
+
return self.tags[tag]
|
|
358
|
+
|
|
359
|
+
def __setitem__(self, tag, data):
|
|
360
|
+
""" Stores the SAM tag named "tag" with the value "data". The
|
|
361
|
+
data type of the tag is interpreted from the Python object type.
|
|
362
|
+
|
|
363
|
+
>>> x = Sam(tags=[])
|
|
364
|
+
>>> x['NM'] = 0
|
|
365
|
+
>>> x['NM']
|
|
366
|
+
0
|
|
367
|
+
"""
|
|
368
|
+
self.tags[tag] = data
|
|
369
|
+
|
|
370
|
+
def index_of(self, pos):
|
|
371
|
+
""" Return the relative index within the alignment from a genomic position 'pos' """
|
|
372
|
+
i = pos - self.pos
|
|
373
|
+
if i >= 0:
|
|
374
|
+
return i
|
|
375
|
+
else:
|
|
376
|
+
raise IndexError("Position {0:n} not in {1}.".format(pos, self.qname))
|
|
377
|
+
|
|
378
|
+
def get(self, key, default_value):
|
|
379
|
+
try:
|
|
380
|
+
return self[key]
|
|
381
|
+
except KeyError:
|
|
382
|
+
return default_value
|
|
383
|
+
|
|
384
|
+
def cigar_split(self):
|
|
385
|
+
# https://github.com/brentp/bwa-meth
|
|
386
|
+
if self.cigar == "*":
|
|
387
|
+
yield (0, None)
|
|
388
|
+
return
|
|
389
|
+
cig_iter = groupby(self.cigar, lambda c: c.isdigit())
|
|
390
|
+
for _, n in cig_iter:
|
|
391
|
+
op = int("".join(n)), "".join(next(cig_iter)[1])
|
|
392
|
+
if op[1] in self._valid_cigar:
|
|
393
|
+
yield op
|
|
394
|
+
else:
|
|
395
|
+
raise ValueError("CIGAR operation %s in record %s is invalid." % (op[1], self.qname))
|
|
396
|
+
|
|
397
|
+
def gapped(self, attr, gap_char='-'):
|
|
398
|
+
""" Return a :class:`.Sam` sequence attribute or tag with all
|
|
399
|
+
deletions in the reference sequence represented as 'gap_char' and all
|
|
400
|
+
insertions in the reference sequence removed. A sequence could
|
|
401
|
+
be :class:``Sam.seq``, ``Sam.qual``, or any :class:`.Sam` tag that
|
|
402
|
+
represents an aligned sequence, such as a methylation tag for bisulfite
|
|
403
|
+
sequencing libraries.
|
|
404
|
+
|
|
405
|
+
>>> x = Sam(*'r001\t99\tref\t7\t30\t8M2I4M1D3M\t=\t37\t39\tTTAGATAAAGGATACTG\t*'.split())
|
|
406
|
+
>>> x.gapped('seq')
|
|
407
|
+
'TTAGATAAGATA-CTG'
|
|
408
|
+
>>> x = Sam(*'r001\t99\tref\t7\t30\t8M2I4M1D3M\t=\t37\t39\tTTAGATAAAGGATACTG\t*'.split(), tags=['ZM:Z:.........M....M.M'])
|
|
409
|
+
>>> x.gapped('ZM')
|
|
410
|
+
'............-M.M'
|
|
411
|
+
"""
|
|
412
|
+
try:
|
|
413
|
+
ungapped = getattr(self, attr)
|
|
414
|
+
except AttributeError:
|
|
415
|
+
ungapped = self[attr] # get dictionary key (tag) if attribute is missing
|
|
416
|
+
if len(ungapped) != len(self.seq):
|
|
417
|
+
raise ValueError("The length of the '%s' attribute is not equal to the length of Sam.seq!" % attr)
|
|
418
|
+
gapped = []
|
|
419
|
+
i = 0
|
|
420
|
+
for n, t in self.cigars:
|
|
421
|
+
if t in self._cigar_align:
|
|
422
|
+
gapped.extend(ungapped[i:i + n])
|
|
423
|
+
i += n
|
|
424
|
+
elif t in self._cigar_ref_only:
|
|
425
|
+
gapped.extend([gap_char] * n)
|
|
426
|
+
elif t in self._cigar_query_only:
|
|
427
|
+
i += n
|
|
428
|
+
elif t in self._cigar_no_align:
|
|
429
|
+
pass
|
|
430
|
+
return ''.join(gapped)
|
|
431
|
+
|
|
432
|
+
def parse_md(self):
|
|
433
|
+
""" Return the ungapped reference sequence from the MD tag, if present.
|
|
434
|
+
"""
|
|
435
|
+
try:
|
|
436
|
+
return self._cache['parse_md']
|
|
437
|
+
except KeyError:
|
|
438
|
+
pass
|
|
439
|
+
try:
|
|
440
|
+
md = self['MD']
|
|
441
|
+
except KeyError:
|
|
442
|
+
raise KeyError('MD tag not found in SAM record.')
|
|
443
|
+
ref_seq = list(self.gapped('seq'))
|
|
444
|
+
md_match = re.findall(r"([0-9]+)\^?([A-Z]+)?", md)
|
|
445
|
+
ref_seq_i = 0
|
|
446
|
+
for i, b in md_match:
|
|
447
|
+
ref_seq_i += int(i)
|
|
448
|
+
for mismatch in b:
|
|
449
|
+
try:
|
|
450
|
+
ref_seq[ref_seq_i] = mismatch
|
|
451
|
+
except IndexError:
|
|
452
|
+
raise IndexError(locals())
|
|
453
|
+
ref_seq_i += 1
|
|
454
|
+
self._cache['parse_md'] = ref_seq
|
|
455
|
+
return ref_seq
|
|
456
|
+
|
|
457
|
+
@property
|
|
458
|
+
def cigars(self):
|
|
459
|
+
""" Returns the CIGAR string as a tuple.
|
|
460
|
+
|
|
461
|
+
>>> x = Sam(cigar='8M2I4M1D3M')
|
|
462
|
+
>>> x.cigars
|
|
463
|
+
((8, 'M'), (2, 'I'), (4, 'M'), (1, 'D'), (3, 'M'))
|
|
464
|
+
"""
|
|
465
|
+
try:
|
|
466
|
+
return self._cache['cigars']
|
|
467
|
+
except KeyError:
|
|
468
|
+
self._cache['cigars'] = tuple(self.cigar_split())
|
|
469
|
+
return self._cache['cigars']
|
|
470
|
+
|
|
471
|
+
@property
|
|
472
|
+
def tags(self):
|
|
473
|
+
""" Parses the tags string to a dictionary if necessary.
|
|
474
|
+
|
|
475
|
+
>>> x = Sam(tags=['XU:Z:cgttttaa', 'XB:Z:cttacgttaagagttaac', 'MD:Z:75', 'NM:i:0', 'NH:i:1', 'RG:Z:1'])
|
|
476
|
+
>>> sorted(x.tags.items(), key=lambda x: x[0])
|
|
477
|
+
[('MD', '75'), ('NH', 1), ('NM', 0), ('RG', '1'), ('XB', 'cttacgttaagagttaac'), ('XU', 'cgttttaa')]
|
|
478
|
+
"""
|
|
479
|
+
try:
|
|
480
|
+
return self._cache['tags']
|
|
481
|
+
except KeyError:
|
|
482
|
+
self._cache['tags'] = parse_sam_tags(self._tags)
|
|
483
|
+
return self._cache['tags']
|
|
484
|
+
|
|
485
|
+
@property
|
|
486
|
+
def paired(self):
|
|
487
|
+
""" Returns True if the read is paired and
|
|
488
|
+
each segment properly aligned according to the aligner. """
|
|
489
|
+
return bool(self.flag & 0x2)
|
|
490
|
+
|
|
491
|
+
@property
|
|
492
|
+
def mapped(self):
|
|
493
|
+
""" Returns True of the read is mapped. """
|
|
494
|
+
return not (self.flag & 0x4)
|
|
495
|
+
|
|
496
|
+
@property
|
|
497
|
+
def secondary(self):
|
|
498
|
+
""" Returns True if the read alignment is secondary. """
|
|
499
|
+
return bool(self.flag & 0x100)
|
|
500
|
+
|
|
501
|
+
@property
|
|
502
|
+
def reverse(self):
|
|
503
|
+
""" Returns True if ``Sam.seq`` is being reverse complemented. """
|
|
504
|
+
return bool(self.flag & 0x10)
|
|
505
|
+
|
|
506
|
+
@property
|
|
507
|
+
def passing(self):
|
|
508
|
+
""" Returns True if the read is passing filters, such as platform/vendor quality controls. """
|
|
509
|
+
return not bool(self.flag & 0x200)
|
|
510
|
+
|
|
511
|
+
@property
|
|
512
|
+
def duplicate(self):
|
|
513
|
+
""" Returns True if the read is a PCR or optical duplicate. """
|
|
514
|
+
return bool(self.flag & 0x400)
|
|
515
|
+
|
|
516
|
+
@property
|
|
517
|
+
def coords(self):
|
|
518
|
+
""" Returns a range of genomic coordinates for the query sequence positions in the gapped alignment. """
|
|
519
|
+
return range(self.pos, self.pos + len(self))
|
|
520
|
+
|
|
521
|
+
@property
|
|
522
|
+
def safename(self):
|
|
523
|
+
"""Return ``Sam.qname`` without paired-end identifier if it exists"""
|
|
524
|
+
if self.qname[-2] == '/':
|
|
525
|
+
return self.qname[:-2]
|
|
526
|
+
else:
|
|
527
|
+
return self.qname
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def parse_sam_tags(tagfields):
|
|
531
|
+
""" Return a dictionary containing the tags """
|
|
532
|
+
return dict([(tag, data) for tag, dtype, data in [decode_tag(x) for x in tagfields]])
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def encode_tag(tag, data):
|
|
536
|
+
""" Write a SAM tag in the format ``TAG:TYPE:data``. Infers the data type
|
|
537
|
+
from the Python object type.
|
|
538
|
+
|
|
539
|
+
>>> encode_tag('YM', '#""9O"1@!J')
|
|
540
|
+
'YM:Z:#""9O"1@!J'
|
|
541
|
+
"""
|
|
542
|
+
if isinstance(data, string_types):
|
|
543
|
+
data_type = 'Z'
|
|
544
|
+
elif isinstance(data, int):
|
|
545
|
+
data_type = 'i'
|
|
546
|
+
elif isinstance(data, float):
|
|
547
|
+
data_type = 'f'
|
|
548
|
+
else:
|
|
549
|
+
raise NotImplementedError("Data {0} cannot be encoded as string, integer, or float tag.".format(data))
|
|
550
|
+
value = ':'.join((tag, data_type, str(data)))
|
|
551
|
+
return value
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def decode_tag(tag_string):
|
|
555
|
+
""" Parse a SAM format tag to a (tag, type, data) tuple. Python object
|
|
556
|
+
types for data are set using the type code. Supported type codes are: A, i, f, Z, H, B
|
|
557
|
+
|
|
558
|
+
>>> decode_tag('YM:Z:#""9O"1@!J')
|
|
559
|
+
('YM', 'Z', '#""9O"1@!J')
|
|
560
|
+
>>> decode_tag('XS:i:5')
|
|
561
|
+
('XS', 'i', 5)
|
|
562
|
+
>>> decode_tag('XF:f:100.5')
|
|
563
|
+
('XF', 'f', 100.5)
|
|
564
|
+
"""
|
|
565
|
+
try:
|
|
566
|
+
tag, data_type, data = tag_string.split(':')
|
|
567
|
+
except ValueError:
|
|
568
|
+
match = re.match(r'([A-Z]{2}):([iZfHB]):(\S+)', tag_string)
|
|
569
|
+
tag = match.group(1)
|
|
570
|
+
data_type = match.group(2)
|
|
571
|
+
data = match.group(3)
|
|
572
|
+
if data_type == 'i':
|
|
573
|
+
return (tag, data_type, int(data))
|
|
574
|
+
elif data_type == 'Z':
|
|
575
|
+
return (tag, data_type, data)
|
|
576
|
+
elif data_type == 'f':
|
|
577
|
+
return (tag, data_type, float(data))
|
|
578
|
+
elif data_type == 'A': # this is just a special case of a character
|
|
579
|
+
return (tag, data_type, data)
|
|
580
|
+
elif data_type == 'H':
|
|
581
|
+
raise NotImplementedError("Hex array SAM tags are currently not parsed.")
|
|
582
|
+
elif data_type == 'B':
|
|
583
|
+
raise NotImplementedError("Byte array SAM tags are currently not parsed.")
|
|
584
|
+
else:
|
|
585
|
+
raise NotImplementedError("Tag {0} cannot be parsed.".format(tag_string))
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def tile_region(rname, start, end, step):
|
|
589
|
+
""" Make non-overlapping tiled windows from the specified region in
|
|
590
|
+
the UCSC-style string format.
|
|
591
|
+
|
|
592
|
+
>>> list(tile_region('chr1', 1, 250, 100))
|
|
593
|
+
['chr1:1-100', 'chr1:101-200', 'chr1:201-250']
|
|
594
|
+
>>> list(tile_region('chr1', 1, 200, 100))
|
|
595
|
+
['chr1:1-100', 'chr1:101-200']
|
|
596
|
+
"""
|
|
597
|
+
while start + step <= end:
|
|
598
|
+
yield '%s:%d-%d' % (rname, start, start + step - 1)
|
|
599
|
+
start += step
|
|
600
|
+
if start < end:
|
|
601
|
+
yield '%s:%d-%d' % (rname, start, end)
|
|
602
|
+
|
|
603
|
+
def bam_read_count(bamfile, samtools_path="samtools"):
|
|
604
|
+
""" Return a tuple of the number of mapped and unmapped reads in a BAM file """
|
|
605
|
+
p = Popen([samtools_path, 'idxstats', bamfile], stdout=PIPE)
|
|
606
|
+
mapped = 0
|
|
607
|
+
unmapped = 0
|
|
608
|
+
for line in p.stdout:
|
|
609
|
+
rname, rlen, nm, nu = line.rstrip().split()
|
|
610
|
+
mapped += int(nm)
|
|
611
|
+
unmapped += int(nu)
|
|
612
|
+
return (mapped, unmapped)
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
if __name__ == "__main__":
|
|
616
|
+
import doctest
|
|
617
|
+
doctest.testmod()
|