-
Notifications
You must be signed in to change notification settings - Fork 16
/
bigWig.R
354 lines (317 loc) · 13.2 KB
/
bigWig.R
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
### =========================================================================
### BigWig support
### -------------------------------------------------------------------------
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### Classes
###
setClass("BigWigFile", contains = "BiocFile")
setClass("BWFile", contains = "BigWigFile")
BigWigFile <- function(path) {
if (!isSingleString(path))
stop("'filename' must be a single string, specifying a path")
new("BigWigFile", resource = path)
}
BWFile <- BigWigFile
setMethod("seqinfo", "BigWigFile", function(x) {
seqlengths <- .Call(BWGFile_seqlengths, expandPath(path(x)))
Seqinfo(names(seqlengths), seqlengths) # no circularity information
})
setClass("BigWigFileList", contains = "BiocFileList",
prototype = prototype(elementType = "BigWigFile"))
BigWigFileList <- function(path)
{
new("BigWigFileList", listData = (lapply(path, BigWigFile)))
}
setMethod("path", "BigWigFileList",
function(object, ...)
{
sapply(as.list(object), path)
})
.allowedColNames <- list(bigWig = "score")
.validateColNames <- function(object, format) {
allowedColNames <- .allowedColNames[[format]]
invalidColNames <- setdiff(colnames(object), allowedColNames)
if (length(invalidColNames))
paste("Column names",
paste("'", invalidColNames, "'", sep = "", collapse=", "),
"are invalid for the", format, "format.")
else NULL
}
setClass("BigWigSelection", prototype = prototype(colnames = "score"),
contains = "RangedSelection")
setValidity("BigWigSelection",
function(object) {
.validateColNames(object, "bigWig")
})
BigWigSelection <- function(ranges=IRangesList(), colnames = "score") {
if (!is.character(colnames) ||
(length(colnames) && !identical(colnames, "score")))
stop("'score' is the only valid column for BigWig")
if (is.character(ranges))
new("BigWigSelection", GenomicSelection(ranges, colnames = colnames))
else {
if (is(ranges, "BigWigFile"))
ranges <- seqinfo(ranges)
new("BigWigSelection", ranges = as(ranges, "IntegerRangesList"),
colnames = colnames)
}
}
setAs("IntegerRangesList", "BigWigSelection", function(from) {
new("BigWigSelection", as(from, "RangedSelection"), colnames = "score")
})
setAs("GenomicRanges", "BigWigSelection", function(from) {
as(as(from, "IntegerRangesList"), "BigWigSelection")
})
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### Export
###
setGeneric("export.bw", function(object, con, ...) standardGeneric("export.bw"))
setMethod("export.bw", "ANY",
function(object, con, ...)
{
export(object, con, "BigWig", ...)
})
setMethod("export", c("ANY", "BigWigFile"),
function(object, con, format, ...)
{
object <- as(object, "GRanges")
callGeneric()
})
setMethod("export", c("GenomicRanges", "BigWigFile"),
function(object, con, format,
dataFormat = c("auto", "variableStep", "fixedStep",
"bedGraph"),
compress = TRUE, fixedSummaries = FALSE)
{
if (!missing(format))
checkArgFormat(con, format)
con <- path.expand(path(con))
object <- sortBySeqnameAndStart(object)
score <- score(object)
if (isValidScore(score))
stop("The score must be numeric, without any NA's")
if (!isTRUEorFALSE(compress))
stop("'compress' must be TRUE or FALSE")
seqlengths <- seqlengths(object)
if (any(is.na(seqlengths)))
stop("Unable to determine seqlengths; either specify ",
"'seqlengths' or specify a genome on 'object' that ",
"is known to BSgenome or UCSC")
sectionPtr <- NULL # keep adding to the same linked list
.bigWigWriter <- function(chromData, con, dataFormat, append) {
if (length(chromData) == 0L)
return()
if (any(tail(start(chromData), -1) <= head(end(chromData), -1)))
stop("BigWig ranges cannot overlap")
sectionPtr <<- .Call(BWGSectionList_add, sectionPtr,
as.vector(seqnames(chromData)[1]),
as(ranges(chromData), "IRanges"),
as.numeric(score(chromData)), dataFormat)
}
dataFormat <- match.arg(dataFormat)
if (dataFormat == "auto")
format <- chooseGraphType(object)
else format <- dataFormat
on.exit(.Call(BWGSectionList_cleanup, sectionPtr))
if (format == "bedGraph")
lapply(split(object, seqnames(object)), .bigWigWriter, con,
dataFormat)
else export.wig(object, con, dataFormat = dataFormat,
writer = .bigWigWriter, trackLine = FALSE)
storage.mode(seqlengths) <- "integer"
invisible(BigWigFile(.Call(BWGSectionList_write, sectionPtr,
seqlengths, compress, fixedSummaries,
con)))
})
setMethod("export", c("List", "BigWigFile"),
function(object, con, format, compress = TRUE, fixedSummaries = FALSE)
{
if (!missing(format))
checkArgFormat(con, format)
con <- path.expand(path(con))
if (!isTRUEorFALSE(compress))
stop("'compress' must be TRUE or FALSE")
if (is.null(names(object)))
stop("'object' must have names")
seqlengths <- elementNROWS(object)
sectionPtr <- NULL # keep adding to the same linked list
on.exit(.Call(BWGSectionList_cleanup, sectionPtr))
writer <- BigWigWriter(object)
for(chr in names(object)) {
sectionPtr <- writer(chr, sectionPtr)
}
invisible(BigWigFile(.Call(BWGSectionList_write, sectionPtr,
seqlengths, compress, fixedSummaries,
con)))
})
setGeneric("BigWigWriter", function(x) standardGeneric("BigWigWriter"))
setMethod("BigWigWriter", "RleList", function(x) {
function(chr, sectionPtr) {
.Call(BWGSectionList_add, sectionPtr,
chr, ranges(x[[chr]]), as.numeric(runValue(x[[chr]])),
"bedGraph")
}
})
setMethods("BigWigWriter", list("IntegerList", "NumericList"), function(x) {
function(chr, sectionPtr) {
.Call(BWGSectionList_add, sectionPtr,
chr, NULL, as.numeric(x[[chr]]),
"fixedStep")
}
})
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### Import
###
setGeneric("import.bw", function(con, ...) standardGeneric("import.bw"))
setMethod("import.bw", "ANY",
function(con, ...)
{
import(con, "BigWig", ...)
})
### Consider the use cases:
### - Extract whole genome or whole chromosome coverage as Rle (ChIP-seq)
### - Use coverage() fast path
### - Extract single position coverage for millions of variants
### - Slow to query by position, so extract whole genome/chromosome (above),
### then use findRun trick.
### - Extract single position coverage for a hundred hot-spot variants
### - coverage() should be fast enough, followed by findRun trick.
### - Extract coverage for one/all genes and summarize (RNA-seq?)
### - probably want summarize,BigWigFile
setMethod("import", "BigWigFile",
function(con, format, text, selection = BigWigSelection(which, ...),
which = con,
as = c("GRanges", "RleList", "NumericList"), ...)
{
if (!missing(format))
checkArgFormat(con, format)
as <- match.arg(as)
if (is(which, "GenomicRanges") && as == "NumericList") {
orig_order <- order(seqnames(which))
}
selection <- as(selection, "BigWigSelection")
validObject(selection)
si <- seqinfo(con)
which <- ranges(selection)
badSpaces <- setdiff(names(which)[lengths(which) > 0L],
seqlevels(si))
if (length(badSpaces) > 0L)
warning("'which' contains seqnames not known to BigWig file: ",
paste(badSpaces, collapse = ", "))
which <- which[names(which) %in% seqlevels(si)]
flatWhich <- unlist(which, use.names = FALSE)
if (is.null(flatWhich))
flatWhich <- IRanges()
which_rl <- split(flatWhich, factor(space(which), seqlevels(si)))
if (as != "NumericList") {
which_rl <- as(which, "NormalIRangesList")
}
which <- GRanges(which_rl)
names(which) <- names(unlist(which_rl, use.names=FALSE))
C_ans <- .Call(BWGFile_query, expandPath(path(con)),
as.character(seqnames(which)), ranges(which),
identical(colnames(selection), "score"),
as == "NumericList")
if (as == "NumericList") {
ans <- as(C_ans, "NumericList")
names(ans) <- names(which)
metadata(ans) <- list(ranges = as(which, "GRanges"))
if (exists("orig_order")) {
ans[orig_order] <- ans
}
ans
} else {
nhits <- C_ans[[3L]]
gr <- GRanges(rep(seqnames(which), nhits), C_ans[[1L]],
seqinfo=si)
gr$score <- C_ans[[2L]]
if (as == "RleList") {
coverage(gr, weight="score")
} else {
strand(gr) <- "*"
gr
}
}
})
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### Summary
###
setMethod("summary", "BigWigFile",
function(object, which = as(seqinfo(object), "GenomicRanges"),
size = 1L, type = c("mean", "min", "max", "coverage", "sd"),
defaultValue = NA_real_, asRle = FALSE,
as = c("GRangesList", "RleList", "matrix"), ...)
{
### FIXME: could do with "GenomicRanges" here, but
### coercions generally only exist for GRanges specifically
which <- as(which, "GRanges")
if (!is.numeric(size))
stop("'size' must be numeric")
size <- recycleIntegerArg(size, "size", length(which))
as <- match.arg(as)
if (any(size > width(which)) && as != "matrix")
stop("some 'which' are smaller than 'size'; ",
"consider passing as='matrix'")
if (as == "matrix" && (length(size) == 0L || any(size != size[1L])))
stop("for as='matrix', there must be one unique 'size'")
type <- match.arg(type)
if (!missing(asRle))
warning("argument asRle is deprecated; use as='RleList'")
if (asRle)
as <- "RleList"
if (type == "sd") type <- "std"
if (!isSingleNumberOrNA(defaultValue))
stop("'defaultValue' must be a single number or NA")
summaryList <- .Call(BWGFile_summary, path.expand(path(object)),
as.character(seqnames(which)),
ranges(which), size, type,
as.numeric(defaultValue))
if (as == "matrix") {
return(do.call(rbind, summaryList))
}
tiles <- tile(which, n = size)
if (asRle) {
setNames(RleList(mapply(Rle, summaryList, as.list(width(tiles))),
compress=FALSE),
names(which))
} else {
tiles <- unlist(tiles)
tiles$score <- unlist(summaryList)
relist(tiles, summaryList)
}
})
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### Conversion
###
wigToBigWig <-
function(x, seqinfo,
dest = paste(file_path_sans_ext(x, TRUE), "bw", sep = "."),
clip = FALSE)
{
if (!isSingleString(x))
stop("'x' must be a single string, the path to a WIG file")
if (!isSingleString(dest))
stop("'dest' must be a single string, the path to the BigWig output")
if (!is(seqinfo, "Seqinfo"))
stop("'seqinfo' must be NULL or a Seqinfo object")
if (!isTRUEorFALSE(clip))
stop("'clip' must be TRUE or FALSE")
seqlengths <- seqlengths(seqinfo)
if (any(is.na(seqlengths)))
stop("'seqlengths(seqinfo)' must not contain any 'NA' values")
x <- path.expand(x)
dest <- path.expand(dest)
ans <- .Call(BWGFile_fromWIG, x, clip, seqlengths, dest)
invisible(BigWigFile(ans))
}
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### Utilities
###
## Remote data are cached locally. Need a way to cleanup.
cleanupBigWigCache <- function(maxDays = 0) {
stopifnot(isSingleNumber(maxDays))
dir <- "/tmp/udcCache"
if (file.exists(dir)) {
invisible(.Call(R_udcCleanup, maxDays))
}
}