File: AllClasses.R

package info (click to toggle)
r-bioc-variantannotation 1.10.5-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 2,172 kB
  • ctags: 109
  • sloc: ansic: 1,088; sh: 4; makefile: 2
file content (428 lines) | stat: -rw-r--r-- 12,617 bytes parent folder | download
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
### =========================================================================
### All classes 
### =========================================================================


### -------------------------------------------------------------------------
### VCF (VIRTUAL) 
###

setClass("VCF",
    contains=c("VIRTUAL", "SummarizedExperiment"),
    representation( 
        fixed="DataFrame",
        info="DataFrame")
)

.valid.VCF.fixed <- function(object)
{
    xlen <- dim(object)[1]
    ffld <- slot(object, "fixed")
    nms <- colnames(ffld)

    if (nrow(ffld) != 0) {
        if (nrow(ffld) != xlen)
            return(paste("'fixed(object)' and 'rowData(object) must have the same ",
                   "number of rows", sep=""))
        if (!all(nms %in% c("paramRangeID", "REF", "ALT", "QUAL", "FILTER")))
            return(paste("'fixed(object)' colnames must be ",
                   "'REF', 'ALT', 'QUAL' and 'FILTER'", sep=""))
        if ("REF" %in% nms)
            if (!is(ffld$REF, "DNAStringSet"))
                return("'ref(object)' must be a DNAStringSet")
        if ("QUAL" %in% nms)
            if (!is(ffld$QUAL, "numeric"))
                return("'qual(object)' must be numeric")
        if ("FILTER" %in% nms)
            if (!is(ffld$FILTER, "character"))
                return("'filt(object)' must be a character")
    }
    NULL
}

.valid.VCF.info <- function(object)
{
    xlen <- nrow(object)
    i <- slot(object, "info")
    if (nrow(i) != xlen)
        return("'info' must have the same number of rows as 'rowData'")
    NULL
}

.valid.VCF.alt <- function(object)
{
    if (length(alt <- alt(object))) {
        if (is(object, "ExpandedVCF")) {
            if (!is(alt, "DNAStringSet") && !is.character(alt))
                return(paste("'alt(object)' must be a DNAStringSet or a ",
                       "character", sep=""))
        } else if (is(object, "CollapsedVCF")) {
            if (!is(alt, "DNAStringSetList") && !is(alt, "CharacterList"))
                return(paste("'alt(object)' must be a DNAStringSetList or a ",
                       "CharacterList", sep=""))
        }
    }
    NULL
}

.valid.VCF <- function(object)
{
    c(.valid.VCF.fixed(object),
      .valid.VCF.info(object),
      .valid.VCF.alt(object))
}

### -------------------------------------------------------------------------
### CollapsedVCF 
###

setClass("CollapsedVCF", 
    contains="VCF",
    prototype=prototype(
      fixed=DataFrame(REF=DNAStringSet(), ALT=DNAStringSetList(),
                      QUAL=numeric(), FILTER=character())),
    validity=.valid.VCF)

setAs("CollapsedVCF", "SummarizedExperiment",
    def = function(from)
    {
        if (strict) {
            force(from)
            class(from) <- "SummarizedExperiment"
        }
        from
    },
    replace = function(from, to, value)
    {
        firstTime <- TRUE
        for (nm in slotNames(value)) {
            v <- slot(value, nm)
            if (firstTime) {
                slot(from, nm, FALSE) <- v
                firstTime <- FALSE
            } else {
                `slot<-`(from, nm, FALSE, v)
            }
        }
        from
    }
)

### -------------------------------------------------------------------------
### ExpandedVCF 
###

setClass("ExpandedVCF", 
    contains="VCF",
    prototype=prototype(
      fixed=DataFrame(REF=DNAStringSet(), ALT=DNAStringSet(),
                      QUAL=numeric(), FILTER=character())),
    validity=.valid.VCF)

### Coercion:
### Recursion problem in an automatically generated coerce method requires
### that we handle coercion from subclasses to SummarizedExperiment.

setAs("ExpandedVCF", "SummarizedExperiment",
    def = function(from)
    {
        if (strict) {
            force(from)
            class(from) <- "SummarizedExperiment"
        }
        from
    },
    replace = function(from, to, value)
    {
        firstTime <- TRUE
        for (nm in slotNames(value)) {
            v <- slot(value, nm)
            if (firstTime) {
                slot(from, nm, FALSE) <- v
                firstTime <- FALSE
            } else {
                `slot<-`(from, nm, FALSE, v)
            }
        }
        from
    }
)

### -------------------------------------------------------------------------
### VCFHeader
###

setClass("VCFHeader",
    representation(
        reference="character",
        samples="character",
        header="SimpleDataFrameList"
    )
)

.valid.VCFHeader.colnames <- function(value, slotname)
{
    if (length(value)) {
        col <- c("Number", "Type", "Description")
        if (ncol(value) != 3 || !all(names(value) %in% col))
            return(paste0("'", slotname, "(VCFHeader)' must be a ",
                   "3 column DataFrame with names ", 
                   paste(col, collapse=", ")))
        else
            return(NULL)
    }
    NULL
}

.valid.VCFHeader.info <- function(object)
    .valid.VCFHeader.colnames(info(object), "info")

.valid.VCFHeader.geno <- function(object)
    .valid.VCFHeader.colnames(geno(object), "geno")

.valid.VCFHeader.meta <- function(object)
{
    value <- meta(object)
    if (length(value)) {
        if (ncol(value) != 1 || names(value) != "Value")
            return(paste0("'meta(VCFHeader)' must be a single ",
                   "column DataFrame with name 'Value'"))
        else
            return(NULL)
    }
    NULL
}

## Test VCFHeader only 
.valid.VCFHeader <- function(object)
{
    return(c(.valid.VCFHeader.info(object),
             .valid.VCFHeader.geno(object),
             .valid.VCFHeader.meta(object)))
}
setValidity("VCFHeader", .valid.VCFHeader, where=asNamespace("VariantAnnotation"))

## These validity checks test the fields in the VCF against 
## the VCFHeader. Called from header<-,VCF-method. 
.valid.VCFHeadervsVCF.fields <- function(object, slotname)
{
    diff <- setdiff(names(slotname(object)), rownames(slotname(header(object))))
    if (length(diff)) {
        warning(paste0(attributes(slotname)$generic[1],
                " fields with no header: ", paste(diff, collapse=",")), 
                call.=FALSE)
    }
    NULL
}

.valid.VCFHeadervsVCF <- function(object)
{
    validObject(header(object))
    c(.valid.VCFHeadervsVCF.fields(object, info),
      .valid.VCFHeadervsVCF.fields(object, geno))
} 

### -------------------------------------------------------------------------
### ScanVcfParam
###

setClass("ScanVcfParam", contains="ScanBVcfParam")

### -------------------------------------------------------------------------
### SIFT, PROVEAN and PolyPhen
###

.SIFTDb <- setRefClass("SIFTDb", contains = "AnnotationDb")

.PROVEANDb <- setRefClass("PROVEANDb", contains = "AnnotationDb")

.PolyPhenDb <- setRefClass("PolyPhenDb", contains = "AnnotationDb")

### -------------------------------------------------------------------------
### VariantType class hierarchy
###

setClass("VariantType",
    representation(
        "VIRTUAL"
    )
)

setMethod("show", "VariantType",
    function(object)
    {
        cat("class:", class(object), "\n")
    }
)

setClass("CodingVariants", contains="VariantType")

setClass("IntronVariants", contains="VariantType")

setClass("ThreeUTRVariants", contains="VariantType")

setClass("FiveUTRVariants", contains="VariantType")

setClass("SpliceSiteVariants", contains="VariantType")

setClass("IntergenicVariants",
    contains="VariantType",
    representation(upstream="integer",
                   downstream="integer")
)

setClass("PromoterVariants",
    contains="VariantType",
    representation(upstream="integer",
                   downstream="integer")
)

setClass("AllVariants",
    contains="VariantType",
    representation(promoter="PromoterVariants",
                   intergenic="IntergenicVariants")
)

### -------------------------------------------------------------------------
### VRanges
###

### This is useful when variants are the unit of analysis, especially
### when diagnosis the effects of filters. Thus, this corresponds to
### an expansion of VCF, where each variant only has one alt
### allele. If the alt is NA, it describes a reference/WT call.
###

.valid.VRanges.ref <- function(object) {
  c(if (any(is.na(object@ref)))
      "'ref' must not contain 'NA' values",
    if (length(which(object@ref == object@alt)) > 0L)
      "'ref' must not match 'alt'")
}

.valid.VRanges.alt <- function(object) {
  if (any(is.na(object@alt) & !is.na(object@altDepth)))
    paste("if 'alt' is 'NA', then 'altDepth' should be 'NA'")
}

.valid.VRanges.strand <- function(object) {
  if (any(object@strand != "+"))
    paste("'strand' must always be '+'")
}

naToZero <- function(x) ifelse(is.na(x), 0L, x)

.valid.VRanges.depth <- function(object) {
  checkDepth <- function(name) {
    if (any(slot(object, name) < 0, na.rm = TRUE))
      paste0("'", name, "' must be non-negative")
  }
  depth.slots <- c("refDepth", "altDepth", "totalDepth")
  do.call(c, lapply(depth.slots, checkDepth))
}

### FIXME: we are not yet checking for redundant observations, i.e.,
### rows with the same seqname, start, end, alt, and sample.
.valid.VRanges <- function(object)
{
  c(.valid.VRanges.ref(object),
    .valid.VRanges.alt(object),
    .valid.VRanges.strand(object),
    .valid.VRanges.depth(object))
}

setTypedRle <- function(type) {
  cname <- paste0(type, "Rle")
  setClass(cname, representation(values = type), contains = "Rle")
  setValidity(cname,
              function(object) {
                if (!is(runValue(object), type))
                  paste("run values in Rle must be", type)
              })
  coercer <- get(paste0("as.", type)) # as(from, type) is NOT the same
  setAs("Rle", cname, function(from) {
    if (!is(runValue(from), type))
      slot(from, "values", check = FALSE) <- coercer(runValue(from))
    new(cname, from)
  })
  setAs("vectorORfactor", cname, function(from) {
    new(cname, Rle(coercer(from)))
  })
  setMethod("[", cname,
            function(x, i, j, ..., drop = getOption("dropRle", FALSE)) {
              as(callNextMethod(), cname)
            })
  setReplaceMethod("[", cname,
                   function(x, i, j, ..., value) {
                     if (missing(i))
                       ans <- callGeneric(x = as(x, "Rle"), value = value)
                     else
                       ans <- callGeneric(x = as(x, "Rle"), i = i, value = value)
                     as(ans, paste0(class(runValue(ans)), "Rle"))
                   })
  setMethod("window", cname,
            function(x, ...) {
              as(callNextMethod(), cname)
            })
  cname
}

### TODO: These could land in IRanges at some point. They are useful
### for constraining class representations, and are convenient
### coercion targets. In theory, we could also use them more broadly,
### i.e., for Rle method dispatch, but that would require work in
### Rle() and runValue<- first, and would break serialized objects.

setTypedRle("raw")
setTypedRle("logical")
setTypedRle("integer")
setTypedRle("numeric")
setTypedRle("complex")
setTypedRle("character")
setTypedRle("factor")

setAtomicRleUnion <- function(type) {
  cname <- paste0(type, "OrRle")
  rlename <- paste0(type, "Rle")
  setClassUnion(cname, c(type, rlename))
  coercer <- get(paste0("as.", type)) # as(from, type) is NOT the same
  setAs("ANY", cname, function(from) {
    coercer(from)
  })
  setAs("Rle", cname, function(from) {
    as(from, rlename)
  })
  cname
}

.integerOrRle <- setAtomicRleUnion("integer")
.characterOrRle <- setAtomicRleUnion("character")
.factorOrRle <- setAtomicRleUnion("factor")

setClass("VRanges",
         representation(ref = "character", # or XStringSet?
                        alt = .characterOrRle,
                        totalDepth = .integerOrRle,
                        refDepth = .integerOrRle,
                        altDepth = .integerOrRle,
                        sampleNames = .factorOrRle,
                        softFilterMatrix = "matrix",
                        hardFilters = "FilterRules"),
         contains = "GRanges",
         validity = .valid.VRanges)

### -------------------------------------------------------------------------
### VRangesList
###

setClass("VRangesList", representation("VIRTUAL"),
         prototype = prototype(elementType = "VRanges"),
         contains = "List")

setClass("SimpleVRangesList",
         contains = c("VRangesList", "SimpleGenomicRangesList"))

setClass("CompressedVRangesList",
         representation(elementMetadata = "DataFrame"),
         prototype = prototype(unlistData = new("VRanges")),
         contains = c("VRangesList", "GRangesList"))