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 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
|
### =========================================================================
### H5SparseMatrixSeed objects
### -------------------------------------------------------------------------
setClass("H5SparseMatrixSeed",
contains=c("Array", "OutOfMemoryObject"),
representation(
"VIRTUAL",
## --------------------- user supplied slots ---------------------
## Absolute path to the HDF5 file so the object won't break when
## the user changes the working directory (e.g. with 'setwd()').
filepath="character",
## Name of the group in the HDF5 file where the sparse matrix is
## stored.
group="character",
## If 'paste0(group, "/data")' is a group, name of a dataset in
## that group. Otherwise, must be set to NULL.
subdata="character_OR_NULL",
## ---------------- automatically populated slots ----------------
dim="integer",
## Can't use an IRanges object for this at the moment because IRanges
## objects don't support large integer start/end values yet.
indptr_ranges="data.frame",
## ------------- populated by specialized subclasses -------------
dimnames="list"
),
prototype(
dimnames=list(NULL, NULL)
)
)
.get_data_name <- function(subdata, group=NULL)
{
name <- "data"
if (!is.null(subdata))
name <- paste0(name, "/", subdata)
if (!is.null(group))
name <- paste0(group, "/", name)
name
}
setClass("CSC_H5SparseMatrixSeed", contains="H5SparseMatrixSeed")
setClass("CSR_H5SparseMatrixSeed", contains="H5SparseMatrixSeed")
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### Transposition
###
### S3/S4 combo for t.CSC_H5SparseMatrixSeed
t.CSC_H5SparseMatrixSeed <- function(x)
{
x@dim <- rev(x@dim)
x@dimnames <- rev(x@dimnames)
class(x) <- class(new("CSR_H5SparseMatrixSeed"))
x
}
setMethod("t", "CSC_H5SparseMatrixSeed", t.CSC_H5SparseMatrixSeed)
### S3/S4 combo for t.CSR_H5SparseMatrixSeed
t.CSR_H5SparseMatrixSeed <- function(x)
{
x@dim <- rev(x@dim)
x@dimnames <- rev(x@dimnames)
class(x) <- class(new("CSC_H5SparseMatrixSeed"))
x
}
setMethod("t", "CSR_H5SparseMatrixSeed", t.CSR_H5SparseMatrixSeed)
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### path() getter/setter
###
### Does NOT access the file.
setMethod("path", "H5SparseMatrixSeed", function(object) object@filepath)
### Just a placeholder for now. Doesn't actually allow changing the path of
### the object yet.
setReplaceMethod("path", "H5SparseMatrixSeed",
function(object, value)
{
new_filepath <- normarg_h5_filepath(value, what1="the supplied path",
what2="the sparse matrix")
old_filepath <- path(object)
if (new_filepath != old_filepath)
stop(wmsg("changing the path of a ", class(object), " object ",
"is not supported yet"))
object
}
)
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### dim() and dimnames() getters
###
### They access the slot, not the file.
###
setMethod("dim", "H5SparseMatrixSeed", function(x) x@dim)
setMethod("dimnames", "H5SparseMatrixSeed",
function(x) S4Arrays:::simplify_NULL_dimnames(x@dimnames)
)
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### chunkdim() getter
###
### Does NOT access the file.
setMethod("chunkdim", "CSC_H5SparseMatrixSeed",
function(x) c(nrow(x), min(ncol(x), 1L))
)
setMethod("chunkdim", "CSR_H5SparseMatrixSeed",
function(x) c(min(nrow(x), 1L), ncol(x))
)
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### is_sparse() and nzcount() methods
###
### This is about **structural** sparsity, not about quantitative sparsity
### measured by sparsity().
setMethod("is_sparse", "H5SparseMatrixSeed", function(x) TRUE)
setMethod("nzcount", "H5SparseMatrixSeed",
function(x) h5length(x@filepath, .get_data_name(x@subdata, x@group))
)
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### Low-level internal h5sparse data readers
###
### All the h5sparse components are monodimensional.
read_h5sparse_component <- function(filepath, group, name,
start=NULL, count=NULL, as.integer=FALSE)
{
name <- paste0(group, "/", name)
if (!is.null(start))
start <- list(start)
if (!is.null(count))
count <- list(count)
h5mread(filepath, name, starts=start, counts=count,
as.vector=TRUE, as.integer=as.integer)
}
### Returns a numeric vector (integer or double).
.read_h5sparse_dim <- function(filepath, group)
{
if (h5exists(filepath, paste0(group, "/shape"))) {
## 10x format
return(read_h5sparse_component(filepath, group, "shape"))
}
## h5ad format
h5attrs <- h5readAttributes(filepath, group)
shape <- h5attrs$shape
if (is.null(shape))
shape <- h5attrs$h5sparse_shape
if (is.null(shape))
stop(wmsg("Group \"", group, "\" in HDF5 file \"", filepath,"\" ",
"contains no 'shape' dataset and has no 'shape' ",
"or 'h5sparse_shape' attribute. As a consequence, the ",
"dimensions of the sparse matrix can't be determined."))
## We pass 'shape' thru as.vector() to drop its class attribute in case
## it's an array.
rev(as.vector(shape))
}
.read_h5sparse_layout <- function(filepath, group)
{
if (h5exists(filepath, paste0(group, "/shape"))) {
## 10x format
return("csr")
}
## h5ad format
h5attrs <- h5readAttributes(filepath, group)
h5sparse_layout <- h5attrs[["encoding-type"]]
if (is.null(h5sparse_layout))
h5sparse_layout <- h5attrs[["h5sparse_format"]]
if (is.null(h5sparse_layout))
return("csr")
ans <- tolower(substr(h5sparse_layout, 1L, 3L))
if (!(ans %in% c("csr", "csc")))
stop(wmsg("sparse matrix in group \"", group, "\" in HDF5 ",
"file \"", filepath,"\" is stored in unsupported ",
"layout \"", h5sparse_layout, "\""))
ans
}
.read_h5sparse_indptr <- function(filepath, group)
read_h5sparse_component(filepath, group, "indptr")
.read_h5sparse_data <-
function(filepath, group, subdata, start=NULL, count=NULL)
{
name <- .get_data_name(subdata)
read_h5sparse_component(filepath, group, name, start=start, count=count)
}
### The row (or column) indices stored in HDF5 dataset "indices" are 0-based
### and we return them as such.
.read_h5sparse_indices <- function(filepath, group, start=NULL, count=NULL)
read_h5sparse_component(filepath, group, "indices",
start=start, count=count, as.integer=TRUE)
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### Constructor
###
.check_group <- function(filepath, group)
{
if (!h5exists(filepath, group))
stop(wmsg("HDF5 group \"", group, "\" does not exist ",
"in this HDF5 file"))
if (h5isdataset(filepath, group)) {
is_h5ad_X_or_layer <- group == "/X" ||
substr(group, 1L, 8L) == "/layers/"
msg1 <- c("\"", group, "\" is an HDF5 dataset, not an HDF5 group, ",
"so it looks like the matrix that you are trying to ",
"access is not stored in a sparse format. Please ",
"consider using the ")
if (is_h5ad_X_or_layer) {
msg2 <- c("H5ADMatrix() constructor if you are trying ",
"to access the central matrix of an h5ad file. ",
"Otherwise, use the HDF5Array() constructor.")
} else {
msg2 <- "HDF5Array() constructor to access this dataset."
}
stop(wmsg(msg1, msg2))
}
if (!h5isgroup(filepath, group))
stop(wmsg("HDF5 object \"", group, "\" is not a group"))
}
.check_data_and_subdata <- function(filepath, group, subdata)
{
data_fullname <- paste0(group, "/data")
if (!h5exists(filepath, data_fullname))
stop(wmsg("HDF5 object \"", data_fullname, "\" does not ",
"exist in this HDF5 file. Are you sure that HDF5 ",
"group \"", group, "\" contains a sparse matrix ",
"stored in CSR/CSC/Yale layout?"))
if (is.null(subdata)) {
if (h5isgroup(filepath, data_fullname))
stop(wmsg("\"", data_fullname, "\" is an HDF5 group, not an ",
"HDF5 dataset. Please use the 'subdata' argument to ",
"specify the name of the dataset in this group that ",
"contains the matrix data."))
if (!h5isdataset(filepath, data_fullname))
stop(wmsg("HDF5 object \"", data_fullname, "\" is not a dataset."))
} else {
if (!isSingleString(subdata) || subdata == "")
stop(wmsg("'subdata' must be NULL or a single non-empty string"))
if (h5isdataset(filepath, data_fullname))
stop(wmsg("\"", data_fullname, "\" is an HDF5 dataset, not an ",
"HDF5 group. Please note that the 'subdata' argument ",
"can be used only when it's a group."))
if (!h5isgroup(filepath, data_fullname))
stop(wmsg("HDF5 object \"", data_fullname, "\" is not a group."))
subdata_fullname <- .get_data_name(subdata, group)
if (!h5exists(filepath, subdata_fullname))
stop(wmsg("HDF5 object \"", subdata_fullname, "\" does not ",
"exist in this HDF5 file."))
if (!h5isdataset(filepath, subdata_fullname))
stop(wmsg("HDF5 object \"", subdata_fullname, "\" is ",
"not a dataset."))
}
}
.get_sparse_matrix_dim <- function(filepath, group, dim=NULL)
{
if (is.null(dim)) {
dim <- .read_h5sparse_dim(filepath, group)
stopifnot(length(dim) == 2L)
return(dim_as_integer(dim, filepath, group, what="sparse matrix"))
}
## Check user-supplied 'dim'.
if (!is.numeric(dim) || length(dim) != 2L || anyNA(dim))
stop(wmsg("supplied 'dim' must be an integer vector ",
"of length 2 with no NAs"))
if (!is.integer(dim)) {
if (any(dim > .Machine$integer.max))
stop(wmsg("supplied dimensions are too big (all dimensions ",
"must be <= '.Machine$integer.max' (= 2^31 - 1))"))
dim <- as.integer(dim)
}
if (any(dim < 0L))
stop(wmsg("supplied 'dim' cannot contain negative values"))
dim
}
### Must return "CSC" or "CSR".
.get_sparse_matrix_layout <- function(filepath, group, sparse.layout=NULL)
{
if (is.null(sparse.layout)) {
h5sparse_layout <- .read_h5sparse_layout(filepath, group)
## Layout in R will be transposed w.r.t. layout used in h5 file.
ans <- switch(h5sparse_layout, `csr`="CSC", `csc`="CSR",
stop(wmsg("unsupported 'h5sparse_layout': ",
h5sparse_layout)))
return(ans)
}
## Check user-supplied 'sparse.layout'.
if (!isSingleString(sparse.layout))
stop(wmsg("'sparse.layout' must be a single string"))
ans <- toupper(sparse.layout)
if (!(ans %in% c("CSC", "CSR")))
stop(wmsg("'sparse.layout' must be either \"CSC\" or \"CSR\""))
ans
}
### Returns an H5SparseMatrixSeed derivative (can be either a
### CSC_H5SparseMatrixSeed or CSR_H5SparseMatrixSeed object).
H5SparseMatrixSeed <- function(filepath, group, subdata=NULL,
dim=NULL, sparse.layout=NULL)
{
## Check 'filepath', 'group', and 'subdata'.
filepath <- normarg_h5_filepath(filepath, what2="the sparse matrix")
group <- normarg_h5_name(group, what1="'group'",
what2="the name of the group",
what3=" that stores the sparse matrix")
.check_group(filepath, group)
.check_data_and_subdata(filepath, group, subdata)
## Get matrix dimensions.
dim <- .get_sparse_matrix_dim(filepath, group, dim=dim)
## Get sparse layout to use ("CSC" or "CSR").
## Note that R has the notions of rows and columns flipped w.r.t.
## HDF5 so:
## - "compressed sparse row" at the HDF5 level translates
## into "compressed sparse column" at the R level,
## - "compressed sparse column" at the HDF5 level translates
## into "compressed sparse row" at the R level.
layout <- .get_sparse_matrix_layout(filepath, group,
sparse.layout=sparse.layout)
if (layout == "CSC") {
expected_indptr_len <- dim[[2L]] + 1L
ans_class <- "CSC_H5SparseMatrixSeed"
} else {
expected_indptr_len <- dim[[1L]] + 1L
ans_class <- "CSR_H5SparseMatrixSeed"
}
## Get 'indptr_ranges'.
nzcount <- h5length(filepath, .get_data_name(subdata, group))
indices_len <- h5length(filepath, paste0(group, "/indices"))
stopifnot(indices_len == nzcount)
indptr <- .read_h5sparse_indptr(filepath, group)
stopifnot(length(indptr) == expected_indptr_len,
indptr[[1L]] == 0L,
indptr[[length(indptr)]] == nzcount)
indptr_ranges <- data.frame(start=indptr[-length(indptr)] + 1,
width=as.integer(diff(indptr)))
new2(ans_class, filepath=filepath, group=group,
dim=dim, indptr_ranges=indptr_ranges)
}
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### .load_CSC_H5SparseMatrixSeed
###
### Loads CSC_H5SparseMatrixSeed object 'x' into memory as a SVT_SparseMatrix
### object, or selected columns only.
### This is the workhorse behind the extract_sparse_array(), extract_array(),
### and read_block_as_sparse() methods for H5SparseMatrixSeed objects, as
### well as behind coercion from CSC_H5SparseMatrixSeed to SVT_SparseMatrix.
### Does NOT propagate the dimnames.
###
### Notes:
### - SparseArray:::make_SVT_SparseMatrix_from_CSC() will fail if
### supplied 'data'/'row_indices' arguments are long vectors because R
### does not support passing long vectors to the .Call interface yet!
### So we use a block strategy where we load blocks of adjacent columns
### and convert them to SVT_SparseMatrix objects, then cbind() all the
### objects together. By default, blocks are made of 125 millions
### data/indices elements.
### - Supports parallelization via the 'BPPARAM' argument. However some
### quick testing with 'BiocParallel::MulticoreParam(2)' on a powerful
### Linux server seemed to indicate that it's not worth it. Execution
### time remained about the same but memory footprint increased
### significantly!
.load_CSC_H5SparseMatrixSeed <- function(x, j=NULL,
DATABLOCKLEN=125000000L,
BPPARAM=NULL)
{
stopifnot(is(x, "CSC_H5SparseMatrixSeed"),
isSingleInteger(DATABLOCKLEN), DATABLOCKLEN >= 0L)
if (is.null(j)) {
ans_ncol <- ncol(x)
w <- x@indptr_ranges[ , "width"]
} else {
stopifnot(is.integer(j))
ans_ncol <- length(j)
if (ans_ncol != 0L)
stopifnot(isStrictlySorted(j),
1L <= j[[1L]], j[[ans_ncol]] <= ncol(x))
w <- x@indptr_ranges[j , "width"]
}
ans_dim <- c(nrow(x), ans_ncol)
## 'cumsum(as.double(w))' instead of 'cumsum(w)' to avoid integer overflow.
ans_indptr <- c(0, cumsum(as.double(w)))
ans_nzcount <- ans_indptr[[length(ans_indptr)]]
## DATABLOCKLEN == 0L means no block processing.
if (DATABLOCKLEN == 0L || ans_nzcount <= DATABLOCKLEN) {
if (is.null(j)) {
start <- count <- NULL
} else {
start <- x@indptr_ranges[j, "start"]
count <- x@indptr_ranges[j, "width"]
}
ans_data <- .read_h5sparse_data(x@filepath, x@group, x@subdata,
start=start, count=count)
ans_row_indices <- .read_h5sparse_indices(x@filepath, x@group,
start=start, count=count)
ans <- SparseArray:::make_SVT_SparseMatrix_from_CSC(ans_dim,
ans_indptr, ans_data, ans_row_indices)
return(ans)
}
## Compute 'nblock' (will always be >= 2).
nblock <- ans_nzcount %/% DATABLOCKLEN
if (ans_nzcount %% DATABLOCKLEN != 0L)
nblock <- nblock + 1L
## Partition column indices in ranges (nb of ranges is guaranteed to be
## >= 1 and <= 'min(nblock, ans_ncol)').
col_ranges <- breakInChunks(ans_ncol, nblock)
## There will be zero-width ranges if and only if 'nblock' > 'ans_ncol'.
## Drop them.
col_ranges <- col_ranges[width(col_ranges) != 0L]
s <- start(col_ranges)
e <- end(col_ranges)
## Load ranges of columns into SVT_SparseMatrix objects.
objects <- S4Arrays:::bplapply2(seq_along(col_ranges),
function(b, x, j, s, e) {
k1 <- s[[b]]
k2 <- e[[b]]
jj <- if (is.null(j)) k1:k2 else j[k1:k2]
## Set 'DATABLOCKLEN' to 0L to disable block processing.
.load_CSC_H5SparseMatrixSeed(x, jj, DATABLOCKLEN=0L)
},
x, j, s, e,
BPPARAM=BPPARAM
)
## Combine all objects together.
do.call(cbind, objects)
}
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### extract_sparse_array() and extract_array() methods
###
.extract_sparse_array_from_CSC_H5SparseMatrixSeed <- function(x, index)
{
j <- index[[2L]]
if (!is.null(j)) {
if (!is.integer(j))
j <- as.integer(j)
sort_j <- !isStrictlySorted(j)
if (sort_j) {
j0 <- j
j <- unique(sort(j))
}
}
svt <- .load_CSC_H5SparseMatrixSeed(x, j=j)
index2 <- list(index[[1L]], NULL)
if (!is.null(j) && sort_j)
index2[[2L]] <- match(j0, j)
extract_sparse_array(svt, index2)
}
setMethod("extract_sparse_array", "CSC_H5SparseMatrixSeed",
function(x, index)
.extract_sparse_array_from_CSC_H5SparseMatrixSeed(x, index)
)
setMethod("extract_sparse_array", "CSR_H5SparseMatrixSeed",
function(x, index)
t(.extract_sparse_array_from_CSC_H5SparseMatrixSeed(t(x), rev(index)))
)
setMethod("extract_array", "H5SparseMatrixSeed",
function(x, index) as.array(extract_sparse_array(x, index))
)
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### Show
###
setMethod("show", "H5SparseMatrixSeed",
function(object)
{
cat(S4Arrays:::array_as_one_line_summary(object), ":\n", sep="")
cat("# dirname: ", dirname(object), "\n", sep="")
cat("# basename: ", basename(object), "\n", sep="")
cat("# group: ", object@group, "\n", sep="")
}
)
### -------------------------------------------------------------------------
### OLD STUFF. To be deprecated soon!
### -------------------------------------------------------------------------
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### .get_data_indices_by_col()
###
### Used by .load_sparse_data(), extractNonzeroDataByCol(), and
### extractNonzeroDataByRow() defined below in this file.
###
### base::sequence() does not properly handle a 'from' that is >
### .Machine$integer.max so we implement a variant that does. Note that
### the 2nd argument of this variant is 'offset' instead of 'from' ('offset'
### being the same as 'from' - 1).
### TODO: Does .sequence2() work if sum(lengths) is > .Machine$integer.max?
.sequence2 <- function(lengths, offset=0)
{
lengths_len <- length(lengths)
if (lengths_len == 0L)
return(numeric(0))
offsets <- offset - cumsum(c(0L, lengths[-lengths_len]))
seq_len(sum(lengths)) + rep.int(offsets, lengths)
}
### 'j' must be an integer vector containing valid col indices.
### Return data indices in a NumericList object parallel to 'j' i.e. with
### one list element per col index in 'j'.
.get_data_indices_by_col <- function(x, j)
{
indptr_ranges <- S4Vectors:::extract_data_frame_rows(x@indptr_ranges, j)
start2 <- indptr_ranges[ , "start"]
width2 <- indptr_ranges[ , "width"]
idx2 <- .sequence2(width2, offset=start2 - 1L)
### Will this work if 'idx2' is a long vector?
relist(idx2, PartitioningByWidth(width2))
}
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### .extract_data_from_adjacent_cols()
###
### Used by .load_sparse_data(), extractNonzeroDataByCol(), and
### extractNonzeroDataByRow() defined below in this file.
###
### 'j1' and 'j2' must be 2 single integers representing a valid range of
### col indices.
### If 'as.sparse=FALSE', returns a NumericList or IntegerList object parallel
### to 'j1:j2' i.e. with one list element per col index in 'j1:j2'.
### If 'as.sparse=TRUE', returns a SparseArraySeed object.
.extract_data_from_adjacent_cols <- function(x, j1, j2, as.sparse=FALSE)
{
j12 <- j1:j2
start <- x@indptr_ranges[j1, "start"]
count_per_col <- x@indptr_ranges[j12, "width"]
count <- sum(count_per_col)
ans_nzdata <- .read_h5sparse_data(x@filepath, x@group, x@subdata,
start=start, count=count)
if (!as.sparse)
return(relist(ans_nzdata, PartitioningByWidth(count_per_col)))
row_indices <- .read_h5sparse_indices(x@filepath, x@group,
start=start, count=count) + 1L
col_indices <- rep.int(j12, count_per_col)
ans_nzindex <- cbind(row_indices, col_indices, deparse.level=0L)
SparseArraySeed(dim(x), ans_nzindex, ans_nzdata, check=FALSE)
}
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### .load_sparse_data()
###
### Used by the OLD_extract_sparse_array() and read_sparse_block() methods
### for H5SparseMatrixSeed objects defined below in this file.
###
### Loads sparse data using the "random" method.
### This method is based on h5mread( , starts=list(start)) which retrieves
### an arbitrary/random subset of the data.
### 'i' must be NULL or an integer vector containing valid row indices.
### 'j' must be an integer vector containing valid col indices. It cannot
### be NULL.
### Both 'i' and 'j' can contain duplicates. Duplicates in 'i' have no effect
### on the output but duplicates in 'j' will produce duplicates in the output.
### Returns a SparseArraySeed object.
.load_random_csc_sparse_data <- function(x, i, j)
{
stopifnot(is.null(i) || is.numeric(i), is.numeric(j))
data_indices <- .get_data_indices_by_col(x, j)
idx2 <- unlist(data_indices, use.names=FALSE)
row_indices <- .read_h5sparse_indices(x@filepath, x@group, start=idx2) + 1L
col_indices <- rep.int(j, lengths(data_indices))
if (!is.null(i)) {
keep_idx <- which(row_indices %in% i)
idx2 <- idx2[keep_idx]
row_indices <- row_indices[keep_idx]
col_indices <- col_indices[keep_idx]
}
ans_nzindex <- cbind(row_indices, col_indices, deparse.level=0L)
ans_nzdata <- .read_h5sparse_data(x@filepath, x@group, x@subdata,
start=idx2)
SparseArraySeed(dim(x), ans_nzindex, ans_nzdata, check=FALSE)
}
### Loads sparse data using the "linear" method.
### This method is based on h5mread( , starts=list(start), counts=list(count))
### which retrieves a linear subset of the data and should be more efficient
### than doing h5mread( , starts=list(seq(start, length.out=count))).
### 'j' must be NULL or a non-empty integer vector containing valid
### col indices. The output is not affected by duplicates in 'j'.
### Returns a SparseArraySeed object.
.load_linear_csc_sparse_data <- function(x, j)
{
if (is.null(j)) {
j1 <- 1L
j2 <- ncol(x)
} else {
stopifnot(is.numeric(j), length(j) != 0L)
j1 <- min(j)
j2 <- max(j)
}
.extract_data_from_adjacent_cols(x, j1, j2, as.sparse=TRUE)
}
.normarg_method <- function(method, j)
{
if (method != "auto")
return(method)
if (is.null(j))
return("linear")
if (length(j) == 0L)
return("random")
j1 <- min(j)
j2 <- max(j)
## 'ratio' is > 0 and <= 1. A value close to 1 indicates that the columns
## to extract are close from each other (a value of 1 indicating that
## they are adjacent e.g. j <- 18:25). A value close to 0 indicates that
## they are far apart from each other i.e. that they are separated by many
## columns that are not requested. The "linear" method is very efficient
## when 'ratio' is close to 1. It is so much more efficient than the
## "random" method (typically 10x or 20x faster) that we choose it when
## 'ratio' is >= 0.2
ratio <- length(j) / (j2 - j1 + 1L)
if (ratio >= 0.2) "linear" else "random"
}
### Duplicates in 'index[[1]]' are ok and won't affect the output.
### Duplicates in 'index[[2]]' are ok but might introduce duplicates
### in the output so should be avoided.
### Returns a SparseArraySeed object.
.load_csc_sparse_data <- function(x, index, method)
{
i <- index[[1L]]
j <- index[[2L]]
method <- .normarg_method(method, j)
if (method == "random") {
ans <- .load_random_csc_sparse_data(x, i, j)
} else {
ans <- .load_linear_csc_sparse_data(x, j)
}
ans
}
### Returns a SparseArraySeed object.
setGeneric(".load_sparse_data", signature="x",
function(x, index, method=c("auto", "random", "linear"))
standardGeneric(".load_sparse_data")
)
setMethod(".load_sparse_data", "CSC_H5SparseMatrixSeed",
function(x, index, method=c("auto", "random", "linear"))
{
method <- match.arg(method)
.load_csc_sparse_data(x, index, method)
}
)
setMethod(".load_sparse_data", "CSR_H5SparseMatrixSeed",
function(x, index, method=c("auto", "random", "linear"))
{
method <- match.arg(method)
t(.load_csc_sparse_data(t(x), rev(index), method))
}
)
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### OLD_extract_sparse_array() and read_sparse_block() methods
###
### TODO: Deprecate this stuff.
###
.OLD_extract_sparse_array_from_H5SparseMatrixSeed <- function(x, index)
{
sas <- .load_sparse_data(x, index) # I/O
OLD_extract_sparse_array(sas, index) # in-memory
}
setMethod("OLD_extract_sparse_array", "H5SparseMatrixSeed",
.OLD_extract_sparse_array_from_H5SparseMatrixSeed
)
### The default read_sparse_block() method defined in DelayedArray would
### work just fine on an H5SparseMatrixSeed derivative (thanks to the
### OLD_extract_sparse_array() method for H5SparseMatrixSeed objects defined
### above), but we overwrite it with the method below which should be
### slightly more efficient. That's because the method below calls
### read_sparse_block() on the SparseArraySeed object returned by
### .load_sparse_data(), and this should be faster than calling
### OLD_extract_sparse_array() on the same object (which is what the
### OLD_extract_sparse_array() method for H5SparseMatrixSeed objects would
### be doing when called by the default read_sparse_block() method).
### Not sure the difference is actually significant enough for this extra
### method to be worth it though, because time is really dominated by I/O
### here, that is, by the call to .load_sparse_data().
.read_sparse_block_from_H5SparseMatrixSeed <- function(x, viewport)
{
index <- makeNindexFromArrayViewport(viewport, expand.RangeNSBS=TRUE)
sas <- .load_sparse_data(x, index) # I/O
## Unlike the OLD_extract_sparse_array() method for H5SparseMatrixSeed
## objects defined above, we use read_sparse_block() here, which should
## be faster than using OLD_extract_sparse_array().
read_sparse_block(sas, viewport) # in-memory
}
setMethod("read_sparse_block", "H5SparseMatrixSeed",
.read_sparse_block_from_H5SparseMatrixSeed
)
### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### extractNonzeroDataByCol() and extractNonzeroDataByRow()
###
### TODO: Deprecate these 2 generics and their methods. These 2 generics are
### weird and don't have good/strong use cases. I suspect nobody uses them
### nor is aware of them.
###
### Extract nonzero data using the "random" method.
### This method is based on h5mread( , starts=list(start)) which retrieves
### an arbitrary/random subset of the data.
### 'j' must be an integer vector containing valid col indices. It cannot
### be NULL.
.random_extract_nonzero_data_by_col <- function(x, j)
{
data_indices <- .get_data_indices_by_col(x, j)
idx2 <- unlist(data_indices, use.names=FALSE)
data <- .read_h5sparse_data(x@filepath, x@group, x@subdata, start=idx2)
relist(data, data_indices)
}
### Extract nonzero data using the "linear" method.
### This method is based on h5mread( , starts=list(start), counts=list(count))
### which retrieves a linear subset of the data and should be more efficient
### than doing h5mread( , starts=list(seq(start, length.out=count))).
### 'j' must be NULL or an integer vector containing valid col indices. It
### should not be empty.
.linear_extract_nonzero_data_by_col <- function(x, j)
{
if (is.null(j)) {
j1 <- 1L
j2 <- ncol(x)
} else {
stopifnot(is.numeric(j), length(j) != 0L)
j1 <- min(j)
j2 <- max(j)
}
nonzero_data <- .extract_data_from_adjacent_cols(x, j1, j2)
if (is.null(j))
return(nonzero_data)
nonzero_data[match(j, j1:j2)]
}
### 'j' must be NULL or an integer vector containing valid col indices.
### Return a NumericList or IntegerList object parallel to 'j' i.e. with
### one list element per col index in 'j'.
.extract_nonzero_csc_sparse_data_by_col <-
function(x, j, method=c("auto", "random", "linear"))
{
method <- match.arg(method)
method <- .normarg_method(method, j)
if (method == "random") {
.random_extract_nonzero_data_by_col(x, j)
} else {
.linear_extract_nonzero_data_by_col(x, j)
}
}
### Return a NumericList or IntegerList object parallel to 'j' i.e. with
### one list element per col index in 'j'.
setGeneric("extractNonzeroDataByCol", signature="x",
function(x, j) standardGeneric("extractNonzeroDataByCol")
)
setMethod("extractNonzeroDataByCol", "CSC_H5SparseMatrixSeed",
function(x, j)
{
j <- S4Arrays:::normalizeSingleBracketSubscript2(j, ncol(x),
colnames(x))
.extract_nonzero_csc_sparse_data_by_col(x, j)
}
)
### Return a NumericList or IntegerList object parallel to 'i' i.e. with
### one list element per row index in 'i'.
setGeneric("extractNonzeroDataByRow", signature="x",
function(x, i) standardGeneric("extractNonzeroDataByRow")
)
setMethod("extractNonzeroDataByRow", "CSR_H5SparseMatrixSeed",
function(x, i)
{
i <- S4Arrays:::normalizeSingleBracketSubscript2(i, nrow(x),
rownames(x))
.extract_nonzero_csc_sparse_data_by_col(t(x), i)
}
)
|