forked from brianpenghe/bamsam-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sampleSAM.py
89 lines (73 loc) · 2.41 KB
/
sampleSAM.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
##################################
# #
# Last modified 02/03/2013 #
# #
# Georgi Marinov #
# #
##################################
import sys
import os
import pysam
import random
import string
from sets import Set
def main(argv):
if len(argv) < 3:
print 'usage: python %s SAMfilename <Number Reads> outputfilename' % argv[0]
print ' Note1: do not run this code on SAM files where identical read IDs correspond to different reads'
print ' i.e. if for example reads come from lane1 of flowcell A and lane1 of flowcell B'
print ' Note2: if reads are paired-end, the program will return the specified number of pairs, not individual reads'
sys.exit(1)
SAM = argv[1]
numReads = int(argv[2])
outputfilename = argv[3]
doPaired=False
if '-paired' in argv:
doPaired=True
i=0
print 'Getting Read IDs'
ReadIDList=[]
lineslist = open(SAM)
for line in lineslist:
if line.startswith('@'):
continue
i+=1
if i % 10000000 == 0:
print str(i/1000000) + 'M alignments'
fields = line.strip().split('\t')
if fields[0].endswith('/1') or fields[0].endswith('/2'):
ID=fields[0][0:-2]
else:
ID=fields[0]
ReadIDList.append(ID)
outfile=open(outputfilename, 'w')
ReadIDList=list(Set(ReadIDList))
print 'found', len(ReadIDList), 'fragments'
SubSampleIDs=random.sample(ReadIDList,numReads)
SubSampleIDDict={}
for ID in SubSampleIDs:
SubSampleIDDict[ID]=''
print 'sampled', (len(SubSampleIDs)), 'IDs'
ReadIDList=[]
SubSampleIDs=[]
print 'Outputting sub-sampled alignments'
lineslist = open(SAM)
i=0
for line in lineslist:
if line.startswith('@'):
# outfile.write(line)
continue
i+=1
if i % 10000000 == 0:
print str(i/1000000) + 'M alignments'
fields = line.strip().split('\t')
if fields[0].endswith('/1') or fields[0].endswith('/2'):
ID=fields[0][0:-2]
else:
ID=fields[0]
if SubSampleIDDict.has_key(ID):
outfile.write(line)
print 'outputted', len(SubSampleIDDict.keys()), 'out of', len(ReadIDList), 'fragments'
outfile.close()
if __name__ == '__main__':
main(sys.argv)