## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>",
                      error = FALSE, warning = FALSE, message = FALSE)

.matrixstats_ok <- requireNamespace("sparseMatrixStats", quietly = TRUE) ||
    requireNamespace("DelayedMatrixStats", quietly = TRUE)

## ----matrixstats-unavailable-note, echo=FALSE, results='asis', eval=!.matrixstats_ok----
# cat("> **Note:** Neither `sparseMatrixStats` nor `DelayedMatrixStats` is ",
#     "installed in this build environment, so the `rowVars()` comparison below ",
#     "is shown but not evaluated. Install one of them (with ",
#     "`BiocManager::install()`) to run it.\n", sep = "")

## ----live-demo----------------------------------------------------------------
library(DuckDBArray)
library(Matrix)
library(MatrixGenerics)

set.seed(1L)
m <- Matrix(rpois(2000 * 400, lambda = 0.3), nrow = 2000, ncol = 400,
            sparse = TRUE)
rownames(m) <- paste0("Gene", seq_len(nrow(m)))
colnames(m) <- paste0("Cell", seq_len(ncol(m)))

path <- tempfile()
writeCoordArray(m, path)
mat <- DuckDBMatrix(path, datacol = "value",
                    keycols = list(index1 = setNames(seq_len(nrow(m)), rownames(m)),
                                   index2 = setNames(seq_len(ncol(m)), colnames(m))),
                    dimtbls = createDimTables(m))

## same answer, one in memory and one queried from disk;
## rowDeviances() is DuckDBArray's own generic and needs no optional package
all.equal(unname(rowDeviances(m, family = "binomial")),
          unname(rowDeviances(mat, family = "binomial")))

## ----live-demo-rowvars, eval=.matrixstats_ok----------------------------------
## rowVars(m) dispatches to sparseMatrixStats/DelayedMatrixStats for the plain
## dgCMatrix; rowVars(mat) is DuckDBArray's own method and needs neither
all.equal(rowVars(m), rowVars(mat))

## ----timings, echo=FALSE, results='asis'--------------------------------------
helper <- system.file("scripts", "make_timings_table.R", package = "DuckDBArray")
res <- if (nzchar(helper)) { source(helper); load_vignette_timings() } else NULL
if (is.null(res)) {
    cat("_Precomputed benchmark timings are not available in this build; ",
        "generate them with `inst/scripts/run_vignette_benchmarks.R`._\n", sep = "")
} else {
    cat("\n**Best effort (full core budget)**\n\n")
    cat(make_timings_table("parallel", results = res,
        caption = "Elapsed seconds, each backend using the full core budget."),
        sep = "\n")
    cat("\n\n**Single-threaded (one core)**\n\n")
    cat(make_timings_table("serial", results = res,
        caption = "Elapsed seconds, one core per backend."), sep = "\n")
    cat("\n\n")
    timings_config_note(res)
}

## ----sessioninfo--------------------------------------------------------------
sessionInfo()

