-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathread_h5ad_helpers.R
More file actions
491 lines (435 loc) · 12.3 KB
/
read_h5ad_helpers.R
File metadata and controls
491 lines (435 loc) · 12.3 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
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
#' Read H5AD encoding
#'
#' Read the encoding and version of an element in a H5AD file
#'
#' @param file Path to a H5AD file or an open H5AD handle
#' @param name Name of the element within the H5AD file
#'
#' @return A named list with names type and version
#'
#' @noRd
read_h5ad_encoding <- function(file, name) {
tryCatch(
{
attrs <- rhdf5::h5readAttributes(file, name)
list(
type = attrs[["encoding-type"]],
version = attrs[["encoding-version"]]
)
},
error = function(e) {
path <- if (is.character(file)) file else rhdf5::H5Fget_name(file) # nolint object_usage_linter
cli_abort(
"Encoding attributes not found for element {.val {name}} in {.path {path}}"
)
}
)
}
#' Read H5AD element
#'
#' Read an element from a H5AD file
#'
#' @param file Path to a H5AD file or an open H5AD handle
#' @param name Name of the element within the H5AD file
#' @param type The encoding type of the element to read
#' @param version The encoding version of the element to read
#' @param stop_on_error Whether to stop on error or generate a warning instead
#' @param ... Extra arguments passed to individual reading functions
#'
#' @details
#' Encoding is automatically determined from the element using
#' `read_h5ad_encoding` and used to select the appropriate reading function.
#'
#' @return Value depending on the encoding
#'
#' @noRd
read_h5ad_element <- function(
file,
name,
type = NULL,
version = NULL,
stop_on_error = FALSE,
...
) {
if (!hdf5_path_exists(file, name)) {
return(NULL)
}
if (is.null(type)) {
encoding_list <- read_h5ad_encoding(file, name)
type <- encoding_list$type
version <- encoding_list$version
}
read_fun <- switch(
type,
"null" = read_h5ad_null,
"array" = read_h5ad_dense_array,
"rec-array" = read_h5ad_rec_array,
"csr_matrix" = read_h5ad_csr_matrix,
"csc_matrix" = read_h5ad_csc_matrix,
"dataframe" = read_h5ad_data_frame,
"dict" = read_h5ad_mapping,
"string" = read_h5ad_string_scalar,
"numeric-scalar" = read_h5ad_numeric_scalar,
"categorical" = read_h5ad_categorical,
"string-array" = read_h5ad_string_array,
"nullable-integer" = read_h5ad_nullable_integer,
"nullable-boolean" = read_h5ad_nullable_boolean,
cli_abort(
"No function for reading H5AD encoding {.cls {type}} for element {.val {name}}"
)
)
tryCatch(
{
read_fun(file = file, name = name, version = version, ...)
},
error = function(e) {
msg <- cli::cli_fmt(cli::cli_bullets(c(
paste0("Error reading element {.field {name}} of type {.cls {type}}"),
"i" = conditionMessage(e)
)))
if (stop_on_error) {
cli_abort(msg)
} else {
cli_warn(msg)
NULL
}
}
)
}
#' Read H5AD null
#'
#' Read a null value from an H5AD file
#'
#' @param file Path to a H5AD file or an open H5AD handle
#' @param name Name of the element within the H5AD file
#' @param version Encoding version of the element to read
#'
#' @return `NULL`
#' @noRd
read_h5ad_null <- function(file, name, version = "0.1.0") {
version <- match.arg(version)
NULL
}
#' Read H5AD dense array
#'
#' Read a dense array from an H5AD file
#'
#' @param file Path to a H5AD file or an open H5AD handle
#' @param name Name of the element within the H5AD file
#' @param version Encoding version of the element to read
#'
#' @return a matrix or a vector if 1D
#'
#' @noRd
read_h5ad_dense_array <- function(file, name, version = "0.2.0") {
version <- match.arg(version)
data <- rhdf5::h5read(file, name, native = FALSE)
# If the array is 1D, explicitly add a dimension
if (is.null(dim(data))) {
data <- as.vector(data)
dim(data) <- length(data)
}
# Transpose the matrix if need be
if (is.matrix(data)) {
data <- t(data)
} else if (is.array(data) && length(dim(data)) > 1) {
data <- aperm(data)
}
# Reverse {rhdf5} coercion to factors
if (is.factor(data) && all(levels(data) %in% c("TRUE", "FALSE"))) {
dims <- dim(data)
data <- as.logical(data)
dim(data) <- dims
}
data
}
read_h5ad_csr_matrix <- function(file, name, version) {
read_h5ad_sparse_array(
file = file,
name = name,
version = version,
type = "csr_matrix"
)
}
read_h5ad_csc_matrix <- function(file, name, version) {
read_h5ad_sparse_array(
file = file,
name = name,
version = version,
type = "csc_matrix"
)
}
#' Read H5AD sparse array
#'
#' Read a sparse array from an H5AD file
#'
#' @param file Path to a H5AD file or an open H5AD handle
#' @param name Name of the element within the H5AD file
#' @param version Encoding version of the element to read
#' @param type Type of the sparse matrix, either "csr_matrix" or "csc_matrix"
#'
#' @return a sparse matrix/DelayedArray???, or a vector if 1D
#' @importFrom Matrix sparseMatrix
#'
#' @noRd
read_h5ad_sparse_array <- function(
file,
name,
version = "0.1.0",
type = c("csr_matrix", "csc_matrix")
) {
version <- match.arg(version)
type <- match.arg(type)
h5group <- rhdf5::H5Gopen(file, name)
on.exit(rhdf5::H5Gclose(h5group), add = TRUE)
attrs <- rhdf5::h5readAttributes(file, name, native = FALSE)
data <- as.vector(h5group$data)
indices <- as.vector(h5group$indices)
indptr <- as.vector(h5group$indptr)
shape <- as.vector(attrs[["shape"]])
if (type == "csc_matrix") {
mtx <- Matrix::sparseMatrix(
i = indices,
p = indptr,
x = data,
dims = shape,
repr = "C",
index1 = FALSE
)
} else if (type == "csr_matrix") {
mtx <- Matrix::sparseMatrix(
j = indices,
p = indptr,
x = data,
dims = shape,
repr = "R",
index1 = FALSE
)
}
mtx
}
#' Read H5AD recarray
#'
#' Read a recarray from an H5AD file
#'
#' @param file Path to a H5AD file or an open H5AD handle
#' @param name Name of the element within the H5AD file
#' @param version Encoding version of the element to read
#'
#' @details
#' A "record array" (recarray) is a Python NumPy array type that contains
#' "fields" that can be indexed using attributes (similar to columns in a
#' spreadsheet). See https://numpy.org/doc/stable/reference/generated/numpy.recarray.html
#' for details.
#'
#' They are used by **scanpy** to score marker gene testing results.
#'
#' @return a named list of 1D arrays
#'
#' @noRd
read_h5ad_rec_array <- function(file, name, version = "0.2.0") {
version <- match.arg(version)
rhdf5::h5read(file, name, native = FALSE, compoundAsDataFrame = FALSE) |>
lapply(as.vector)
}
#' Read H5AD nullable boolean
#'
#' Read a nullable boolean from an H5AD file
#'
#' @param file Path to a H5AD file or an open H5AD handle
#' @param name Name of the element within the H5AD file
#' @param version Encoding version of the element to read
#'
#' @return a boolean vector
#'
#' @noRd
read_h5ad_nullable_boolean <- function(file, name, version = "0.1.0") {
as.logical(read_h5ad_nullable(file, name, version))
}
#' Read H5AD nullable integer
#'
#' Read a nullable integer from an H5AD file
#'
#' @param file Path to a H5AD file or an open H5AD handle
#' @param name Name of the element within the H5AD file
#' @param version Encoding version of the element to read
#'
#' @return an integer vector
#'
#' @noRd
read_h5ad_nullable_integer <- function(file, name, version = "0.1.0") {
as.integer(read_h5ad_nullable(file, name, version))
}
#' Read H5AD nullable
#'
#' Read a nullable vector (boolean or integer) from an H5AD file
#'
#' @param file Path to a H5AD file or an open H5AD handle
#' @param name Name of the element within the H5AD file
#' @param version Encoding version of the element to read
#'
#' @return a nullable vector
#'
#' @noRd
read_h5ad_nullable <- function(file, name, version = "0.1.0") {
version <- match.arg(version)
h5group <- rhdf5::H5Gopen(file, name)
on.exit(rhdf5::H5Gclose(h5group), add = TRUE)
data <- as.vector(h5group$values)
mask <- as.logical(h5group$mask)
data[mask] <- NA
data
}
#' Read H5AD string array
#'
#' Read a string array from an H5AD file
#'
#' @param file Path to a H5AD file or an open H5AD handle
#' @param name Name of the element within the H5AD file
#' @param version Encoding version of the element to read
#'
#' @return a character vector/matrix
#'
#' @noRd
read_h5ad_string_array <- function(file, name, version = "0.2.0") {
version <- match.arg(version)
data <- rhdf5::h5read(file, name, native = FALSE)
if (is.null(dim(data)) || length(dim(data)) == 1) {
data <- as.vector(data)
dim(data) <- length(data)
}
# transpose the matrix if need be
if (is.matrix(data)) {
data <- t(data)
} else if (is.array(data) && length(dim(data)) > 1) {
data <- aperm(data)
}
data
}
#' Read H5AD categorical
#'
#' Read a categorical from an H5AD file
#'
#' @param file Path to a H5AD file or an open H5AD handle
#' @param name Name of the element within the H5AD file
#' @param version Encoding version of the element to read
#'
#' @return a factor
#'
#' @noRd
read_h5ad_categorical <- function(file, name, version = "0.2.0") {
version <- match.arg(version)
h5group <- rhdf5::H5Gopen(file, name)
on.exit(rhdf5::H5Gclose(h5group), add = TRUE)
# Get codes and convert to 1-based indexing
codes <- h5group$codes + 1L
# Set missing values
codes[codes == 0L] <- NA_integer_
levels <- h5group$categories
attrs <- rhdf5::h5readAttributes(file, name, native = FALSE)
ordered <- attrs[["ordered"]]
factor(levels[codes], levels = levels, ordered = ordered)
}
#' Read H5AD string scalar
#'
#' Read a string scalar from an H5AD file
#'
#' @param file Path to a H5AD file or an open H5AD handle
#' @param name Name of the element within the H5AD file
#' @param version Encoding version of the element to read
#'
#' @return a character vector of length 1
#'
#' @noRd
read_h5ad_string_scalar <- function(file, name, version = "0.2.0") {
version <- match.arg(version)
rhdf5::h5read(file, name, native = FALSE)
}
#' Read H5AD numeric scalar
#'
#' Read a numeric scalar from an H5AD file
#'
#' @param file Path to a H5AD file or an open H5AD handle
#' @param name Name of the element within the H5AD file
#' @param version Encoding version of the element to read
#'
#' @return a numeric vector of length 1
#'
#' @noRd
read_h5ad_numeric_scalar <- function(file, name, version = "0.2.0") {
version <- match.arg(version)
value <- rhdf5::h5read(file, name, native = FALSE)
if (is.factor(value) && all(levels(value) %in% c("TRUE", "FALSE"))) {
value <- as.logical(value)
}
value
}
#' Read H5AD mapping
#'
#' Read a mapping from an H5AD file
#'
#' @param file Path to a H5AD file or an open H5AD handle
#' @param name Name of the element within the H5AD file
#' @param version Encoding version of the element to read
#'
#' @return a named list
#'
#' @noRd
read_h5ad_mapping <- function(file, name, version = "0.1.0") {
version <- match.arg(version)
h5group <- rhdf5::H5Gopen(file, name)
on.exit(rhdf5::H5Gclose(h5group), add = TRUE)
items <- rhdf5::h5ls(h5group, recursive = FALSE)$name
read_h5ad_collection(file, name, items)
}
#' Read H5AD data frame
#'
#' Read a data frame from an H5AD file
#'
#' @param file Path to a H5AD file or an open H5AD handle
#' @param name Name of the element within the H5AD file
#' @param version Encoding version of the element to read
#'
#' @return a data.frame
#'
#' @noRd
read_h5ad_data_frame <- function(file, name, version = "0.2.0") {
version <- match.arg(version)
attrs <- rhdf5::h5readAttributes(file, name, native = FALSE)
index_name <- attrs[["_index"]]
column_order <- attrs[["column-order"]]
index <- read_h5ad_element(file, file.path(name, index_name))
data <- read_h5ad_collection(file, name, column_order)
as.data.frame(
row.names = index,
data,
check.names = FALSE,
fix.empty.names = FALSE
)
}
#' Read multiple H5AD datatypes
#'
#' @param file Path to a H5AD file or an open H5AD handle
#' @param name Name of the element within the H5AD file
#' @param item_names Vector of item names (in order)
#'
#' @return a named list
#'
#' @noRd
read_h5ad_collection <- function(file, name, item_names) {
items <- lapply(
item_names,
function(item_name) {
new_name <- paste0(name, "/", item_name)
encoding <- read_h5ad_encoding(file, new_name)
read_h5ad_element(
file = file,
name = new_name,
type = encoding$type,
version = encoding$version
)
}
)
names(items) <- item_names
items
}