Repository navigation
Expand file tree
/
Copy pathhelper.R
More file actions
289 lines (253 loc) · 9.59 KB
/
Copy pathhelper.R
File metadata and controls
289 lines (253 loc) · 9.59 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
#
# find_peak
#
find_peak <- function(gene, acceptor_sites, gene_strand, feature_type,
smoothed=FALSE, include_plot=FALSE, secondary=FALSE) {
# Determine orientation of feature relative to CDS
if ((feature_type == 'sl' && gene_strand == '+') ||
(feature_type == 'polya' && gene_strand == '-')) {
feature_side <- 'left'
} else {
feature_side <- 'right'
}
# Create a vector from the furthest SL site to the CDS boundary
if (feature_side == 'left') {
cds_boundary <- start(gene)
raw_scores <- rep(0, cds_boundary - min(start(acceptor_sites)))
rel_start <- cds_boundary - start(acceptor_sites) + 1
} else {
cds_boundary <- end(gene)
raw_scores <- rep(0, max(start(acceptor_sites)) - cds_boundary)
rel_start <- start(acceptor_sites) - cds_boundary + 1
}
# add scores at indices where acceptor sites were detected
raw_scores[rel_start] <- score(acceptor_sites)
x <- 1:length(raw_scores)
# create smooted version of scores (optional)
if (smoothed) {
input_scores <- ksmooth(x, raw_scores, kernel="normal", bandwidth=6,
n.points=length(x))$y
} else {
input_scores <- raw_scores
}
# find acceptor site peak
if (secondary && (length(acceptor_sites) >= 2)) {
# secondary site
j <- 2
} else {
# primary site
j <- 1
}
sorted_scores <- sort(input_scores, decreasing=TRUE)
raw_idx <- which(input_scores == sorted_scores[j])
if (length(raw_idx) > 1) {
if (feature_side == 'left') {
raw_idx <- head(raw_idx, 1)
} else {
raw_idx <- tail(raw_idx, 1)
}
}
# find raw score (number of reads) for the desired primary or secondary
# site peak
raw_score <- raw_scores[raw_idx]
# If smoothing was used, the actual location of the smoothed peak may not
# have any support. In this case we will find the nearest site to the peak
# with a non-zero score in the raw scores vector
while(raw_score == 0) {
# find next highest peak
j <- j + 1
raw_idx <- which(input_scores == sorted_scores[j])
# if more than one peak, choose the furthest one from CDS
if (length(raw_idx) > 1) {
if (feature_side == 'left') {
raw_idx <- head(raw_idx, 1)
} else {
raw_idx <- tail(raw_idx, 1)
}
}
raw_score <- raw_scores[raw_idx]
}
# plot raw and smoothed peaks
if (include_plot) {
if (smoothed) {
df <- melt(data.frame(x, raw=raw_scores, smoothed=input_scores),
id=c("x"), variable.name='type')
print(qplot(x, value, data=df, color=type, geom='line')
+ ggtitle(gene$ID))
} else {
df <- melt(data.frame(x, raw=raw_scores), id=c("x"),
variable.name='type')
print(qplot(x, value, data=df, geom='line')
+ ggtitle(gene$ID))
}
}
# find index of the site with the highest score (or second highest score,
# in the case of secondary site selection)
idx <- which(score(acceptor_sites) == raw_score)
# if there is a tie, use the furthest site from CDS
if (length(idx) > 1) {
if (feature_side == 'left') {
idx <- head(idx, 1)
} else {
idx <- tail(idx, 1)
}
}
return(idx)
}
#
# find_primary_site
#
# Determines the primary site among a list of acceptor sites and their
# associated score (number of reads mapped).
#
# Returns a list containing the site and score for the primary site.
#
find_primary_site <- function(acceptor_sites, feature, gene, gene_strand, smoothed=FALSE) {
if (length(acceptor_sites) == 0) {
return(list(location=NA, num_reads=NA))
} else if (length(acceptor_sites) == 1) {
# if only one site found, use it
return(list(location=start(acceptor_sites)[1],
num_reads=score(acceptor_sites)[1]))
}
# two or more sites
# find highest smoothed peak which has non-zero coverage in the raw
# data as well
max_index <- find_peak(gene, acceptor_sites, gene_strand, feature,
smoothed=smoothed)
if (smoothed) {
max_index_smoothed <- find_peak(gene, acceptor_sites, gene_strand,
feature, smoothed=TRUE)
# if the smoothing would result in a different primary UTR choice,
# plot the raw and smoothed versions of the data
if (abs(max_index - max_index_smoothed) > 15) {
num_diff <- num_diff + 1
if (plot_num <= max_plots) {
sprintf("PLOTTING %d/%d", plot_num, max_plots)
#tmp <- find_peak(gene, acceptor_sites, gene_strand, feature,
# smoothed=TRUE, include_plot=TRUE)
plot_num <- plot_num + 1
}
}
}
return(list(location=start(acceptor_sites)[max_index],
num_reads=score(acceptor_sites)[max_index]))
}
#
# find_secondary_site
#
# Determines the secondary site among a list of acceptor sites and their
# associated score (number of reads mapped).
#
# Returns a list containing the site and score for the secondary site.
#
find_secondary_site <- function(acceptor_sites, feature, gene, gene_strand,
smoothed=FALSE) {
# If zero or one sites are found, then there is no secondary site detected
if (length(acceptor_sites) <= 1) {
return(list(location=NA, num_reads=NA))
}
# find second highest peak
secondary_site_index <- find_peak(gene, acceptor_sites, gene_strand,
feature, smoothed=smoothed, secondary=TRUE)
if (smoothed) {
secondary_site_index_smoothed <- find_peak(gene, acceptor_sites,
gene_strand, feature,
smoothed=TRUE,
secondary=TRUE)
# if the smoothing would result in a different secondary UTR choice,
# plot the raw and smoothed versions of the data
#if (abs(secondary_site_index - secondary_site_index_smoothed) > 15) {
# num_diff <- num_diff + 1
# if (plot_num <= max_plots) {
# tmp <- find_peak(gene, acceptor_sites, gene_strand, feature,
# smoothed=TRUE, include_plot=TRUE,
# secondary=TRUE)
# plot_num <- plot_num + 1
# }
#}
}
return(list(location=start(acceptor_sites)[secondary_site_index],
num_reads=score(acceptor_sites)[secondary_site_index]))
}
}
#
# get_utr_sequences
#
# Returns a vector of Biostrings instances containing the UTR sequence for each
# input gene.
#
get_utr_sequences <- function(genes, fasta, utr_lengths, utr5=TRUE) {
# retrieve utr length if known
widths <- data.frame(id=genes$ID, width=NA)
widths$width <- utr_lengths[match(genes$ID, utr_lengths$name),]$length
# For UTRs of unknown length, set to 0 for now; will set back to NA later
unknown_utrs <- is.na(widths$width)
widths$width[unknown_utrs] <- 0
# get positive and negative strand genes
if (utr5) {
utr <- flank(genes, widths$width)
} else {
utr <- flank(genes, widths$width, start=FALSE)
}
pos_strand <- utr[as.character(strand(utr)) == "+"]
neg_strand <- utr[as.character(strand(utr)) == "-"]
# for genes that were assigned the default UTR size, make sure that the
# assigned boundaries fall within the chromosome
#start(pos_strand) <- pmax(1, start(pos_strand))
#start(neg_strand) <- pmax(1, start(neg_strand))
end(pos_strand) <- pmin(end(pos_strand), width(fasta[seqnames(pos_strand)]))
end(neg_strand) <- pmin(end(neg_strand), width(fasta[seqnames(neg_strand)]))
seqs <- fasta[pos_strand]
seqs <- append(seqs, reverseComplement(fasta[neg_strand]))
names(seqs) <- c(pos_strand$ID, neg_strand$ID)
return(seqs)
}
#
# get_num_reads
#
# Returns the number of reads mapped to a given position for the specified
# stage, or 0 if none are found
#
get_num_reads <- function(utr_reads, site) {
if (is.na(site)) {
return(NA)
}
num_reads <- score(utr_reads[start(utr_reads) == site])
return(ifelse(length(num_reads) == 0, 0, num_reads))
}
#
# get_utr_composition
#
# Creates a dataframe containing the GC richness and CT richness for each
# input sequence.
#
get_utr_composition <- function (seqs) {
freqs <- alphabetFrequency(seqs)
df <- data.frame(
name=names(seqs),
gc=round((freqs[,'G'] + freqs[,'C']) / rowSums(freqs[,1:4]), 3),
ct=round((freqs[,'C'] + freqs[,'T']) / rowSums(freqs[,1:4]), 3)
)
# If length is unknown or sequence contains mostly N's, make NA
na_ind <- (freqs[,'N'] / width(seqs)) > 0.5
na_ind[is.na(na_ind)] <- TRUE
df[na_ind, 'gc'] <- NA
df[na_ind, 'ct'] <- NA
df[width(seqs) == 0, 'gc'] <- NA
df[width(seqs) == 0, 'ct'] <- NA
return(df)
}
# rescale to range 0-1
# if trimmed=TRUE, outliers will be trimmed first to reduce their influence on
# the resulting colorscale
rescale <- function (x, trimmed=TRUE, trim_quantile=0.99) {
if (trimmed) {
lower_bound <- quantile(x, 1 - trim_quantile)
upper_bound <- quantile(x, trim_quantile)
x <- pmax(pmin(x, upper_bound), lower_bound)
return(pmax(0, ((x-min(x)) / (max(x) - min(x)))))
}
# no trimming
return(pmax(0, ((x-min(x)) / (max(x) - min(x)))))
}