# Converting BUS format into sparse matrix

Lambda Moses

#### 2024-10-29

# Contents

## 0.1 Introduction

The Barcode, UMI, Set (BUS) format is a new way to represent pseudoalignments of reads from RNA-seq. Files of this format can be efficiently generated by the command line tool `kallisto bus`. With `kallisto bus` and this package, we go from the fastq files to the sparse matrix used for downstream analysis such as with Seurat within half an hour, while Cell Ranger would take hours.

In this vignette, we convert an 10x 1:1 mouse and human cell mixture dataset from the BUS format to a sparse matrix. To see how the BUS format can be generated from fastq file, as well as more in depth vignettes, see the website of this package.

Note that this vignette is deprecated and is kept for historical reasons as it was implemented when `kallisto | bustools` was experimental. The functionality of `make_sparse_matrix` has been implemented more efficiently in the command line tool `bustools`. Please use the updated version of `bustools` and if you wish, the wrapper `kb` instead.

## 0.2 Download the dataset

    # The dataset package
    library(TENxBUSData)
    library(BUSpaRse)
    library(Matrix)
    library(zeallot)
    library(ggplot2)

    TENxBUSData(".", dataset = "hgmm100")
    #> see ?TENxBUSData and browseVignettes('TENxBUSData') for documentation
    #> loading from cache
    #> The downloaded files are in F:\biocbuild\bbs-3.20-bioc\tmpdir\RtmpC2SrBP\Rbuild143a8c7f662a\BUSpaRse\vignettes/out_hgmm100
    #> [1] "F:\\biocbuild\\bbs-3.20-bioc\\tmpdir\\RtmpC2SrBP\\Rbuild143a8c7f662a\\BUSpaRse\\vignettes/out_hgmm100"

## 0.3 Convert to sparse matrix

First, we map transcripts, as in the `kallisto` index, to the corresponding genes.

    tr2g <- transcript2gene(species = c("Homo sapiens", "Mus musculus"), type = "vertebrate",
                            kallisto_out_path = "./out_hgmm100", ensembl_version = 99,
                            write_tr2g = FALSE)
    #> Querying biomart for transcript and gene IDs of Homo sapiens
    #> Querying biomart for transcript and gene IDs of Mus musculus

    head(tr2g)
    #>          transcript              gene gene_name chromosome_name
    #> 1 ENST00000434970.2 ENSG00000237235.2     TRDD2              14
    #> 2 ENST00000415118.1 ENSG00000223997.1     TRDD1              14
    #> 3 ENST00000448914.1 ENSG00000228985.1     TRDD3              14
    #> 4 ENST00000632684.1 ENSG00000282431.1     TRBD1               7
    #> 5 ENST00000390583.1 ENSG00000211923.1  IGHD3-10              14
    #> 6 ENST00000431440.2 ENSG00000232543.2  IGHD4-11              14

Here we make both the gene count matrix and the TCC matrix.

    c(gene_count, tcc) %<-% make_sparse_matrix("./out_hgmm100/output.sorted.txt",
                                   tr2g = tr2g, est_ncells = 1e5,
                                   est_ngenes = nrow(tr2g))
    #> Reading matrix.ec
    #> Processing ECs
    #> Matching genes to ECs
    #> Reading data
    #> Constructing gene count matrix
    #> Constructing TCC matrix

## 0.4 Remove empty droplets

Here we have a sparse matrix with genes in rows and cells in columns.

    dim(gene_count)
    #> [1]  26937 151449

This dataset should only have about 100 cells, but here we get over 100,000. In fact, most of the barcodes correspond to empty droplets; they can be removed by filtering out barcodes with too few UMI.

    tot_counts <- Matrix::colSums(gene_count)
    summary(tot_counts)
    #>     Min.  1st Qu.   Median     Mean  3rd Qu.     Max.
    #>     1.00     1.00     2.00    24.77     5.00 64041.00

    df1 <- get_knee_df(gene_count)
    infl1 <- get_inflection(df1)

    knee_plot(df1, infl1)

    gene_count <- gene_count[, tot_counts > infl1]
    dim(gene_count)
    #> [1] 26937   122

Then this sparse matrix can be used in Seurat for downstream analysis.

Likewise, we can remove empty droplets from the TCC matrix.

    dim(tcc)
    #> [1] 129371 157659

This dataset should only have about 100 cells, but here we get over 100,000. In fact, most of the barcodes correspond to empty droplets; they can be removed by filtering out barcodes with too few UMI.

    tot_counts <- Matrix::colSums(tcc)
    summary(tot_counts)
    #>     Min.  1st Qu.   Median     Mean  3rd Qu.     Max.
    #>     1.00     1.00     2.00    25.84     5.00 69235.00

    df2 <- get_knee_df(tcc)
    infl2 <- get_inflection(df2)

    knee_plot(df2, infl2)

    tcc <- tcc[, tot_counts > infl2]
    dim(tcc)
    #> [1] 129371    121

    sessionInfo()
    #> R version 4.4.1 (2024-06-14 ucrt)
    #> Platform: x86_64-w64-mingw32/x64
    #> 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] stats     graphics  grDevices utils     datasets  methods   base
    #>
    #> other attached packages:
    #> [1] ggplot2_3.5.1      zeallot_0.1.0      Matrix_1.7-1       BUSpaRse_1.20.0
    #> [5] TENxBUSData_1.19.0 BiocStyle_2.34.0
    #>
    #> loaded via a namespace (and not attached):
    #>   [1] DBI_1.2.3                   bitops_1.0-9
    #>   [3] httr2_1.0.5                 biomaRt_2.62.0
    #>   [5] rlang_1.1.4                 magrittr_2.0.3
    #>   [7] matrixStats_1.4.1           compiler_4.4.1
    #>   [9] RSQLite_2.3.7               GenomicFeatures_1.58.0
    #>  [11] png_0.1-8                   vctrs_0.6.5
    #>  [13] stringr_1.5.1               ProtGenerics_1.38.0
    #>  [15] pkgconfig_2.0.3             crayon_1.5.3
    #>  [17] fastmap_1.2.0               magick_2.8.5
    #>  [19] dbplyr_2.5.0                XVector_0.46.0
    #>  [21] utf8_1.2.4                  Rsamtools_2.22.0
    #>  [23] rmarkdown_2.28              UCSC.utils_1.2.0
    #>  [25] tinytex_0.53                purrr_1.0.2
    #>  [27] bit_4.5.0                   xfun_0.48
    #>  [29] zlibbioc_1.52.0             cachem_1.1.0
    #>  [31] GenomeInfoDb_1.42.0         jsonlite_1.8.9
    #>  [33] progress_1.2.3              blob_1.2.4
    #>  [35] highr_0.11                  DelayedArray_0.32.0
    #>  [37] BiocParallel_1.40.0         parallel_4.4.1
    #>  [39] prettyunits_1.2.0           plyranges_1.26.0
    #>  [41] R6_2.5.1                    bslib_0.8.0
    #>  [43] stringi_1.8.4               rtracklayer_1.66.0
    #>  [45] GenomicRanges_1.58.0        jquerylib_0.1.4
    #>  [47] Rcpp_1.0.13                 bookdown_0.41
    #>  [49] SummarizedExperiment_1.36.0 knitr_1.48
    #>  [51] IRanges_2.40.0              tidyselect_1.2.1
    #>  [53] abind_1.4-8                 yaml_2.3.10
    #>  [55] codetools_0.2-20            curl_5.2.3
    #>  [57] lattice_0.22-6              tibble_3.2.1
    #>  [59] withr_3.0.2                 Biobase_2.66.0
    #>  [61] KEGGREST_1.46.0             evaluate_1.0.1
    #>  [63] BiocFileCache_2.14.0        xml2_1.3.6
    #>  [65] ExperimentHub_2.14.0        Biostrings_2.74.0
    #>  [67] pillar_1.9.0                BiocManager_1.30.25
    #>  [69] filelock_1.0.3              MatrixGenerics_1.18.0
    #>  [71] stats4_4.4.1                generics_0.1.3
    #>  [73] RCurl_1.98-1.16             BiocVersion_3.20.0
    #>  [75] ensembldb_2.30.0            S4Vectors_0.44.0
    #>  [77] hms_1.1.3                   munsell_0.5.1
    #>  [79] scales_1.3.0                glue_1.8.0
    #>  [81] lazyeval_0.2.2              tools_4.4.1
    #>  [83] AnnotationHub_3.14.0        BiocIO_1.16.0
    #>  [85] BSgenome_1.74.0             GenomicAlignments_1.42.0
    #>  [87] XML_3.99-0.17               grid_4.4.1
    #>  [89] tidyr_1.3.1                 AnnotationDbi_1.68.0
    #>  [91] colorspace_2.1-1            GenomeInfoDbData_1.2.13
    #>  [93] restfulr_0.0.15             cli_3.6.3
    #>  [95] rappdirs_0.3.3              fansi_1.0.6
    #>  [97] S4Arrays_1.6.0              dplyr_1.1.4
    #>  [99] AnnotationFilter_1.30.0     gtable_0.3.6
    #> [101] sass_0.4.9                  digest_0.6.37
    #> [103] BiocGenerics_0.52.0         SparseArray_1.6.0
    #> [105] farver_2.1.2                rjson_0.2.23
    #> [107] memoise_2.0.1               htmltools_0.5.8.1
    #> [109] lifecycle_1.0.4             httr_1.4.7
    #> [111] mime_0.12                   bit64_4.5.2