Contents

library(CellaRepertorium)
library(SingleCellExperiment)
#> Loading required package: SummarizedExperiment
#> Loading required package: MatrixGenerics
#> Loading required package: matrixStats
#> 
#> Attaching package: 'matrixStats'
#> The following object is masked from 'package:dplyr':
#> 
#>     count
#> 
#> Attaching package: 'MatrixGenerics'
#> The following objects are masked from 'package:matrixStats':
#> 
#>     colAlls, colAnyNAs, colAnys, colAvgsPerRowSet, colCollapse,
#>     colCounts, colCummaxs, colCummins, colCumprods, colCumsums,
#>     colDiffs, colIQRDiffs, colIQRs, colLogSumExps, colMadDiffs,
#>     colMads, colMaxs, colMeans2, colMedians, colMins, colOrderStats,
#>     colProds, colQuantiles, colRanges, colRanks, colSdDiffs, colSds,
#>     colSums2, colTabulates, colVarDiffs, colVars, colWeightedMads,
#>     colWeightedMeans, colWeightedMedians, colWeightedSds,
#>     colWeightedVars, rowAlls, rowAnyNAs, rowAnys, rowAvgsPerColSet,
#>     rowCollapse, rowCounts, rowCummaxs, rowCummins, rowCumprods,
#>     rowCumsums, rowDiffs, rowIQRDiffs, rowIQRs, rowLogSumExps,
#>     rowMadDiffs, rowMads, rowMaxs, rowMeans2, rowMedians, rowMins,
#>     rowOrderStats, rowProds, rowQuantiles, rowRanges, rowRanks,
#>     rowSdDiffs, rowSds, rowSums2, rowTabulates, rowVarDiffs, rowVars,
#>     rowWeightedMads, rowWeightedMeans, rowWeightedMedians,
#>     rowWeightedSds, rowWeightedVars
#> Loading required package: GenomicRanges
#> Loading required package: Biobase
#> Welcome to Bioconductor
#> 
#>     Vignettes contain introductory material; view with
#>     'browseVignettes()'. To cite Bioconductor, see
#>     'citation("Biobase")', and for packages 'citation("pkgname")'.
#> 
#> Attaching package: 'Biobase'
#> The following object is masked from 'package:MatrixGenerics':
#> 
#>     rowMedians
#> The following objects are masked from 'package:matrixStats':
#> 
#>     anyMissing, rowMedians
library(dplyr)
library(ggplot2)
library(readr)
library(tidyr)
library(stringr)
library(purrr)

It is possible to combine ContigCellDB objects with SingleCellExperiment objects that measure overlapping barcodes. We choose to include the ContigCellDB object as a member of the colData. In this way, it is possible to include different cellular “views” of the repertoire, such as the alpha chain and beta chain properties, as well as the paired clonotypes.

1 “Load” expression

First we’ll cook up some single cell expression data.

set.seed(1345)
data(ccdb_ex)
barcodes = ccdb_ex$cell_tbl[ccdb_ex$cell_pk]

# Take a subsample of almost all of the barcdes
barcodes = barcodes[sample(nrow(barcodes), nrow(barcodes) - 5),]
samples = unique(ccdb_ex$cell_tbl[setdiff(ccdb_ex$cell_pk, 'barcode')])

# For each sample, generate  0-100 "extra" barcodes for which only 5' expression is recovered
extra = samples %>% rowwise() %>% mutate(extrabc = {
  extra_bc = floor(runif(1, 0, 100))
  list(tibble(barcode = paste0('barcode', seq_len(extra_bc))))
}) 
extra = extra %>% unnest(cols = c(extrabc))
all_bc = bind_rows(extra, barcodes)

Simulate some “cells” and “genes” that nearly form a superset of the cells for which repertoire are available. This is generally true if no barcode filters have been applied to the expression data. In practice a few cells may have repertoire but not expression (or fail QC for expression). We will work with the intersection of these cells.

genes = 200
cells = nrow(all_bc)
array_size = genes*cells
expression = matrix(rnbinom(array_size, size = 5, mu = 3), nrow = genes, ncol = cells)
sce = SingleCellExperiment(assay = list(counts = expression), colData = all_bc)

2 Remake the ContigCellDB with empty cells

ccdb2 = ccdb_join(sce, ccdb_ex)

ccdb2 = cdhit_ccdb(ccdb2, 'cdr3', type = 'AA', cluster_pk = 'aa80', identity = .8, min_length = 5)
ccdb2 = fine_clustering(ccdb2, sequence_key = 'cdr3', type = 'AA', keep_clustering_details = FALSE)
#> Calculating intradistances on 993 clusters.
#> Summarizing

The ccdb_join(template, ccdb) function does a left join of the template onto the cell_tbl of the ccdb. This will ensure that the cell_tbl is expanded and ordered properly to mesh with sce when we add it below.

3 Chain pairings

colData(sce)$alpha =  canonicalize_cell(ccdb2, chain == 'TRA', contig_fields = c('chain', 'v_gene','d_gene', 'j_gene', 'aa80'))

colData(sce)$beta =  canonicalize_cell(ccdb2, chain == 'TRB', contig_fields = c('chain', 'v_gene','d_gene', 'j_gene', 'aa80'))

colData(sce)$pairing = enumerate_pairing(ccdb2, chain_recode_fun = 'guess')

We can add multiple views, represented as fields in the colData(sce) of the repertoire.

4 Visualization of TCR features with Scater

We can leverage Scater’s ability to use “nested” data frames to visualize TCR features.

library(scater)
#> Loading required package: scuttle
sce = logNormCounts(sce)
sce = runPCA(sce)
plotReducedDim(sce, dimred = 'PCA', colour_by = I(sce$pairing$pairing), point_alpha = 1)

Here we calculate the first two principal components (which aren’t very interesting because these are simulated data without any special structure), and then visualize if the TCR was paired or not.

only_paired = sce[,which(sce$pairing$pairing == 'paired')]
plotReducedDim(only_paired, dimred = 'PCA', colour_by = I(only_paired$alpha$j_gene), point_alpha = 1)
#> Warning: Removed 328 rows containing missing values (geom_point).

plotReducedDim(only_paired, dimred = 'PCA', colour_by = I(only_paired$beta$j_gene), point_alpha = 1)

Since the ContigCellDB is nested within the SingleCellExperiment it automatically gets subsetted appropriately when the parent object is subsetted. Enough data.frame-like semantics have been implemented so that fields from the cell_tbl can be visualized.

5 Colophone

sessionInfo()
#> R version 4.2.1 (2022-06-23)
#> Platform: x86_64-pc-linux-gnu (64-bit)
#> Running under: Ubuntu 20.04.5 LTS
#> 
#> Matrix products: default
#> BLAS:   /home/biocbuild/bbs-3.16-bioc/R/lib/libRblas.so
#> LAPACK: /home/biocbuild/bbs-3.16-bioc/R/lib/libRlapack.so
#> 
#> locale:
#>  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
#>  [3] LC_TIME=en_GB              LC_COLLATE=C              
#>  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
#>  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
#>  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
#> [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
#> 
#> attached base packages:
#> [1] stats4    stats     graphics  grDevices utils     datasets  methods  
#> [8] base     
#> 
#> other attached packages:
#>  [1] scater_1.26.0               scuttle_1.8.0              
#>  [3] SingleCellExperiment_1.20.0 SummarizedExperiment_1.28.0
#>  [5] Biobase_2.58.0              GenomicRanges_1.50.0       
#>  [7] MatrixGenerics_1.10.0       matrixStats_0.62.0         
#>  [9] Biostrings_2.66.0           GenomeInfoDb_1.34.0        
#> [11] XVector_0.38.0              IRanges_2.32.0             
#> [13] S4Vectors_0.36.0            BiocGenerics_0.44.0        
#> [15] ggdendro_0.1.23             purrr_0.3.5                
#> [17] stringr_1.4.1               tidyr_1.2.1                
#> [19] readr_2.1.3                 ggplot2_3.3.6              
#> [21] dplyr_1.0.10                CellaRepertorium_1.8.0     
#> [23] BiocStyle_2.26.0           
#> 
#> loaded via a namespace (and not attached):
#>   [1] ggbeeswarm_0.6.0          minqa_1.2.5              
#>   [3] colorspace_2.0-3          ellipsis_0.3.2           
#>   [5] BiocNeighbors_1.16.0      listenv_0.8.0            
#>   [7] furrr_0.3.1               farver_2.1.1             
#>   [9] ggrepel_0.9.1             bit64_4.0.5              
#>  [11] fansi_1.0.3               codetools_0.2-18         
#>  [13] splines_4.2.1             sparseMatrixStats_1.10.0 
#>  [15] cachem_1.0.6              knitr_1.40               
#>  [17] jsonlite_1.8.3            nloptr_2.0.3             
#>  [19] broom_1.0.1               broom.mixed_0.2.9.4      
#>  [21] BiocManager_1.30.19       compiler_4.2.1           
#>  [23] backports_1.4.1           assertthat_0.2.1         
#>  [25] Matrix_1.5-1              fastmap_1.1.0            
#>  [27] cli_3.4.1                 BiocSingular_1.14.0      
#>  [29] htmltools_0.5.3           prettyunits_1.1.1        
#>  [31] tools_4.2.1               rsvd_1.0.5               
#>  [33] gtable_0.3.1              glue_1.6.2               
#>  [35] GenomeInfoDbData_1.2.9    reshape2_1.4.4           
#>  [37] Rcpp_1.0.9                jquerylib_0.1.4          
#>  [39] vctrs_0.5.0               nlme_3.1-160             
#>  [41] DelayedMatrixStats_1.20.0 xfun_0.34                
#>  [43] globals_0.16.1            beachmat_2.14.0          
#>  [45] lme4_1.1-31               irlba_2.3.5.1            
#>  [47] lifecycle_1.0.3           future_1.28.0            
#>  [49] zlibbioc_1.44.0           MASS_7.3-58.1            
#>  [51] scales_1.2.1              vroom_1.6.0              
#>  [53] hms_1.1.2                 parallel_4.2.1           
#>  [55] RColorBrewer_1.1-3        yaml_2.3.6               
#>  [57] gridExtra_2.3             sass_0.4.2               
#>  [59] stringi_1.7.8             highr_0.9                
#>  [61] ScaledMatrix_1.6.0        boot_1.3-28              
#>  [63] BiocParallel_1.32.0       rlang_1.0.6              
#>  [65] pkgconfig_2.0.3           bitops_1.0-7             
#>  [67] evaluate_0.17             lattice_0.20-45          
#>  [69] archive_1.1.5             labeling_0.4.2           
#>  [71] cowplot_1.1.1             bit_4.0.4                
#>  [73] tidyselect_1.2.0          parallelly_1.32.1        
#>  [75] plyr_1.8.7                magrittr_2.0.3           
#>  [77] bookdown_0.29             R6_2.5.1                 
#>  [79] magick_2.7.3              generics_0.1.3           
#>  [81] DelayedArray_0.24.0       DBI_1.1.3                
#>  [83] pillar_1.8.1              withr_2.5.0              
#>  [85] RCurl_1.98-1.9            tibble_3.1.8             
#>  [87] crayon_1.5.2              utf8_1.2.2               
#>  [89] tzdb_0.3.0                rmarkdown_2.17           
#>  [91] viridis_0.6.2             progress_1.2.2           
#>  [93] grid_4.2.1                forcats_0.5.2            
#>  [95] digest_0.6.30             munsell_0.5.0            
#>  [97] viridisLite_0.4.1         beeswarm_0.4.0           
#>  [99] vipor_0.4.5               bslib_0.4.0