-
Notifications
You must be signed in to change notification settings - Fork 6
/
exon_seek.py
executable file
·337 lines (303 loc) · 18.7 KB
/
exon_seek.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
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
325
326
327
328
329
330
331
332
333
334
335
336
337
#!/usr/bin/env python
# Copyright (C) 2012-2013 Collin Tokheim
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
File: exon_seek.py
Author: Collin Tokheim
Description: exon_seek.py holds the ExonSeek class which searches
for appropriate flanking "constitutive" exons to place primers on.
'''
import algorithms as algs
import multinomial_em as mem
import logging
import json
import utils
class ExonSeek(object):
'''
This class handles the finding exons with a psi value threshold. That is,
it finds flanking exons to place primers where the exon inclusion level is
above a user-defined value.
'''
def __init__(self, target, splice_graph, ID, cutoff, upstream=None, downstream=None):
'''
As the purpose of ExonSeek is to flanking constitutive exons, it is
necessary to know what needs to be "flanked", the target, and have a
splice graph representation of gene structure (splice_graph). The ID
variable is meant to prevent overwriting of files.
'''
self.id = ID # id is to prevent overwriting files in self.save_path_info
self.cutoff = cutoff
self.target = target # (start, end)
self.upstream, self.downstream = upstream, downstream # if set, the user specified upstream or downstream exons
self.graph = splice_graph.get_graph() # convenience variable (could just use splice_graph)
if self.target not in self.graph.nodes():
raise utils.PrimerSeqError('Error: The target was not found in the splice graph')
self.strand = splice_graph.strand # convenience variable
self.splice_graph = splice_graph
biconnected_comp = filter(lambda x: target in x, algs.get_biconnected(self.graph))
self.total_components = None # these will be defined after calling methods
self.psi_upstream, self.psi_target, self.psi_downstream = None, None, None # these will be defined after calling methods
self.all_paths = None
self.num_of_biconnected = len(biconnected_comp)
if len(self.graph.predecessors(self.target)) == 0 or len(self.graph.successors(self.target)) == 0:
self.component = None # no flanking exon case
elif self.num_of_biconnected == 0:
self.no_biconnected_case()
elif self.num_of_biconnected == 1:
self.component = sorted(biconnected_comp[0], key=lambda x: (x[0], x[1])) # make sure component is sorted by position
self.one_biconnected_case()
elif self.num_of_biconnected == 2:
self.component = map(lambda x: sorted(x, key=lambda y: (y[0], y[1])), biconnected_comp)
self.two_biconnected_case()
else:
raise ValueError('Error: There to be either 0, 1, or 2 biconnected components. Received %s' % self.num_of_biconnected)
def get_info(self):
'''
Return all of the important variables in just one method call.
'''
return self.all_paths, self.upstream, self.downstream, self.component, self.psi_target, self.psi_upstream, self.psi_downstream
def save_path_info(self, p, cts):
'''
Save information about isoforms and their read counts into a json file.
'''
with open('tmp/isoforms/' + str(self.id) + '.json', 'w') as handle:
json.dump({'path': p, 'counts': list(cts)}, handle, indent=4) # output path information to tmp file
self.paths, self.counts = p, cts # store for programatic access
def find_closest_exon_above_cutoff(self, paths, counts, possible_exons):
"""
Progressively step away from the target exon to find a sufficient constitutive exon
"""
psi_list = []
for exon in possible_exons:
psi = mem.estimate_psi(exon, paths, counts)
psi_list.append(psi)
if psi >= self.cutoff:
return exon, psi
# If code reaches this point then there was no flanking exon that met
# the self.cutoff criteria. Raise utils.PrimerSeqError to indicate failure.
raise utils.PrimerSeqError('A sufficiently high included flanking exon could '
'not be found (max: %.3f, cutoff: %.3f)' % (max(psi_list), self.cutoff))
def two_biconnected_case(self):
'''
This is a case where the target exon is constitutive but has two
flanking biconnected components. Meaning estimating psi for both
the upstream and downstream exon is necessary
'''
print 'two biconnected case'
if self.component[0][-1] == self.target:
before_component, after_component = self.component
else:
after_component, before_component = self.component
# since there is two components I need two subgraphs/paths. One for
# before and after the target exon (before/after are defined by
# chromosome position)
before_all_paths = algs.AllPaths(self.splice_graph, before_component, self.target, self.splice_graph.chr)
before_all_paths.trim_tx_paths()
before_paths, before_counts = before_all_paths.estimate_counts()
after_all_paths = algs.AllPaths(self.splice_graph, after_component, self.target, self.splice_graph.chr)
after_all_paths.trim_tx_paths()
after_paths, after_counts = after_all_paths.estimate_counts()
if self.upstream and self.downstream:
if self.strand == '+':
self.psi_upstream = mem.estimate_psi(self.upstream, before_paths, before_counts)
self.psi_downstream = mem.estimate_psi(self.downstream, after_paths, after_counts)
elif self.strand == '-':
self.psi_upstream = mem.estimate_psi(self.upstream, after_paths, after_counts)
self.psi_downstream = mem.estimate_psi(self.downstream, before_paths, before_counts)
elif self.strand == '+':
self.upstream, self.psi_upstream = self.find_closest_exon_above_cutoff(before_paths,
before_counts,
list(reversed(before_component[:-1])))
self.downstream, self.psi_downstream = self.find_closest_exon_above_cutoff(after_paths,
after_counts,
after_component[1:])
else:
self.upstream, self.psi_upstream = self.find_closest_exon_above_cutoff(after_paths,
after_counts,
after_component[1:])
self.downstream, self.psi_downstream = self.find_closest_exon_above_cutoff(before_paths,
before_counts,
list(reversed(before_component[:-1])))
self.total_components = before_component[:-1] + after_component
self.psi_target = 1.0
# handle the combined components
tmp_start_ix = self.total_components.index(self.upstream) if self.splice_graph.strand == '+' else self.total_components.index(self.downstream)
tmp_end_ix = self.total_components.index(self.downstream) if self.splice_graph.strand == '+' else self.total_components.index(self.upstream)
self.all_paths = algs.AllPaths(self.splice_graph, self.total_components[tmp_start_ix:tmp_end_ix], self.target, self.splice_graph.chr)
self.all_paths.trim_tx_paths()
self.all_paths.set_all_path_coordinates()
self.paths, self.counts = self.all_paths.estimate_counts() # used to be self.before_all_paths
utils.save_path_info(self.id, self.paths, self.counts)
def no_biconnected_case(self):
'''
Case where the target, upstream, and downstream exons are all
constitutive. Thus just return the immediate upstream and downstream
exon along with original target.
'''
print 'no biconnected case'
# add information to log file
logging.debug('It appears %s has two imediate flanking constitutive exons' % str(self.target))
if len(self.graph.successors(self.target)) > 1:
logging.debug('Conflict between biconnected components and successors')
if len(self.graph.predecessors(self.target)) > 1:
logging.debug('Conflict between biconnected components and predecessors')
if self.upstream and self.downstream:
tmp_upstream = self.graph.predecessors(self.target)[0] if self.strand == '+' else self.graph.successors(self.target)[0]
# define adjacent exons as flanking constitutive since all three (the
# target exon, upstream exon, and downstream exon) are constitutive
tmp_upstream = self.graph.predecessors(self.target)[0] if self.strand == '+' else self.graph.successors(self.target)[0]
tmp_downstream = self.graph.successors(self.target)[0] if self.strand == '+' else self.graph.predecessors(self.target)[0]
if self.upstream and self.downstream:
if self.upstream != tmp_upstream or self.downstream != tmp_downstream:
# raise error if the user defined exon does not match expectation
raise utils.PrimerSeqError('Error: Flanking exon choice too far from target exon')
self.upstream = tmp_upstream # assign upstream after user-defined exon check
self.downstream = tmp_downstream # assign downstream after user-defined exon check
# defining two attributes as the same thing seems silly but in a
# different case with two biconnected components the two components
# need to be merged into a single self.total_components
self.total_components = [self.upstream, self.target, self.downstream]
self.component = self.total_components
# create a dummy all paths variable even though there is only one path
self.all_paths = algs.AllPaths(self.splice_graph, self.component, self.target, self.splice_graph.chr)
self.all_paths.trim_tx_paths()
self.all_paths.set_all_path_coordinates()
# only one isoform, so read counts do not really matter
self.paths, self.counts = self.all_paths.estimate_counts()
utils.save_path_info(self.id, self.paths, self.counts)
# since the upstream, target, and downstream exon are constitutive then
# they all have inclusion of 1.0
self.psi_target, self.psi_upstream, self.psi_downstream = 1.0, 1.0, 1.0
def one_biconnected_case(self):
'''
Target exon could be cons_titutive or alternatively spliced.
'''
if self.target == self.component[0]:
# constitutive exon of biconnected component, exons with > start pos are
# not constitutive. However, the immediate preceding exon will be
# constitutive
self.first_exon_case()
elif self.target == self.component[-1]:
# constitutive exon of biconnected component, exons with < start pos are not
# constitutive. However, the immediate successor exon will be
# constitutive.
self.last_exon_case()
else:
# non-constitutive exon case
self.non_constitutive_case()
self.total_components = self.component
def non_constitutive_case(self):
'''
In this case, I also estimate the psi for the target exon since
it is alternatively spliced. Both upstream and downstream exons are
checked for the closest sufficiently included exon.
'''
print 'non-constitutive case'
index = self.component.index(self.target)
# get tx path information
self.all_paths = algs.AllPaths(self.splice_graph, self.component, self.target, self.splice_graph.chr)
self.all_paths.trim_tx_paths()
self.all_paths.set_all_path_coordinates()
self.paths, self.counts = self.all_paths.estimate_counts()
if self.upstream and self.downstream:
# known flanking exon case
self.psi_upstream = mem.estimate_psi(self.upstream, self.paths, self.counts)
self.psi_downstream = mem.estimate_psi(self.downstream, self.paths, self.counts)
elif self.strand == '-':
self.upstream, self.psi_upstream = self.find_closest_exon_above_cutoff(self.paths,
self.counts,
self.component[index + 1:])
self.downstream, self.psi_downstream = self.find_closest_exon_above_cutoff(self.paths,
self.counts,
list(reversed(self.component[:index])))
else:
self.upstream, self.psi_upstream = self.find_closest_exon_above_cutoff(self.paths,
self.counts,
list(reversed(self.component[:index])))
self.downstream, self.psi_downstream = self.find_closest_exon_above_cutoff(self.paths,
self.counts,
self.component[index + 1:])
utils.save_path_info(self.id, self.paths, self.counts)
self.psi_target = mem.estimate_psi(self.target, self.paths, self.counts)
def first_exon_case(self):
'''
Case where the target and one flanking exon is constitutive.
'''
print 'first exon case'
if len(self.graph.predecessors(self.target)) > 1:
logging.debug('Error: Conflict between biconnected components and predecessors')
# get tx path information
self.all_paths = algs.AllPaths(self.splice_graph, self.component, self.target, self.splice_graph.chr)
self.all_paths.trim_tx_paths()
self.all_paths.set_all_path_coordinates()
self.paths, self.counts = self.all_paths.estimate_counts()
if self.upstream and self.downstream:
# user defined flanking exon case
if self.strand == '+' and self.graph.predecessors(self.target)[0] == self.upstream:
self.psi_upstream = 1.0
self.psi_downsteam = mem.estimate_psi(self.downstream, self.paths, self.counts)
elif self.strand == '-' and self.graph.predecessors(self.target)[0] == self.downstream:
self.psi_downstream = 1.0
self.psi_upstream = mem.estimate_psi(self.upstream, self.paths, self.counts)
else:
raise utils.PrimerSeqError('Error: Flanking exon choice too far from target exon')
elif self.strand == '+':
self.upstream = self.graph.predecessors(self.target)[0]
self.psi_upstream = 1.0 # defined by biconnected component alg as constitutive
self.downstream, self.psi_downstream = self.find_closest_exon_above_cutoff(self.paths,
self.counts, self.component[1:])
utils.save_path_info(self.id, [[self.upstream] + p for p in self.paths], self.counts) # add const. upstream exon to all self.paths
else:
self.upstream, self.psi_upstream = self.find_closest_exon_above_cutoff(self.paths,
self.counts, self.component[1:])
self.downstream = self.graph.predecessors(self.target)[0]
self.psi_downstream = 1.0
utils.save_path_info(self.id, [p + [self.downstream] for p in self.paths], self.counts) # add const. downstream exon to all paths
self.psi_target = 1.0
def last_exon_case(self):
'''
Case where the target and one flanking exon are constitutive.
'''
print 'last exon case'
if len(self.graph.successors(self.target)) > 1:
logging.debug('Conflict between biconnected components and successors')
possible_const = self.component[:-1]
possible_const.reverse() # reverse the order since closer exons should be looked at first
# get tx path information
self.all_paths = algs.AllPaths(self.splice_graph, self.component, self.target, self.splice_graph.chr)
self.all_paths.trim_tx_paths()
self.all_paths.set_all_path_coordinates()
self.paths, self.counts = self.all_paths.estimate_counts()
if self.upstream and self.downstream:
# user defined flanking exon case
if self.strand == '+':
self.psi_upstream = mem.estimate_psi(self.upstream, self.paths, self.counts)
self.psi_downstream = 1.0
elif self.strand == '-':
self.psi_upstream = 1.0
self.psi_downstream = mem.estimate_psi(self.downstream, self.paths, self.counts)
if self.strand == '+':
self.upstream, self.psi_upstream = self.find_closest_exon_above_cutoff(self.paths,
self.counts, possible_const)
self.downstream = self.graph.successors(self.target)[0]
self.psi_downstream = 1.0
utils.save_path_info(self.id, [p + [self.downstream] for p in self.paths], self.counts) # add const. downstream exon to all self.paths
else:
self.upstream = self.graph.successors(self.target)[0]
self.psi_upstream = 1.0
self.downstream, self.psi_downstream = self.find_closest_exon_above_cutoff(self.paths,
self.counts, possible_const)
utils.save_path_info(self.id, [[self.upstream] + p for p in self.paths], self.counts) # add const. upstream exon to all paths
self.psi_target = 1.0 # the target is constitutive in this case