Repository navigation
Expand file tree
/
Copy pathsplitSAM.py
More file actions
executable file
·164 lines (111 loc) · 4.6 KB
/
Copy pathsplitSAM.py
File metadata and controls
executable file
·164 lines (111 loc) · 4.6 KB
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
#!/usr/bin/env python
# Read a .sam file, output several fasta files containing reads which
# do not overlap in the SAM alignment.
# The SAM file is assumed to be sorted by chr and position.
# AUTHOR: Tom Skelly (thomas.skelly@fnlcr.nih.gov)
import os
import sys
import optparse
import re # regular expressions
import string
from tt_log import logger
import CigarString as cs
VERSION = '20150501.01'
FLAG_NOT_ALIGNED = 0x04 # SAM file flags
FLAG_REVERSE = 0x10
FLAG_SECONDARY = 0x100
FASTA_WRAP = 60
BOWTIE_BUILD = '/is2/projects/pacbio/static/software/packages/bowtie2-2.2.3/bowtie2-build'
def main ():
logger.debug('version %s starting' % VERSION)
opt, args = getParms()
if len(args) > 0:
logger.debug('reading SAM file %s' % args[0])
handle = open (args[0], 'r')
else:
logger.debug('reading SAM data from stdin')
handle = sys.stdin
totReads = 0 # assorted counters
totAlign = 0
totUnsup = 0
lastPos = dict() # current position in SAM file by chr (for sort check)
fileSeq = 0
fastaList = list() # list of currently open output fasta files
compltab = string.maketrans ('ACGT', 'TGCA') # for reverse-complementing reads
fastaNonAligned = tiledFasta ('%s.nonaligned.fasta' % opt.prefix)
for line in handle: # main loop: read the SAM file
if line.startswith('@'):
continue
totReads += 1
lineFields = line.split('\t') # just split it once, not 6 times in list comp
readName, flags, chr, start, cigarString, bases = [lineFields[i] for i in (0,1,2,3,5,9)]
flags = int(flags)
start = int(start)
if readName.find('|f1p0|') != -1:
totUnsup += 1
continue # skip unsupported reads
if flags & FLAG_NOT_ALIGNED:
fastaNonAligned.addRead (readName, '*', 0, 0, bases)
continue
totAlign += 1
strand = '-' if (flags & FLAG_REVERSE) else '+'
cigar = cs.CigarString(cigarString, start)
end = start + cigar.genomicLength() - 1; # -1 to report last base, rather than last+1
if start < lastPos.get(chr, 0):
raise RuntimeError ('SAM file is not sorted by position')
lastPos[chr] = start
if strand == '-':
bases = bases[::-1].translate(compltab)
found = False
for fasta in fastaList:
if fasta.fits (chr, start):
fasta.addRead (readName, chr, start, end, bases)
found = True
break
if not found:
fileSeq += 1
fasta = tiledFasta ('%s.%03d.fasta' % (opt.prefix, fileSeq))
fastaList.append(fasta)
fasta.addRead (readName, chr, start, end, bases)
handle.close()
fastaNonAligned.close()
for fasta in fastaList:
fasta.close()
fasta.makeRef()
logger.debug('found %d reads, of which %d aligned, %d were f1p0', totReads, totAlign, totUnsup)
logger.debug('finished')
def getParms (): # use default input sys.argv[1:]
parser = optparse.OptionParser(usage='%prog [options] <SAM_file> ... ')
parser.add_option ('--prefix', help='start of fasta file name (required)')
parser.set_defaults (prefix=None,
)
opt, args = parser.parse_args()
return opt, args
class tiledFasta (object):
def __init__ (self, name):
self.name = name
self.handle = open (name, 'w')
self.lastPos = dict()
logger.debug('opened %s' % name)
def fits (self, chr, start):
return start > self.lastPos.get(chr, 0)
def addRead (self, readName, chr, start, end, bases):
self.lastPos[chr] = end
self.handle.write ('>%s %s %d %d\n' % (readName, chr, start, end))
for ix in xrange(0, len(bases), FASTA_WRAP):
self.handle.write (bases[ix:ix+FASTA_WRAP] + '\n')
def close (self):
self.handle.close()
logger.debug('closed %s' % self.name)
def makeRef (self):
'''Invoke bowtie-build on the fasta file.'''
if not self.handle.closed:
self.close()
command = '%s %s %s > %s.out 2>&1' % (BOWTIE_BUILD, self.name, self.name, self.name)
logger.debug(command)
buildOut = os.popen (command) # this should return nothing, since we've redirected the output
rc = buildOut.close()
if rc is not None:
raise RuntimeError ('bowtie2-build failed: %d' % rc)
if __name__ == "__main__":
main()