# Extending dispatch to more batch correction methods

Aaron Lun1

1Cancer Research UK Cambridge Institute, Cambridge, United Kingdom

#### Revised: 11 February 2019

#### Package

batchelor 1.17.0

# 1 Overview

The batchelor package provides the `batchCorrect()` generic that dispatches on its `PARAM` argument. Users writing code using `batchCorrect()` can easily change one method for another by simply modifying the class of object supplied as `PARAM`. For example:

    B1 <- matrix(rnorm(10000), ncol=50) # Batch 1
    B2 <- matrix(rnorm(10000), ncol=50) # Batch 2

    # Switching easily between batch correction methods.
    m.out <- batchCorrect(B1, B2, PARAM=ClassicMnnParam())
    f.out <- batchCorrect(B1, B2, PARAM=FastMnnParam(d=20))
    r.out <- batchCorrect(B1, B2, PARAM=RescaleParam(pseudo.count=0))

Developers of other packages can extend this further by adding their batch correction methods to this dispatch system. This improves interoperability across packages by allowing users to easily experiment with different methods.

# 2 Setting up

You will need to `Imports: batchelor, methods` in your `DESCRIPTION` file. You will also need to add `import(methods)`, `importFrom(batchelor, "batchCorrect")` and `importClassesFrom(batchelor, "BatchelorParam")` in your `NAMESPACE` file.

Obviously, you will also need to have a function that implements your batch correction method. For demonstration purposes, we will use an identity function that simply returns the input values1 1 1 Not a very good correction, but that’s not the point right now.. This is implemented like so:

    noCorrect <- function(...)
    # Takes a set of batches and returns them without modification.
    {
       do.call(cbind, list(...))
    }

# 3 Deriving a `BatchelorParam` subclass

We need to define a new `BatchelorParam` subclass that instructs the `batchCorrect()` generic to dispatch to our new method. This is most easily done like so:

    NothingParam <- setClass("NothingParam", contains="BatchelorParam")

Note that `BatchelorParam` itself is derived from a `SimpleList` and can be modified with standard list operators like `$`.

    nothing <- NothingParam()
    nothing

    ## NothingParam of length 0

    nothing$some_value <- 1
    nothing

    ## NothingParam of length 1
    ## names(1): some_value

If no parameters are set, the default values in the function will be used2 2 2 Here there are none in `noCorrect()`, but presumably your function is more complex than that.. Additional slots can be specified in the class definition if there are important parameters that need to be manually specified by the user.

# 4 Defining a `batchCorrect` method

## 4.1 Input

The `batchCorrect()` generic looks like this:

    batchCorrect

    ## standardGeneric for "batchCorrect" defined from package "batchelor"
    ##
    ## function (..., batch = NULL, restrict = NULL, subset.row = NULL,
    ##     correct.all = FALSE, assay.type = NULL, PARAM)
    ## standardGeneric("batchCorrect")
    ## <bytecode: 0x000001c521135e40>
    ## <environment: 0x000001c52112b840>
    ## Methods may be defined for arguments: PARAM
    ## Use  showMethods(batchCorrect)  for currently available ones.

Any implemented method must accept one or more matrix-like objects containing single-cell gene expression matrices in `...`. Rows are assumed to be genes and columns are assumed to be cells. If only one object is supplied, `batch` must be specified to indicate the batches to which each cell belongs.

Alternatively, one or more `SingleCellExperiment` objects can be supplied, containing the gene expression matrix in the `assay.type` assay. These should not be mixed with matrix-like objects, i.e., if one object is a `SingleCellExperiment`, all objects should be `SingleCellExperiment`s.

The `subset.row=` argument specifies a subset of genes on which to perform the correction. The `correct.all=` argument specifies whether corrected values should be returned for all genes, by “extrapolating” from the results for the genes that were used3 3 3 If your method cannot support this option, setting it to `TRUE` should raise an error.. See the Output section below for the expected output from each combination of these settings.

The `restrict=` argument allows users to compute the correction using only a subset of cells in each batch (e.g., from cell controls). The correction is then “extrapolated” to all cells in the batch4 4 4 Again, if your method cannot support this, any non-`NULL` value of `restrict` should raise an error., such that corrected values are returned for all cells.

## 4.2 Output

Any implemented method must return a `SingleCellExperiment` where the first assay contains corrected gene expression values for all genes. Corrected values should be returned for all genes if `correct.all=TRUE` or `subset.row=NULL`. If `correct.all=FALSE` and `subset.row` is not `NULL`, values should only be returned for the selected genes.

Cells should be reported in the same order that they are supplied in `...`. In cases with multiple batches, the cell identities are simply concatenated from successive objects in their specified order, i.e., all cells from the first object (in their provided order), then all cells from the second object, and so on. If there is only a single batch, the order of cells in that batch should be preserved.

The output object should have row names equal to the row names of the input objects. Column names should be equivalent to the concatenated column names of the input objects, unless all are `NULL`, in which case the column names in the output can be `NULL`. In situations where some input objects have column names, and others are `NULL`, those missing column names should be filled in with empty strings. This represents the expected behaviour when `cbind`ing multiple matrices together.

Finally, the `colData` slot should contain ‘batch’, a vector specifying the batch of origin for each cell.

## 4.3 Demonstration

Finally, we define a method that calls our `noCorrect` function while satisfying all of the above input/output requirements. To be clear, it is not mandatory to lay out the code as shown below; this is simply one way that all the requirements can be satisfied. We have used some internal batchelor functions for brevity - please contact us if you find these useful and want them to be exported.

    setMethod("batchCorrect", "NothingParam", function(..., batch = NULL,
        restrict=NULL, subset.row = NULL, correct.all = FALSE,
        assay.type = "logcounts", PARAM)
    {
        batches <- list(...)
        checkBatchConsistency(batches)

        # Pulling out information from the SCE objects.
        is.sce <- checkIfSCE(batches)
        if (any(is.sce)) {
            batches[is.sce] <- lapply(batches[is.sce], assay, i=assay.type)
        }

        # Subsetting by 'batch', if only one object is supplied.
        do.split <- length(batches)==1L
        if (do.split) {
            divided <- divideIntoBatches(batches[[1]], batch=batch, restrict=restrict)
            batches <- divided$batches
            restrict <- divided$restricted
        }

        # Subsetting by row.
        # This is a per-gene "method", so correct.all=TRUE will ignore subset.row.
        # More complex methods will need to handle this differently.
        if (correct.all) {
            subset.row <- NULL
        } else if (!is.null(subset.row)) {
            subset.row <- normalizeSingleBracketSubscript(originals[[1]], subset.row)
            batches <- lapply(batches, "[", i=subset.row, , drop=FALSE)
        }

        # Don't really need to consider restrict!=NULL here, as this function
        # doesn't do anything with the cells anyway.
        output <- do.call(noCorrect, batches)

        # Reordering the output for correctness if it was previously split.
        if (do.split) {
            d.reo <- divided$reorder
            output <- output[,d.reo,drop=FALSE]
        }

        ncells.per.batch <- vapply(batches, FUN=ncol, FUN.VALUE=0L)
        batch.names <- names(batches)
        if (is.null(batch.names)) {
            batch.names <- seq_along(batches)
        }

        SingleCellExperiment(list(corrected=output),
            colData=DataFrame(batch=rep(batch.names, ncells.per.batch)))
    })

And it works5 5 5 In a strictly programming sense, as the method itself does no correction at all.:

    n.out <- batchCorrect(B1, B2, PARAM=NothingParam())
    n.out

    ## class: SingleCellExperiment
    ## dim: 200 100
    ## metadata(0):
    ## assays(1): corrected
    ## rownames: NULL
    ## rowData names(0):
    ## colnames: NULL
    ## colData names(1): batch
    ## reducedDimNames(0):
    ## mainExpName: NULL
    ## altExpNames(0):

Remember to export both the new method and the `NothingParam` class and constructor.

# 5 Session information

    sessionInfo()

    ## R version 4.3.0 RC (2023-04-18 r84287 ucrt)
    ## Platform: x86_64-w64-mingw32/x64 (64-bit)
    ## Running under: Windows Server 2022 x64 (build 20348)
    ##
    ## Matrix products: default
    ##
    ##
    ## locale:
    ## [1] LC_COLLATE=C
    ## [2] LC_CTYPE=English_United States.utf8
    ## [3] LC_MONETARY=English_United States.utf8
    ## [4] LC_NUMERIC=C
    ## [5] LC_TIME=English_United States.utf8
    ##
    ## time zone: America/New_York
    ## tzcode source: internal
    ##
    ## attached base packages:
    ## [1] stats4    stats     graphics  grDevices utils     datasets  methods
    ## [8] base
    ##
    ## other attached packages:
    ##  [1] scater_1.29.0               ggplot2_3.4.2
    ##  [3] scran_1.29.0                scuttle_1.11.0
    ##  [5] scRNAseq_2.15.0             batchelor_1.17.0
    ##  [7] SingleCellExperiment_1.23.0 SummarizedExperiment_1.31.1
    ##  [9] Biobase_2.61.0              GenomicRanges_1.53.1
    ## [11] GenomeInfoDb_1.37.1         IRanges_2.35.1
    ## [13] S4Vectors_0.39.1            BiocGenerics_0.47.0
    ## [15] MatrixGenerics_1.13.0       matrixStats_0.63.0
    ## [17] knitr_1.42                  BiocStyle_2.29.0
    ##
    ## loaded via a namespace (and not attached):
    ##   [1] jsonlite_1.8.4                magrittr_2.0.3
    ##   [3] magick_2.7.4                  ggbeeswarm_0.7.2
    ##   [5] GenomicFeatures_1.53.0        farver_2.1.1
    ##   [7] rmarkdown_2.21                BiocIO_1.11.0
    ##   [9] zlibbioc_1.47.0               vctrs_0.6.2
    ##  [11] memoise_2.0.1                 Rsamtools_2.17.0
    ##  [13] DelayedMatrixStats_1.23.0     RCurl_1.98-1.12
    ##  [15] htmltools_0.5.5               S4Arrays_1.1.2
    ##  [17] progress_1.2.2                AnnotationHub_3.9.1
    ##  [19] curl_5.0.0                    BiocNeighbors_1.19.0
    ##  [21] SparseArray_1.1.2             sass_0.4.6
    ##  [23] bslib_0.4.2                   cachem_1.0.8
    ##  [25] ResidualMatrix_1.11.0         GenomicAlignments_1.37.0
    ##  [27] igraph_1.4.2                  mime_0.12
    ##  [29] lifecycle_1.0.3               pkgconfig_2.0.3
    ##  [31] rsvd_1.0.5                    Matrix_1.5-4
    ##  [33] R6_2.5.1                      fastmap_1.1.1
    ##  [35] GenomeInfoDbData_1.2.10       shiny_1.7.4
    ##  [37] digest_0.6.31                 colorspace_2.1-0
    ##  [39] AnnotationDbi_1.63.1          dqrng_0.3.0
    ##  [41] irlba_2.3.5.1                 ExperimentHub_2.9.0
    ##  [43] RSQLite_2.3.1                 beachmat_2.17.1
    ##  [45] labeling_0.4.2                filelock_1.0.2
    ##  [47] fansi_1.0.4                   httr_1.4.5
    ##  [49] compiler_4.3.0                bit64_4.0.5
    ##  [51] withr_2.5.0                   BiocParallel_1.35.0
    ##  [53] viridis_0.6.3                 DBI_1.1.3
    ##  [55] highr_0.10                    biomaRt_2.57.0
    ##  [57] rappdirs_0.3.3                DelayedArray_0.27.2
    ##  [59] rjson_0.2.21                  bluster_1.11.0
    ##  [61] tools_4.3.0                   vipor_0.4.5
    ##  [63] beeswarm_0.4.0                interactiveDisplayBase_1.39.0
    ##  [65] httpuv_1.6.9                  glue_1.6.2
    ##  [67] restfulr_0.0.15               promises_1.2.0.1
    ##  [69] grid_4.3.0                    Rtsne_0.16
    ##  [71] cluster_2.1.4                 generics_0.1.3
    ##  [73] gtable_0.3.3                  ensembldb_2.25.0
    ##  [75] hms_1.1.3                     metapod_1.9.0
    ##  [77] BiocSingular_1.17.0           ScaledMatrix_1.9.1
    ##  [79] xml2_1.3.4                    utf8_1.2.3
    ##  [81] XVector_0.41.1                ggrepel_0.9.3
    ##  [83] BiocVersion_3.18.0            pillar_1.9.0
    ##  [85] stringr_1.5.0                 limma_3.57.0
    ##  [87] later_1.3.1                   dplyr_1.1.2
    ##  [89] BiocFileCache_2.9.0           lattice_0.21-8
    ##  [91] rtracklayer_1.61.0            bit_4.0.5
    ##  [93] tidyselect_1.2.0              locfit_1.5-9.7
    ##  [95] Biostrings_2.69.0             gridExtra_2.3
    ##  [97] bookdown_0.33                 ProtGenerics_1.33.0
    ##  [99] edgeR_3.43.1                  xfun_0.39
    ## [101] statmod_1.5.0                 stringi_1.7.12
    ## [103] lazyeval_0.2.2                yaml_2.3.7
    ## [105] evaluate_0.20                 codetools_0.2-19
    ## [107] tibble_3.2.1                  BiocManager_1.30.20
    ## [109] cli_3.6.1                     xtable_1.8-4
    ## [111] munsell_0.5.0                 jquerylib_0.1.4
    ## [113] Rcpp_1.0.10                   dbplyr_2.3.2
    ## [115] png_0.1-8                     XML_3.99-0.14
    ## [117] parallel_4.3.0                ellipsis_0.3.2
    ## [119] blob_1.2.4                    prettyunits_1.1.1
    ## [121] AnnotationFilter_1.25.0       sparseMatrixStats_1.13.0
    ## [123] bitops_1.0-7                  viridisLite_0.4.2
    ## [125] scales_1.2.1                  purrr_1.0.1
    ## [127] crayon_1.5.2                  rlang_1.1.1
    ## [129] cowplot_1.1.1                 KEGGREST_1.41.0