File: NaArray-class.R

package info (click to toggle)
r-bioc-sparsearray 1.6.2%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,768 kB
  • sloc: ansic: 16,138; makefile: 2
file content (321 lines) | stat: -rw-r--r-- 9,445 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
### =========================================================================
### NaArray objects
### -------------------------------------------------------------------------
###
### Like SVT_SparseArray objects but the background value is NA instead of
### zero.
###

setClass("NaArray",
    contains="Array",
    representation(
        dim="integer",
        dimnames="list",
        type="character",
        NaSVT="NULL_OR_list",  # NULL or na-Sparse Vector Tree (NaSVT)
        .svt_version="integer"
    ),
    prototype(
        dim=0L,
        dimnames=list(NULL),
        type="logical",
        .svt_version=SVT_VERSION
    )
)

.SUPPORTED_NAARRAY_TYPES <-
    c("integer", "logical", "double", "complex", "character")

.validate_NaArray <- function(x)
{
    if (!isSingleString(x@type))
        return("'type' slot must be a single string")
    if (!(x@type %in% .SUPPORTED_NAARRAY_TYPES)) {
        in1string <- paste(paste0('"', .SUPPORTED_NAARRAY_TYPES, '"'),
                           collapse=", ")
        return(paste0("'type' slot must be one of ", in1string))
    }
    TRUE
}
setValidity2("NaArray", .validate_NaArray)

### Extending RectangularData gives us a few things for free (e.g. validity
### method for RectangularData objects, head(), tail(), etc...). Note
### that even though NaMatrix already extends Array (via NaArray),
### we need to make it a *direct* child of Array, and to list Array *before*
### RectangularData in the 'contains' field below. This will ensure that
### method dispatch will always choose the method for Array in case a generic
### has methods defined for both, Array and RectangularData.
### Note that the fact that we need this "hack" is a hint that we could
### achieve a cleaner class hierarchy by inserting a Matrix class in it.
### Matrix would contain Array and RectangularData (in that order). Then
### NaMatrix would contain NaArray and Matrix (in that order).
### Unfortunately the Matrix package already defines a Matrix class so
### we would need to use a different name.
setClass("NaMatrix",
    contains=c("NaArray", "Array", "RectangularData"),
    prototype=prototype(
        dim=c(0L, 0L),
        dimnames=list(NULL, NULL)
    )
)

.validate_NaMatrix <- function(x)
{
    if (length(x@dim) != 2L)
        return("'dim' slot must be an integer vector of length 2")
    TRUE
}
setValidity2("NaMatrix", .validate_NaMatrix)


### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### Going back and forth between NaArray and NaMatrix
###

### --- From NaArray to NaMatrix ---

setAs("NaArray", "NaMatrix",
    function(from) new("NaMatrix", from)
)

### --- From NaMatrix to NaArray ---

setAs("NaMatrix", "NaArray", function(from) from)  # no-op

setMethod("coerce", c("NaMatrix", "NaArray"),
    function(from, to, strict=TRUE) from  # no-op
)


### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### dim(), dimnames(), and `dimnames<-`()
###

setMethod("dim", "NaArray", function(x) x@dim)

setMethod("dimnames", "NaArray",
    function(x) S4Arrays:::simplify_NULL_dimnames(x@dimnames)
)

setReplaceMethod("dimnames", "NaArray",
    function(x, value)
    {
        x@dimnames <- S4Arrays:::normarg_dimnames(value, dim(x))
        x
    }
)


### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### type() getter and setter
###

setMethod("type", "NaArray", function(x) x@type)

.normarg_NaArray_type <- function(type, what="'type'")
{
    if (!isSingleString(type))
        stop(wmsg(what, " must be a single string"))
    if (type == "numeric")
        return("double")
    if (!(type %in% .SUPPORTED_NAARRAY_TYPES)) {
        in1string <- paste(paste0('"', .SUPPORTED_NAARRAY_TYPES, '"'),
                           collapse=", ")
        stop(wmsg(what, " must be one of ", in1string))
    }
    type
}

.set_NaArray_type <- function(x, value)
{
    stopifnot(is(x, "NaArray"))
    check_svt_version(x)

    value <- .normarg_NaArray_type(value, "the supplied type")
    x_type <- type(x)
    if (value == x_type)
        return(x)

    new_NaSVT <- SparseArray.Call("C_set_SVT_type",
                                  x@dim, x@type, x@NaSVT, TRUE, value)
    BiocGenerics:::replaceSlots(x, type=value, NaSVT=new_NaSVT, check=FALSE)
}

setReplaceMethod("type", "NaArray", .set_NaArray_type)


### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### is_nonna(), nnacount(), nnawhich(), nnavals(), `nnavals<-`()
###

### Returns a "logical" **SVT_SparseArray** object!
.is_nonna_NaSVT <- function(x)
{
    stopifnot(is(x, "NaArray"))
    check_svt_version(x)
    ans_SVT <- SparseArray.Call("C_is_nonzero_SVT", x@dim, x@NaSVT)
    new_SVT_SparseArray(x@dim, x@dimnames, "logical", ans_SVT, check=FALSE)
}

setMethod("is_nonna", "NaArray", .is_nonna_NaSVT)

### Note that like for the length of atomic vectors in base R, the "non-NA
### count" will be returned as a double if it's > .Machine$integer.max
.nnacount_NaSVT <- function(x)
{
    stopifnot(is(x, "NaArray"))
    check_svt_version(x)
    SparseArray.Call("C_nzcount_SVT", x@dim, x@NaSVT)
}
setMethod("nnacount", "NaArray", .nnacount_NaSVT)

### Returns an integer vector of length nnacount(x) if 'arr.ind=FALSE', or
### a matrix with nnacount(x) rows if 'arr.ind=TRUE'.
.nnawhich_NaSVT <- function(x, arr.ind=FALSE)
{
    stopifnot(is(x, "NaArray"))
    check_svt_version(x)
    if (!isTRUEorFALSE(arr.ind))
        stop(wmsg("'arr.ind' must be TRUE or FALSE"))
    SparseArray.Call("C_nzwhich_SVT", x@dim, x@NaSVT, arr.ind)
}
setMethod("nnawhich", "NaArray", .nnawhich_NaSVT)

### TODO: Implement optimized nnavals() and `nnavals<-`() methods for
### NaArray objects.


### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### Low-level constructor
###

new_NaArray <- function(dim, dimnames=NULL,
                        type="logical", NaSVT=NULL, check=TRUE)
{
    stopifnot(is.integer(dim))
    if (length(dim) == 2L) {
        ans_class <- "NaMatrix"
    } else {
        ans_class <- "NaArray"
    }
    dimnames <- S4Arrays:::normarg_dimnames(dimnames, dim)
    new2(ans_class, dim=dim, dimnames=dimnames,
                    type=type, NaSVT=NaSVT, check=check)
}


### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### Going back and forth between NaArray objects and ordinary arrays
###

.from_NaArray_to_array <- function(from)
{
    stopifnot(is(from, "NaArray"))
    check_svt_version(from)
    SparseArray.Call("C_from_SVT_SparseArray_to_Rarray",
                     from@dim, dimnames(from), from@type, from@NaSVT, TRUE)
}

### S3/S4 combo for as.array.NaArray
as.array.NaArray <- function(x, ...) .from_NaArray_to_array(x)
setMethod("as.array", "NaArray", as.array.NaArray)

.build_NaArray_from_array <- function(x, dimnames=NULL, type=NA)
{
    stopifnot(is.array(x))
    if (is.null(dimnames)) {
        ans_dimnames <- dimnames(x)
    } else {
        ans_dimnames <- S4Arrays:::normarg_dimnames(dimnames, dim(x))
    }
    if (identical(type, NA))
        type <- type(x)
    ans_NaSVT <- SparseArray.Call("C_build_SVT_from_Rarray", x, type, TRUE)
    new_NaArray(dim(x), ans_dimnames, type, ans_NaSVT, check=FALSE)
}

setAs("array", "NaArray",
    function(from) .build_NaArray_from_array(from)
)
setAs("matrix", "NaMatrix",
    function(from) .build_NaArray_from_array(from)
)


### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### NaArray() constructor
###

.new_empty_NaArray <- function(type=NA)
{
    if (identical(type, NA))
        type <- "logical"
    new2("NaArray", type=type, check=FALSE)
}

.NaArray <- function(x, dimnames=NULL, type=NA)
{
    if (is.array(x))
        return(.build_NaArray_from_array(x, dimnames=dimnames, type=type))

    ans <- as(x, "NaArray")
    ans <- S4Arrays:::set_dimnames(ans, dimnames)
    if (!identical(type, NA))
        type(ans) <- type
    ans
}

NaArray <- function(x, dim=NULL, dimnames=NULL, type=NA)
{
    if (!identical(type, NA))
        type <- .normarg_NaArray_type(type, "the requested type")

    if (is.null(dim)) {
        if (missing(x))
            return(.new_empty_NaArray(type))
        return(.NaArray(x, dimnames=dimnames, type=type))
    }

    dim <- S4Arrays:::normarg_dim(dim)
    ans <- new_NaArray(dim, dimnames=dimnames, check=FALSE)
    if (!missing(x)) {
        nnaidx <- nnawhich(x)
        ans[nnaidx] <- as.vector(x[nnaidx])
    }
    if (!identical(type, NA))
        type(ans) <- type
    ans
}


### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### show()
###

.show_nnacount <- function(x)
{
    x_nnacount <- nnacount(x)
    x_density <- x_nnacount / length(x)
    sprintf("[nnacount=%s (%s%%)]", format(x_nnacount),
                                    signif(100 * x_density, digits=2))
}

setMethod("show", "NaArray",
    function(object)
    {
        ## Only reason we print the headline in 2 steps is because we
        ## want to make sure to print at least something (part1) even
        ## when printing part2 is going to fail. This will happen for
        ## example if the call to nnacount() in .show_nnacount() fails.
        cat(show_headline_part1(object))
        cat(.show_nnacount(object))
        if (any(dim(object) == 0L)) {
            cat("\n")
            return()
        }
        cat(":\n", sep="")
        S4Arrays:::print_some_array_elements(object)
    }
)