-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathload_data.py
More file actions
executable file
·324 lines (238 loc) · 9.83 KB
/
load_data.py
File metadata and controls
executable file
·324 lines (238 loc) · 9.83 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
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
import numpy as np
import pysam
import utils
import pdb
MIN_MAP_QUAL = 10
class Genome():
def __init__(self, fasta_filename, map_filename):
self._seq_handle = pysam.FastaFile(fasta_filename)
self._map_handles = [pysam.TabixFile(map_filename+'_%d.gz'%r)
for r in utils.READ_LENGTHS]
def get_sequence(self, transcripts):
sequences = []
for transcript in transcripts:
# get DNA sequence
seq = self._seq_handle.fetch(transcript.chromosome, transcript.start, transcript.stop).upper()
# get DNA sequence of transcript
# reverse complement, if necessary
if transcript.strand=="-":
seq = seq[::-1]
seq = ''.join(np.array(list(seq))[transcript.mask].tolist())
seq = utils.make_complement(seq)
else:
seq = ''.join(np.array(list(seq))[transcript.mask].tolist())
# get RNA sequence
seq = ''.join(['U' if s=='T' else s for s in seq])
sequences.append(seq)
return sequences
def get_mappability(self, transcripts):
mappabilities = []
for transcript in transcripts:
# get mappable positions
mappables = [np.zeros(transcript.mask.shape, dtype='bool')
for r in utils.READ_LENGTHS]
tbx_iters = [handle.fetch(transcript.chromosome, transcript.start, transcript.stop)
for handle in self._map_handles]
if transcript.strand=='+':
offsets = [1,1,1,1]
else:
offsets = utils.READ_LENGTHS
for tbx_iter,mappable,offset in zip(tbx_iters,mappables,offsets):
for tbx in tbx_iter:
row = tbx.split('\t')
start = int(row[1]) - transcript.start + offset - 1
end = int(row[2]) - transcript.start + offset - 1
mappable[start:end] = True
if transcript.strand=='+':
mappables = np.array(mappables).T.astype('bool')
else:
mappables = np.array(mappables).T.astype('bool')[::-1]
mappabilities.append(mappables[transcript.mask,:])
return mappabilities
def close(self):
self._seq_handle.close()
ig = [handle.close() for handle in self._map_handles]
class RiboSeq():
def __init__(self, file_prefix):
self._fwd_handles = [pysam.TabixFile(file_prefix+'_fwd.%d.gz'%r)
for r in utils.READ_LENGTHS]
self._rev_handles = [pysam.TabixFile(file_prefix+'_rev.%d.gz'%r)
for r in utils.READ_LENGTHS]
def get_counts(self, transcripts):
read_counts = []
for transcript in transcripts:
rcounts = [np.zeros(transcript.mask.shape, dtype='int') for r in utils.READ_LENGTHS]
if transcript.strand=='+':
tbx_iters = [handle.fetch(transcript.chromosome, transcript.start, transcript.stop) \
for handle in self._fwd_handles]
else:
tbx_iters = [handle.fetch(transcript.chromosome, transcript.start, transcript.stop) \
for handle in self._rev_handles]
for tbx_iter,counts in zip(tbx_iters,rcounts):
for tbx in tbx_iter:
row = tbx.split('\t')
count = int(row[3])
asite = int(row[1]) - transcript.start
counts[asite] = count
if transcript.strand=='+':
rcounts = np.array(rcounts).T.astype(np.uint64)
else:
rcounts = np.array(rcounts).T.astype(np.uint64)[::-1]
read_counts.append(rcounts[transcript.mask,:])
return read_counts
def get_total_counts(self, transcripts):
read_counts = self.get_counts(transcripts)
total_counts = np.array([counts.sum() for counts in read_counts])
return total_counts
def get_exon_total_counts(self, transcripts):
exon_counts = []
for transcript in transcripts:
rcounts = [np.zeros(transcript.mask.shape, dtype='int') for r in utils.READ_LENGTHS]
if transcript.strand=='+':
tbx_iters = [handle.fetch(transcript.chromosome, transcript.start, transcript.stop) \
for handle in self._fwd_handles]
else:
tbx_iters = [handle.fetch(transcript.chromosome, transcript.start, transcript.stop) \
for handle in self._rev_handles]
for tbx_iter,counts in zip(tbx_iters,rcounts):
for tbx in tbx_iter:
row = tbx.split('\t')
count = int(row[3])
asite = int(row[1]) - transcript.start
counts[asite] = count
rcounts = np.array(rcounts).T.astype(np.uint64)
exon_counts.append(np.array([rcounts[start:end,:].sum()
for start,end in transcript.exons]))
return exon_counts
def close(self):
ig = [handle.close() for handle in self._fwd_handles]
ig = [handle.close() for handle in self._rev_handles]
class RnaSeq():
def __init__(self, filename):
self._handle = pysam.TabixFile(filename+'.gz')
self.total = 0
for chrom in self._handle.contigs:
self.total += reduce(lambda x,y: x+y, (int(tbx.split('\t')[3]) for tbx in self._handle.fetch(chrom)))
def get_total_counts(self, transcripts):
total_counts = []
for transcript in transcripts:
tbx_iter = self._handle.fetch(transcript.chromosome, transcript.start, transcript.stop)
if transcript.strand=='+':
mask = transcript.mask
else:
mask = transcript.mask[::-1]
counts = 0
for tbx in tbx_iter:
row = tbx.split('\t')
site = int(row[1])-transcript.start
count = int(row[3])
if mask[site]:
counts += 1
total_counts.append(max([1,counts])*1e6/float(transcript.L*self.total))
total_counts = np.array(total_counts)
return total_counts
def close(self):
self._handle.close()
class Transcript():
def __init__(self, line, attr):
self.id = attr['transcript_id']
self.chromosome = line[0]
self.start = int(line[3])-1
self.stop = int(line[4])
# if not specified, transcript is on positive strand
if line[6] in ['+','-']:
self.strand = line[6]
else:
self.strand = '+'
self.cdstart = None
self.cdstop = None
self.exons = []
self.has_CDS = False
self.proteinid = ''
# add attribute fields that are available
try:
self.type = attr['transcript_type']
except KeyError:
pass
try:
self.type = attr['gene_biotype']
except KeyError:
pass
try:
self.geneid = attr['gene_id']
except KeyError:
pass
try:
self.genename = attr['gene_name']
except KeyError:
pass
try:
self.ref_transcript_id = attr['reference_id']
except KeyError:
pass
try:
self.ref_gene_id = attr['ref_gene_id']
except KeyError:
pass
try:
self.genename = attr['ref_gene_name']
except KeyError:
pass
def add_exon(self, line):
exon = (int(line[3])-1, int(line[4]))
self.exons.append(exon)
def generate_transcript_model(self):
if len(self.exons)>0:
# order exons
order = np.argsort(np.array([e[0] for e in self.exons]))
self.exons = [[self.exons[o][0],self.exons[o][1]] for o in order]
# extend transcript boundaries, if needed
self.start = min([self.start, self.exons[0][0]])
self.stop = max([self.stop, self.exons[-1][-1]])
# set transcript model
self.exons = [(e[0]-self.start, e[1]-self.start) for e in self.exons]
self.mask = np.zeros((self.stop-self.start,),dtype='bool')
ig = [self.mask.__setslice__(start,stop,True) for (start,stop) in self.exons]
if self.strand=='-':
self.mask = self.mask[::-1]
self.L = self.mask.sum()
else:
# no exons for transcript; remove
raise ValueError
def load_gtf(filename):
transcripts = dict()
handle = open(filename, "r")
for line in handle:
# remove comments
if line.startswith('#'):
continue
# read data
data = line.strip().split("\t")
attr = dict([(ln.split()[0],eval(ln.split()[1])) for ln in data[8].split(';')[:-1]])
# identify chromosome of the transcript
if data[0].startswith('c'):
chrom = data[0]
else:
chrom = 'chr%s'%data[0]
data[0] = chrom
transcript_id = attr['transcript_id']
try:
# if transcript is in dictionary, only parse exons
transcripts[transcript_id]
if data[2]=='exon':
transcripts[transcript_id].add_exon(data)
else:
pass
except KeyError:
if data[2]=='transcript':
# initialize new transcript
transcripts[transcript_id] = Transcript(data, attr)
handle.close()
# generate transcript models
keys = transcripts.keys()
for key in keys:
try:
transcripts[key].generate_transcript_model()
except ValueError:
del transcripts[key]
return transcripts