forked from scverse/anndataR
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnnDataView.R
More file actions
402 lines (355 loc) · 10.7 KB
/
AnnDataView.R
File metadata and controls
402 lines (355 loc) · 10.7 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
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
#' @title A View of an AnnData Object
#'
#' @description A lazy view of an AnnData object that allows applying subsetting operations
#' without immediately executing them. Subsetting is applied when converting to
#' a concrete AnnData implementation (InMemoryAnnData, HDF5AnnData) or other
#' formats (SingleCellExperiment, Seurat).
#'
#' @return A `AnnDataView` object
#'
#' @seealso [AnnData-usage] for details on creating and using `AnnData` objects
#'
#' @family AnnData classes
#'
#' @examples
#' # Create a base AnnData object
#' ad <- AnnData(
#' X = matrix(1:15, 3L, 5L),
#' obs = data.frame(row.names = LETTERS[1:3], cell_type = c("A", "B", "A")),
#' var = data.frame(row.names = letters[1:5], gene_type = c("X", "Y", "X", "Y", "Z"))
#' )
#'
#' # Create a view with lazy subsetting using S3 [ method
#' view <- ad[ad$obs$cell_type == "A", ad$var$gene_type %in% c("X", "Y")]
#'
#' # Apply subsetting by converting to a concrete implementation
#' result <- view$as_InMemoryAnnData()
#'
#' @export
AnnDataView <- R6::R6Class(
"AnnDataView",
inherit = AbstractAnnData,
private = list(
.base_adata = NULL,
.obs_subset = NULL,
.var_subset = NULL,
# Apply subsetting to matrices/data frames with explicit dimension control
.apply_subset = function(
x,
obs_on_rows = FALSE,
var_on_rows = FALSE,
obs_on_cols = FALSE,
var_on_cols = FALSE
) {
if (is.null(x)) {
return(x)
}
# Check if x is a subsettable matrix-like object (data.frame, matrix, or Matrix)
if (is.data.frame(x) || is.matrix(x) || inherits(x, "Matrix")) {
result <- x
# Apply obs subsetting to rows if requested
if (obs_on_rows && !is.null(private$.obs_subset)) {
result <- result[private$.obs_subset, , drop = FALSE]
}
# Apply var subsetting to rows if requested
if (var_on_rows && !is.null(private$.var_subset)) {
result <- result[private$.var_subset, , drop = FALSE]
}
# Apply obs subsetting to columns if requested
if (obs_on_cols && !is.null(private$.obs_subset)) {
result <- result[, private$.obs_subset, drop = FALSE]
}
# Apply var subsetting to columns if requested
if (var_on_cols && !is.null(private$.var_subset)) {
result <- result[, private$.var_subset, drop = FALSE]
}
result
} else {
x
}
},
# Apply subsetting to vectors
.apply_vector_subset = function(x, use_obs = FALSE, use_var = FALSE) {
if (is.null(x) || !is.vector(x)) {
return(x)
}
if (use_obs && !is.null(private$.obs_subset)) {
return(x[private$.obs_subset])
}
if (use_var && !is.null(private$.var_subset)) {
return(x[private$.var_subset])
}
x
},
# Helper to show error for setter operations
.abort_setter = function(field_name) {
cli_abort(
paste0(
"Cannot set {.field {field_name}} on an {.cls AnnDataView} object. Convert to a concrete implementation ",
"first using any of the {.code as_*()} methods ",
"(e.g., {.code adata$as_InMemoryAnnData()}, {.code adata$as_HDF5AnnData()})."
)
)
},
# Override class name to show "View of BaseClass"
.class_name = function() {
base_class <- class(private$.base_adata)[1]
paste("View of", base_class)
}
),
active = list(
#' @field X See [AnnData-usage]
X = function(value) {
if (!missing(value)) {
private$.abort_setter("X")
}
private$.apply_subset(
private$.base_adata$X,
obs_on_rows = TRUE,
var_on_cols = TRUE
)
},
#' @field layers See [AnnData-usage]
layers = function(value) {
if (!missing(value)) {
private$.abort_setter("layers")
}
layers <- private$.base_adata$layers
if (is.null(layers)) {
return(NULL)
}
# Apply subsetting to each layer (obs on rows, var on columns)
lapply(layers, function(x) {
private$.apply_subset(x, obs_on_rows = TRUE, var_on_cols = TRUE)
})
},
#' @field obs See [AnnData-usage]
obs = function(value) {
if (!missing(value)) {
private$.abort_setter("obs")
}
private$.apply_subset(private$.base_adata$obs, obs_on_rows = TRUE)
},
#' @field var See [AnnData-usage]
var = function(value) {
if (!missing(value)) {
private$.abort_setter("var")
}
private$.apply_subset(private$.base_adata$var, var_on_rows = TRUE)
},
#' @field obs_names See [AnnData-usage]
obs_names = function(value) {
if (!missing(value)) {
private$.abort_setter("obs_names")
}
private$.apply_vector_subset(
private$.base_adata$obs_names,
use_obs = TRUE
)
},
#' @field var_names See [AnnData-usage]
var_names = function(value) {
if (!missing(value)) {
private$.abort_setter("var_names")
}
private$.apply_vector_subset(
private$.base_adata$var_names,
use_var = TRUE
)
},
#' @field obsm See [AnnData-usage]
obsm = function(value) {
if (!missing(value)) {
private$.abort_setter("obsm")
}
obsm <- private$.base_adata$obsm
if (is.null(obsm)) {
return(NULL)
}
# Apply obs subsetting to each matrix (filter rows only)
lapply(obsm, function(x) {
private$.apply_subset(x, obs_on_rows = TRUE)
})
},
#' @field varm See [AnnData-usage]
varm = function(value) {
if (!missing(value)) {
private$.abort_setter("varm")
}
varm <- private$.base_adata$varm
if (is.null(varm)) {
return(NULL)
}
# Apply var subsetting to each matrix (filter rows only)
lapply(varm, function(x) {
private$.apply_subset(x, var_on_rows = TRUE)
})
},
#' @field obsp See [AnnData-usage]
obsp = function(value) {
if (!missing(value)) {
private$.abort_setter("obsp")
}
obsp <- private$.base_adata$obsp
if (is.null(obsp)) {
return(NULL)
}
# Apply obs subsetting to each matrix (both rows and columns)
lapply(obsp, function(x) {
private$.apply_subset(x, obs_on_rows = TRUE, obs_on_cols = TRUE)
})
},
#' @field varp See [AnnData-usage]
varp = function(value) {
if (!missing(value)) {
private$.abort_setter("varp")
}
varp <- private$.base_adata$varp
if (is.null(varp)) {
return(NULL)
}
# Apply var subsetting to each matrix (both rows and columns)
lapply(varp, function(x) {
private$.apply_subset(x, var_on_rows = TRUE, var_on_cols = TRUE)
})
},
#' @field uns See [AnnData-usage]
uns = function(value) {
if (!missing(value)) {
private$.abort_setter("uns")
}
# uns is not affected by subsetting
private$.base_adata$uns
}
),
public = list(
#' @description
#' Create a new AnnDataView object
#'
#' @param base_adata An existing AnnData object to create a view of
#' @param i Optional initial obs subset (logical, integer, or character vector)
#' @param j Optional initial var subset (logical, integer, or character vector)
#'
#' @return A new `AnnDataView` object
initialize = function(base_adata, i, j) {
if (!inherits(base_adata, "AbstractAnnData")) {
cli_abort("{.arg base_adata} must be an {.cls AbstractAnnData} object")
}
private$.base_adata <- base_adata
private$.obs_subset <- convert_to_indices(
i,
base_adata$n_obs(),
base_adata$obs_names,
"observations"
)
private$.var_subset <- convert_to_indices(
j,
base_adata$n_vars(),
base_adata$var_names,
"variables"
)
invisible(self)
},
#' Subset the AnnDataView
#'
#' @param i Row indices (observations). Can be numeric, logical, or character.
#' @param j Column indices (variables). Can be numeric, logical, or character.
#'
#' @return A new `AnnDataView` object
subset = function(i, j) {
if (missing(i)) {
i <- NULL
}
if (missing(j)) {
j <- NULL
}
# processing observation indices
processed_i <- convert_to_indices(
i,
self$n_obs(),
self$obs_names,
"observations"
)
new_i <- if (is.null(processed_i)) {
private$.obs_subset
} else if (is.null(private$.obs_subset)) {
processed_i
} else {
private$.obs_subset[processed_i]
}
# processing variable indices
processed_j <- convert_to_indices(
j,
self$n_vars(),
self$var_names,
"variables"
)
new_j <- if (is.null(processed_j)) {
private$.var_subset
} else if (is.null(private$.var_subset)) {
processed_j
} else {
private$.var_subset[processed_j]
}
AnnDataView$new(private$.base_adata, new_i, new_j)
}
)
)
#' Convert various subset types to integer indices
#'
#' @param subset The subset condition (logical, integer, or character vector)
#' @param max_length The maximum allowed length/index
#' @param names_vector The names to match against for character subsetting
#' @param context_name Name for error messages ("observations" or "variables")
#'
#' @return Integer vector of indices, or NULL if subset is NULL
#' @keywords internal
#' @noRd
convert_to_indices <- function(
subset,
max_length,
names_vector,
context_name = "items"
) {
if (missing(subset) || is.null(subset)) {
return(NULL)
}
if (is.logical(subset)) {
if (length(subset) != max_length) {
cli_abort(
"Logical subset of {context_name} must have length {max_length}"
)
}
which(subset)
} else if (is.numeric(subset)) {
subset <- as.integer(subset)
if (any(subset < 1 | subset > max_length)) {
cli_abort(
"Integer indices for {context_name} must be between 1 and {max_length}"
)
}
subset
} else if (is.character(subset)) {
if (is.null(names_vector)) {
cli_abort(c(
"Cannot use character names to subset {context_name}",
"i" = "The {context_name} do not have names ({.field obs_names}/{.field var_names} are NULL)",
"i" = "Use integer indices instead, or set names first"
))
}
indices <- match(subset, names_vector)
if (anyNA(indices)) {
# nolint start: object_usage_linter
missing_names <- subset[is.na(indices)]
# nolint end: object_usage_linter
cli_abort(
"Names of {context_name} not found: {paste(missing_names, collapse = ', ')}"
)
}
indices
} else {
cli_abort(
"Subset of {context_name} must be logical, integer, or character vector"
)
}
}