Last updated: 2019-09-06

Checks: 7 0

Knit directory: BUSpaRse_notebooks/

This reproducible R Markdown analysis was created with workflowr (version 1.4.0). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20181214) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility. The version displayed above was the version of the Git repository at the time these results were generated.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    BUSpaRse_notebooks.Rproj
    Ignored:    data/fastqs/
    Ignored:    data/hgmm_100_fastqs.tar
    Ignored:    data/hgmm_1k_fastqs.tar
    Ignored:    data/hgmm_1k_v3_fastqs.tar
    Ignored:    data/hgmm_1k_v3_fastqs/
    Ignored:    data/hs_cdna.fa.gz
    Ignored:    data/mm_cdna.fa.gz
    Ignored:    data/mm_cdna97.fa.gz
    Ignored:    data/neuron_10k_v3_fastqs.tar
    Ignored:    data/neuron_10k_v3_fastqs/
    Ignored:    data/retina/
    Ignored:    data/whitelist_v2.txt
    Ignored:    data/whitelist_v3.txt
    Ignored:    output/hs_mm_tr_index.idx
    Ignored:    output/mm_cDNA_introns_97_collapse.idx
    Ignored:    output/mm_tr_index.idx
    Ignored:    output/mm_tr_index97.idx
    Ignored:    output/out_hgmm1k/
    Ignored:    output/out_hgmm1k_v3/
    Ignored:    output/out_retina/

Untracked files:
    Untracked:  analysis/dropseq_retina.Rmd
    Untracked:  output/neuron10k/
    Untracked:  output/neuron10k_collapse/
    Untracked:  output/tr2g_mm97.tsv

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the R Markdown and HTML files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view them.

File Version Author Date Message
Rmd 0546e85 Lambda Moses 2019-09-06 Updated for the new version of BUSpaRse
html cba7dc4 Lambda Moses 2019-08-27 Build site.
Rmd 3312497 Lambda Moses 2019-08-27 To be consistent with velocyto
html 9b05bd3 Lambda Moses 2019-08-22 Build site.
Rmd 1a1b473 Lambda Moses 2019-08-22 Forgot to update a paragraph explaining bash code
html 84f0381 Lambda Moses 2019-08-22 Build site.
Rmd 85be0ed Lambda Moses 2019-08-21 Updated for bustools 0.39.3 and newer development version of Seurat
html c3fe4dc Lambda Moses 2019-07-26 Build site.
Rmd 9904300 Lambda Moses 2019-07-26 Stuff users won’t see, but saves me time
html e0ec72a Lambda Moses 2019-07-26 Build site.
Rmd 54e66d4 Lambda Moses 2019-07-26 Added phase portraits and fixed some embarrasingly wrong bash chunks.
Rmd 342b3bf Lambda Moses 2019-07-26 Reran with Ensembl 97, fixed embarrasingly wrong bash chunks, and added phase portraits
html a3abb12 Lambda Moses 2019-07-25 Build site.
Rmd 28b6ed4 Lambda Moses 2019-07-25 Changed the embarrasing title
html 22204f9 Lambda Moses 2019-07-25 Build site.
Rmd 1bd5af5 Lambda Moses 2019-07-25 RNA velocity tutorial

In this notebook, we perform RNA velocity analysis on the 10x 10k neurons from an E18 mouse. Instead of the velocyto command line tool, we will use the kallisto | bus pipeline, which is much faster than velocyto, to quantify spliced and unspliced transcripts.

Setup

If you would like to rerun this notebook, you can git clone this repository or directly download this notebook from GitHub.

Install packages

This notebook demonstrates the use of command line tools kallisto and bustools. Please use kallisto >= 0.46, whose binary can be downloaded here. Also, please use bustools >= 0.39.3, whose binary of bustools can be found here. User interface of bustools has changed in version 0.39.3. For version 0.39.2, see earlier git commits of this notebook.

After you download the binary, you should decompress the file (if it is tar.gz) with tar -xzvf file.tar.gz in the bash terminal, and add the directory containing the binary to PATH by export PATH=$PATH:/foo/bar, where /foo/bar is the directory of interest. Then you can directly invoke the binary on the command line as we will do in this notebook.

We will be using the R packages below. BUSpaRse is not yet on CRAN or Bioconductor. For Mac users, see the installation note for BUSpaRse. BUSpaRse will be used to generate the transcript to gene file for bustools and to read output of bustools into R. We will also use Seurat version 3 which is now on CRAN. Recently, Satija lab announced SeuratWrappers, with which we can run RNA velocity directly from Seurat. SeuratWrappers is also GitHub only at present. We need to install velocyto.R, which is GitHub only, to compute and visualize RNA velocity after quantifying spliced and unspliced transcripts.

# Install devtools if it's not already installed
if (!require(devtools)) {
  install.packages("devtools")
}
# Install from GitHub
devtools::install_github("BUStools/BUSpaRse")
devtools::install_github("satijalab/seurat-wrappers")
devtools::install_github("velocyto-team/velocyto.R")

This vignette uses the version of DropletUtils from Bioconductor version 3.9; the version from Bioconductor 3.8 has a different user interface. If you are using a version of R older than 3.6.0 and want to rerun this vignette, then you can adapt the knee plot code to the older version of DropletUtils, or install DropletUtils from GitHub, which I did for this notebook. BSgenome.Mmusculus.UCSC.mm10 and AnnotationHub are also on Bioconductor. Bioconductor packages can be installed as such:

if (!require(BiocManager)) {
  install.packages("BiocManager")
}
BiocManager::install(c("DropletUtils", "BSgenome.Mmusculus.UCSC.mm10", "AnnotationHub"))

The other packages are on CRAN.

library(BUSpaRse)
library(Seurat)
library(SeuratWrappers)
library(BSgenome.Mmusculus.UCSC.mm10)
library(AnnotationHub)
library(zeallot) # For %<-% that unpacks lists in the Python manner
library(DropletUtils)
library(tidyverse)
library(uwot) # For umap
library(GGally) # For ggpairs
library(velocyto.R)
library(SingleR)
library(scales)
library(plotly)
theme_set(theme_bw())

Download data

The dataset we are using is 10x 10k neurons from an E18 mouse (almost 25 GB).

# Download data
if (!file.exists("./data/neuron_10k_v3_fastqs.tar")) {
  download.file("http://s3-us-west-2.amazonaws.com/10x.files/samples/cell-exp/3.0.0/neuron_10k_v3/neuron_10k_v3_fastqs.tar", "./data/neuron_10k_v3_fastqs.tar", method = "wget", quiet = TRUE)
}

Then untar the downloaded file.

cd ./data
tar -xvf ./neuron_10k_v3_fastqs.tar

Generate spliced and unspliced matrices

In order to know which reads come from spliced as opposed to unspliced transcripts, we need to see whether the reads contain intronic sequences. Thus we need to include intronic sequences in the kallisto index. This can be done with the BUSpaRse function get_velocity_files, which generates all files required to run RNA velocity with kallisto | bustools. First, we need a genome annotation to get intronic sequences. We can get genome annotation from GTF or GFF3 files from Ensembl with getGTF or getGFF from the R package biomartr, but Bioconductor provides genome annotations in its databases and package ecosystem as well. As of writing, the most recent version of Ensembl is 97. UCSC annotation can be obtained from Bioconductor package TxDb.Mmusculus.UCSC.mm10.knownGene.

# query AnnotationHub for mouse Ensembl annotation
ah <- AnnotationHub()
snapshotDate(): 2019-08-02
query(ah, pattern = c("Ensembl", "97", "Mus musculus", "EnsDb"))
AnnotationHub with 1 record
# snapshotDate(): 2019-08-02 
# names(): AH73905
# $dataprovider: Ensembl
# $species: Mus musculus
# $rdataclass: EnsDb
# $rdatadateadded: 2019-05-02
# $title: Ensembl 97 EnsDb for Mus musculus
# $description: Gene and protein annotations for Mus musculus based on ...
# $taxonomyid: 10090
# $genome: GRCm38
# $sourcetype: ensembl
# $sourceurl: http://www.ensembl.org
# $sourcesize: NA
# $tags: c("97", "AHEnsDbs", "Annotation", "EnsDb", "Ensembl",
#   "Gene", "Protein", "Transcript") 
# retrieve record with 'object[["AH73905"]]' 
# Get mouse Ensembl 97 annotation
edb <- ah[["AH73905"]]
downloading 0 resources
loading from cache
require("ensembldb")

Explaining the arguments of get_velocity_files:

  • X, the genome annotation, which is here edb. Here edb is an EnsDb object. Other allowed inputs are: a path to a GTF file, a GRanges object made from loading a GTF file into R, or a TxDb object (e.g. TxDb.Mmusculus.UCSC.mm10.knownGene).
  • L: Length of the biological read of the technology of interest. For 10x v1 and v2 chemistry, L is 98 nt, and for v3 chemistry, L is 91 nt. The length of flanking region around introns is L-1, to capture reads from nascent transcripts that partially map to intronic and exonic sequences.
  • Genome: Genome, either a DNAStringSet or BSgenome object. Genomes of Homo sapiens and common model organisms can also be easily obtained from Bioconductor. The one used in this notebook is from the package BSgenome.Mmusculus.UCSC.mm10. Alternatively, you can download genomes from Ensembl, RefSeq, or GenBank with biomartr::getGenome. Make sure that the annotation and the genome use the same genome version, which is here GRCm38 (mm10).
  • Transcriptome: While you may supply a transcriptome in the form of a path to a fasta file or a DNAStringSet, this is not required. The transcriptome can be extracted from the genome with the gene annotation. We recommend extracting the transcriptome from the genome, so the transcript IDs used in the transcriptome and the annotation (and importantly, in the tr2g.tsv file, explained later) are guaranteed to match. In this notebook, the transcriptome is not supplied and will be extracted from the genome.
  • isoform_action: There are two options regarding gene isoforms from alternative splicing or alternative transcription start or termination site. One is to get intronic sequences separately for each isoform, and another is to collapse all isoforms of a gene by taking the union of all exonic ranges of the gene. I’m not sure which way is better, but since in the case of alternative splicing, some intronic sequences of one isoform can actually be exonic sequences of another isoform, we will collapse isoforms here.
get_velocity_files(edb, L = 91, Genome = BSgenome.Mmusculus.UCSC.mm10, 
                   out_path = "./output/neuron10k_collapse", 
                   isoform_action = "collapse")

For regular gene count data, we build a kallisto index for cDNAs as reads are pseudoaligned to cDNAs. Here, for RNA velocity, as reads are pseudoaligned to the flanked intronic sequences in addition to the cDNAs, the flanked intronic sequences should also be part of the kallisto index. We advise you to run this step on a server, as it takes up to about 50 GB of memory and takes about an hour to run.

# Intron index
kallisto index -i ./output/mm_cDNA_introns_97_collapse.idx ./output/neuron10k_collapse/cDNA_introns.fa

The initial bus file is generated the same way as in regular gene count data, except with the cDNA + flanked intron index.

cd ./data/neuron_10k_v3_fastqs
kallisto bus -i ../../output/mm_cDNA_introns_97_collapse.idx \
-o ../../output/neuron10k_collapse -x 10xv3 -t8 \
neuron_10k_v3_S1_L002_R1_001.fastq.gz neuron_10k_v3_S1_L002_R2_001.fastq.gz \
neuron_10k_v3_S1_L001_R1_001.fastq.gz neuron_10k_v3_S1_L001_R2_001.fastq.gz

The most recent version of BUSpaRse ensures that all transcripts on the capture list are present in the transcriptome. Otherwise the output of bustools capture will be wrong. I hope that this will be fixed soon or will get a helpful error message.

A barcode whitelist of all valid barcode can be used, though is not strictly required. The 10x whitelist contains all barcodes from the kit. The 10x whitelist file comes with Cell Ranger installation, and is copies to the working directory of this notebook. For bustools, the whitelist must be a text file with one column, each row of which is a valid cell barcode. The text file must not be compressed.

cp ~/cellranger-3.0.2/cellranger-cs/3.0.2/lib/python/cellranger/barcodes/3M-february-2018.txt.gz \
./data/whitelist_v3.txt.gz
# Decompress
gunzip ./data/whitelist_v3.txt.gz

The bustools correct command checks the whitelist and can correct some barcodes not on the whitelist but might have been due to sequencing error or mutation. If you do not wish to use a whitelist, then you can skip bustools correct below and go straight to bustools sort. In bash, | is a pipe just like the magrittr pipe %>% in R. The - by the end of the bustools sort command indicates where what goes through the pipe goes, i.e. the output of bustools correct is becoming the input to bustools sort. -t4 means using 4 threads.

The bustools capture command determines what is from cDNA and what is from the flanked introns and generate two separate bus files. The -s flag specifies that transcripts are to be captured; bustools capture also supports barcodes (-b) and UMIs (-u). To be consistent with velocyto, here “spliced” reads are those not mapping to any flanked intronic regions (so can’t be spanning intron-exon junctions), and “unspliced” reads are those not mapping to any exclusively exonic regions. The -x flag is used to find the complement of the capture list (which is the argument to -c), so the complement to the intronic list gives us the “spliced” reads from the above criterion, and the complement to the exonic list gives us the “unspliced” reads from the above criterion.

cd ./output/neuron10k_collapse
bustools correct -w ../../data/whitelist_v3.txt -p output.bus | \
bustools sort -o output.correct.sort.bus -t4 -
bustools capture -s -x -o spliced.bus -c ./introns_tx_to_capture.txt -e matrix.ec -t transcripts.txt output.correct.sort.bus
bustools capture -s -x -o unspliced.bus -c ./cDNA_tx_to_capture.txt -e matrix.ec -t transcripts.txt output.correct.sort.bus

Unlike for just a gene count matrix, for RNA velocity, 2 matrices are generated. One for spliced transcripts, and the other for unspliced.

cd ./output/neuron10k_collapse
bustools count -o unspliced -g ./tr2g.tsv -e matrix.ec -t transcripts.txt --genecounts unspliced.bus
bustools count -o spliced -g ./tr2g.tsv -e matrix.ec -t transcripts.txt --genecounts spliced.bus

Preprocessing

Remove empty droplets

Now we have the spliced and unspliced matrices to be read into R:

c(spliced, unspliced) %<-% read_velocity_output(spliced_dir = "./output/neuron10k_collapse",
                                                spliced_name = "spliced",
                                                unspliced_dir = "./output/neuron10k_collapse",
                                                unspliced_name = "unspliced")

The %<-% from zeallot unpacks a list of 2 into 2 separate objects in the Python and Matlab manner. How many UMIs are from unspliced transcripts?

sum(unspliced@x) / (sum(unspliced@x) + sum(spliced@x))
[1] 0.3819906

In previous versions of this notebook, there were more unspliced counts than spliced counts. As part of an ongoing project, I converted the supposedly unspliced bus output into text and inspected it in R as a data frame. The output was wrong; there were still reads mapped to exclusively exonic regions in that bus file. However, the problem was fixed when I made sure that all transcripts in the capture list are also in the transcript list in the kallisto bus output, so the current version should be correct. However, this is still a higher proportion of unspliced counts. In contrast, for velocyto, the unspliced count is usually between 10% and 20% of the sum of spliced and unspliced. Perhaps this is because kallisto | bus counts reads that are partially intronic and partially exonic as unspliced while velocyto throws away many reads (see this GitHub issue).

We expect around 10,000 cells. There are over 10 times more barcodes here, since most barcodes are from empty droplets. The number of genes does not seem too outrageous.

dim(spliced)
[1]   55487 1221171
dim(unspliced)
[1]  55487 723370

Most barcodes only have 0 or 1 UMIs detected.

tot_count <- Matrix::colSums(spliced)
summary(tot_count)
    Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
    0.00     1.00     1.00    64.97     2.00 47215.00 

A commonly used method to estimate the number of empty droplets is barcode ranking knee and inflection points, as those are often assumed to represent transition between two components of a distribution. While more sophisticated methods exist (e.g. see emptyDrops in DropletUtils), for simplicity, we will use the barcode ranking method here. However, whichever way we go, we don’t have the ground truth. The spliced matrix is used for filtering, though both matrices have similar inflection points.

bc_rank <- barcodeRanks(spliced)
bc_uns <- barcodeRanks(unspliced)

Here the knee plot is transposed, because this is more generalizable to multi-modal data, such that those with not only RNA-seq but also abundance of cell surface markers. In that case, we can plot number of UMIs on the x axis, number of cell surface protein tags on the y axis, and barcode rank based on both UMI and protein tag counts on the z axis; it makes more sense to make barcode rank the dependent variable. See this blog post by Lior Pachter for a more detailed explanation.

tibble(rank = bc_rank$rank, total = bc_rank$total, matrix = "spliced") %>% 
  bind_rows(tibble(rank = bc_uns$rank, total = bc_uns$total, matrix = "unspliced")) %>% 
  distinct() %>% 
  ggplot(aes(total, rank, color = matrix)) +
  geom_line() +
  geom_vline(xintercept = metadata(bc_rank)$knee, color = "blue", linetype = 2) +
  geom_vline(xintercept = metadata(bc_rank)$inflection, color = "green", linetype = 2) +
  geom_vline(xintercept = metadata(bc_uns)$knee, color = "purple", linetype = 3) +
  geom_vline(xintercept = metadata(bc_uns)$inflection, color = "cyan", linetype = 3) +
  annotate("text", y = c(1000, 1000, 500, 500), 
           x = 1.5 * c(metadata(bc_rank)$knee, metadata(bc_rank)$inflection,
                       metadata(bc_uns)$knee, metadata(bc_uns)$inflectio),
           label = c("knee (s)", "inflection (s)", "knee (u)", "inflection (u)"), 
           color = c("blue", "green", "purple", "cyan")) +
  scale_x_log10() +
  scale_y_log10() +
  labs(y = "Rank", x = "Total UMI counts") +
  theme_bw()
Warning: Transformation introduced infinite values in continuous x-axis

Version Author Date
cba7dc4 Lambda Moses 2019-08-27
84f0381 Lambda Moses 2019-08-22
e0ec72a Lambda Moses 2019-07-26
22204f9 Lambda Moses 2019-07-25

Which inflection point should be used to remove what are supposed to be empty droplets? The one of the spliced matrix or the unspliced matrix?

Actually, spliced and unspliced counts are multimodal data, so why not make one of those promised 3D plots where the barcode rank depends on two variables? The rank (z axis) would now be the number cells with at least x spliced UMIs and y unspliced UMIs. How shall this be computed? The transposed knee plot (or rank-UMI plot) can be thought of as (1 - ECDF(total_UMI))*n_cells. In the ECDF of total UMI counts, the dependent variable is the proportion of cells with at most this number of distinct UMIs. So 1 minus that would mean the proportion of cells with at least this number of distinct UMIs. In the knee plot, the rank is the number of cells with at least this number of distinct UMIs. So dividing by the number of cells, we get 1 - ECDF(total_UMI). Would computing the 2D ECDF be more efficient than this naive approach? There is an R package that can compute bivariate ECDFs called Emcdf, but it uses so much memory that even our server can’t handle. I failed to find implementations of bivariate ECDFs in other languages. There is an algorithm based on range trees that can find multivariate ECDF efficiently.

Before obtaining a more efficient implementation, I used my naive approach that translates this concept into code very literally. Though I used Rcpp, it’s really slow. The trick to make it faster is to only evaluate how many cells have at least x spliced and y unspliced counts at a smaller number of grid points of x and y.

//[[Rcpp::depends(RcppProgress)]]
#include <progress.hpp>
#include <progress_bar.hpp>
#include <Rcpp.h>
using namespace Rcpp;

//[[Rcpp::export]]
NumericMatrix bc_ranks2(NumericVector x, NumericVector y, 
                        NumericVector x_grid, NumericVector y_grid) {
  NumericMatrix out(x_grid.size(), y_grid.size());
  Progress p(x_grid.size(), true);
  for (int i = 0; i < x_grid.size(); i++) {
    checkUserInterrupt();
    for (int j = 0; j < y_grid.size(); j++) {
      out(i,j) = sum((x_grid[i] <= x) & (y_grid[j] <= y));
    }
    p.increment();
  }
  return(out);
}

As most barcodes have a small number of distinct UMIs detected, the grid should be denser for fewer counts. Making the grid in log space achieves this.

# Can only plot barcodes with both spliced and unspliced counts
bcs_inter <- intersect(colnames(spliced), colnames(unspliced))
s <- colSums(spliced[,bcs_inter])
u <- colSums(unspliced[,bcs_inter])
# Grid points
sr <- sort(unique(exp(round(log(s)*100)/100)))
ur <- sort(unique(exp(round(log(u)*100)/100)))
# Run naive approach
bc2 <- bc_ranks2(s, u, sr, ur)

What would the “rank” look like?

# can't turn color to lot scale unless log values are plotted
z_use <- log10(bc2)
z_use[is.infinite(z_use)] <- NA
plot_ly(x = sr, y = ur, z = z_use) %>% add_surface() %>% 
  layout(scene = list(xaxis = list(title = "Total spliced UMIs", type = "log"),
                      yaxis = list(title = "Total unspliced UMIs", type = "log"),
                      zaxis = list(title = "Rank (log10)")))

Looks like it worked. This looks pretty symmetric as the rank-UMI plots for the spliced and unspliced matrices are pretty similar. How can this be used to decide what may be empty droplets? This worths some more thoughts. The surface might also need to be be smoothed for automated thresholding, just like in DropletUtils’s inflection method. For now, for simplicity, the inflection point for the spliced matrix will be used provisionally.

bcs_use <- colnames(spliced)[tot_count > metadata(bc_rank)$inflection]
# Remove genes that aren't detected
tot_genes <- Matrix::rowSums(spliced)
genes_use <- rownames(spliced)[tot_genes > 0]
sf <- spliced[genes_use, bcs_use]
uf <- unspliced[genes_use, bcs_use]
dim(sf)
[1] 24761 11066

Cell type annotation

SingleR uses bulk RNA-seq data of isolated known cell types as a reference to annotate cell types in scRNA-seq datasets. The reference uses gene symbols or names rather than Ensembl IDs.

# Get gene names
gns <- tr2g_EnsDb(edb)[,c("gene", "gene_name")] %>% 
  distinct()
data("mouse.rnaseq")
# Convert from gene symbols to Ensembl gene ID
ref_use <- mouse.rnaseq$data
rownames(ref_use) <- gns$gene[match(rownames(ref_use), gns$gene_name)]
ref_use <- ref_use[!is.na(rownames(ref_use)),]
annot <- SingleR("single", sf, ref_data = ref_use, types = mouse.rnaseq$types)

In order not to have cells not of the neural or glial lineages overshadow velocity visualization, only cells of the neural and glial lineages are kept.

ind <- annot$labels %in% c("NPCs", "Neurons", "OPCs", "Oligodendrocytes", 
                           "qNSCs", "aNSCs", "Astrocytes", "Ependymal")
cells_use <- annot$cell.names[ind]
sf <- sf[, cells_use]
uf <- uf[, cells_use]

Meaning of the acronyms:

  • NPCs: Neural progenitor cells
  • OPCs: Oligodendrocyte progenitor cells
  • qNSCs: Quiescent neural stem cells
  • aNSCs: Active neural stem cells

QC

Both the spliced and unspliced matrices are normalized and scaled with SCTransform, which is an alternative to NormalizeData, ScaleData, and FindVariableFeatures.

seu <- CreateSeuratObject(sf, assay = "sf") %>% 
  SCTransform(assay = "sf", new.assay.name = "spliced")
seu[["uf"]] <- CreateAssayObject(uf)
seu <- SCTransform(seu, assay = "uf", new.assay.name = "unspliced")
# Add cell type metadata
seu <- AddMetaData(seu, setNames(annot$labels[ind], cells_use), 
                   col.name = "cell_type")
cols_use <- c("nCount_sf", "nFeature_sf", "nCount_uf", "nFeature_uf")
VlnPlot(seu, cols_use, pt.size = 0.1, ncol = 1, group.by = "cell_type")

Version Author Date
84f0381 Lambda Moses 2019-08-22
e0ec72a Lambda Moses 2019-07-26

There’s only 1 cell labeled ependymal by SingleR. How does number of UMI counts relate to number of genes detected? How does number of UMI counts in the spliced matrix relate to the number of gene detected in the unspliced matrix?

# Helper functions for ggpairs
log10_diagonal <- function(data, mapping, ...) {
  ggally_densityDiag(data, mapping, ...) + scale_x_log10()
}
log10_points <- function(data, mapping, ...) {
  ggally_points(data, mapping, ...) + scale_x_log10() + scale_y_log10()
}
ggpairs(seu@meta.data, columns = cols_use,
        upper = list(continuous = "cor"),
        diag = list(continuous = log10_diagonal),
        lower = list(continuous = wrap(log10_points, alpha = 0.1, size=0.3)),
        progress = FALSE)

Version Author Date
cba7dc4 Lambda Moses 2019-08-27
84f0381 Lambda Moses 2019-08-22
e0ec72a Lambda Moses 2019-07-26
22204f9 Lambda Moses 2019-07-25

Dimension reduction

When visualizing RNA velocity on reduced dimensions, should the cell embeddings be from the spliced matrix or the unspliced matrix or the sum of both? In my opinion, it makes the most sense to plot RNA velocity over cell embeddings from the spliced matrix. The arrows in RNA velocity visualization stand for where the cell is predicted to be going in the near future. Where does the cell go from? The current state. And the current state is represented by the spliced matrix, while the unspliced matrix represents what is soon to come. Thus all the dimension reduction here will be computed from the spliced matrix.

DefaultAssay(seu) <- "spliced"
seu <- RunPCA(seu, verbose = FALSE, npcs = 70)
ElbowPlot(seu, ndims = 70)

Version Author Date
84f0381 Lambda Moses 2019-08-22
e0ec72a Lambda Moses 2019-07-26
22204f9 Lambda Moses 2019-07-25
# Need to use DimPlot due to weird workflowr problem with PCAPlot that calls seu[[wflow.build]]
# and eats up memory. I suspect this is due to the sys.call() in 
# Seurat:::SpecificDimPlot. 
DimPlot(seu, reduction = "pca",
        group.by = "cell_type", pt.size = 0.5, label = TRUE, repel = TRUE) +
  scale_color_brewer(type = "qual", palette = "Set2")
Warning: Using `as.character()` on a quosure is deprecated as of rlang 0.3.0.
Please use `as_label()` or `as_name()` instead.
This warning is displayed once per session.

Version Author Date
84f0381 Lambda Moses 2019-08-22
e0ec72a Lambda Moses 2019-07-26
22204f9 Lambda Moses 2019-07-25
seu <- RunTSNE(seu, dims = 1:50, verbose = FALSE)
DimPlot(seu, reduction = "tsne",
        group.by = "cell_type", pt.size = 0.5, label = TRUE, repel = TRUE) +
  scale_color_brewer(type = "qual", palette = "Set2")

Version Author Date
84f0381 Lambda Moses 2019-08-22
e0ec72a Lambda Moses 2019-07-26
22204f9 Lambda Moses 2019-07-25

This looks quite similar to the tSNE from gene count matrix of this same dataset, except rotated; see the slingshot notebook

In the most recent development version of Seurat, RunUMAP can use the R package uwot as the backend, thus obliterating calling Python UMAP through reticulate. On servers, reticulate does not work due to this issue.

seu <- RunUMAP(seu, dims = 1:50, umap.method = "uwot")
Warning: The default method for RunUMAP has changed from calling Python UMAP via reticulate to the R-native UWOT using the cosine metric
To use Python UMAP via reticulate, set umap.method to 'umap-learn' and metric to 'correlation'
This message will be shown once per session
12:20:32 Read 10718 rows and found 50 numeric columns
12:20:32 Using Annoy for neighbor search, n_neighbors = 30
12:20:32 Building Annoy index with metric = cosine, n_trees = 50
0%   10   20   30   40   50   60   70   80   90   100%
[----|----|----|----|----|----|----|----|----|----|
**************************************************|
12:20:34 Writing NN index file to temp file /tmp/RtmpD0UNE7/file1d9ec452ba473
12:20:34 Searching Annoy index using 1 thread, search_k = 3000
12:20:37 Annoy recall = 100%
12:20:39 Commencing smooth kNN distance calibration using 1 thread
12:20:41 Initializing from normalized Laplacian + noise
12:20:41 Commencing optimization for 200 epochs, with 434464 positive edges
12:20:52 Optimization finished
DimPlot(seu, reduction = "umap",
        group.by = "cell_type", pt.size = 0.5, label = TRUE, repel = TRUE) +
  scale_color_brewer(type = "qual", palette = "Set2")

Version Author Date
cba7dc4 Lambda Moses 2019-08-27
84f0381 Lambda Moses 2019-08-22
e0ec72a Lambda Moses 2019-07-26
22204f9 Lambda Moses 2019-07-25

As expected, qNSCs are on the one end , and neurons are on the other. Clustering should partition the big blob of NPCs that SingleR could not further partition due to limitations in the SingleR reference for mouse brains.

seu <- FindNeighbors(seu, verbose = FALSE) %>% 
  FindClusters(resolution = 1, verbose = FALSE) # Louvain
DimPlot(seu, pt.size = 0.5, reduction = "umap", label = TRUE)

Version Author Date
cba7dc4 Lambda Moses 2019-08-27
84f0381 Lambda Moses 2019-08-22
e0ec72a Lambda Moses 2019-07-26
22204f9 Lambda Moses 2019-07-25

RNA velocity

seu <- RunVelocity(seu, ncores = 10, reduction = "pca", verbose = FALSE)

Unfortunately, velocyto.R does not natively support ggplot2. This is a function that assigns colors to each cell in base R graphics.

cell_pal <- function(cell_cats, pal_fun) {
  categories <- sort(unique(cell_cats))
  pal <- setNames(pal_fun(length(categories)), categories)
  pal[cell_cats]
}

velocyto.R also requires that the vector of colors should have cell barcodes/IDs as names to match color to cell.

cell_colors <- cell_pal(seu$cell_type, brewer_pal("qual", "Set2"))
cell_colors_clust <- cell_pal(seu$seurat_clusters, hue_pal())
names(cell_colors) <- names(cell_colors_clust) <- colnames(sf)

Would a clean trajectory from qNSCs to NPCs to neurons be traced? The arrows are projected onto non-linear dimension reductions by correlation between the predicted cell state and gene expression of other cells in the dataset.

cc_umap <- show.velocity.on.embedding.cor(emb = Embeddings(seu, "umap"),
                                          vel = Tool(seu, slot = "RunVelocity"),
                                          n.cores = 50, show.grid.flow = TRUE,
                                          grid.n = 50, cell.colors = cell_colors,
                                          cex = 0.5, cell.border.alpha = 0,
                                          arrow.scale = 2, arrow.lwd = 0.75,
                                          xlab = "UMAP1", ylab = "UMAP2")

Version Author Date
cba7dc4 Lambda Moses 2019-08-27
84f0381 Lambda Moses 2019-08-22
c3fe4dc Lambda Moses 2019-07-26
22204f9 Lambda Moses 2019-07-25
knn ... transition probs ... done
calculating arrows ... done
grid estimates ... grid.sd= 0.287425  min.arrow.size= 0.0057485  max.grid.arrow.length= 0.03662748  done

This presents a much more complicated picture. The cells labeled qNSCs are at the bottom right. The more mature neurons also seem to be changing a lot. This step is computationally expensive; in subsequent calls to show.velocity.on.embedding.cor for the same dimension reduction, the expensive part can be bypassed by supplying the output of the first call.

show.velocity.on.embedding.cor(emb = Embeddings(seu, "umap"),
                               vel = Tool(seu, slot = "RunVelocity"),
                               n.cores = 50, show.grid.flow = TRUE,
                               grid.n = 50, cell.colors = cell_colors_clust,
                               cex = 0.5, cell.border.alpha = 0,
                               arrow.scale = 2, arrow.lwd = 0.75, 
                               cc = cc_umap$cc,
                               xlab = "UMAP1", ylab = "UMAP2")

Version Author Date
cba7dc4 Lambda Moses 2019-08-27
84f0381 Lambda Moses 2019-08-22
e0ec72a Lambda Moses 2019-07-26
22204f9 Lambda Moses 2019-07-25
knn ... transition probs ... done
calculating arrows ... done
grid estimates ... grid.sd= 0.287425  min.arrow.size= 0.0057485  max.grid.arrow.length= 0.03662748  done

qNSCs and closely related astrocytes are in the cluster at the bottom right of this plot. This picture is mostly consistent with going from qNSCs to neurons, though manual cell type annotation would be helpful.

Phase portraits

Let’s look at phase portraits of some genes:

gene.relative.velocity.estimates(GetAssayData(seu, slot = "data", assay = "spliced"),
                                 GetAssayData(seu, slot = "data", assay = "unspliced"),
                                 cell.emb = Embeddings(seu, "umap"),
                                 show.gene = gns$gene[gns$gene_name == "Mef2c"],
                                 old.fit = Tool(seu, slot = "RunVelocity"),
                                 cell.colors = cell_colors)
calculating convolved matrices ... done

Version Author Date
cba7dc4 Lambda Moses 2019-08-27
84f0381 Lambda Moses 2019-08-22
e0ec72a Lambda Moses 2019-07-26
[1] 1

This is Mef2c (myocyte enhancer factor 2C), which is highly expressed in the mouse adult cortex though not much in the embryonic CNS until E18, according to the NCBI page of this gene. In this dataset, it’s more highly expressed among a subset of cells labeled neurons and those close to those neurons. However, it seems that it’s close to steady state (the line in panel 3, the phase portrait); in most cells there aren’t much more or fewer unspliced than spliced transcripts, but it seems to be below steady state for neurons, meaning that the gene is downregulated in those cells.

gene.relative.velocity.estimates(GetAssayData(seu, slot = "data", assay = "spliced"),
                                 GetAssayData(seu, slot = "data", assay = "unspliced"),
                                 cell.emb = Embeddings(seu, "umap"),
                                 show.gene = gns$gene[gns$gene_name == "Fabp7"],
                                 old.fit = Tool(seu, slot = "RunVelocity"),
                                 cell.colors = cell_colors)
calculating convolved matrices ... done

Version Author Date
cba7dc4 Lambda Moses 2019-08-27
84f0381 Lambda Moses 2019-08-22
e0ec72a Lambda Moses 2019-07-26
[1] 1

This is Fabp7 (fatty acid binding protein 7). It’s highly expressed in the mouse embryonic CNS, though much less so in adult CNS, according to the NCBI page of this gene. In this dataset, it’s highly expressed in the cells close to qNSCs, i.e. those in earlier stages of differentiation. The line in the third panel representing the steady state was fitted with the lower and upper extremes of the plot in case of departure from steady state. Here we see many cells below the putative steady state, downregulated and with fewer unspliced transcripts than expected. The fourth panel is the residual of the fit in the third panel, with red for positive and blue for negative. It seems that some cells with many spliced counts for this gene has fewer than “steady state” counts of unspliced counts.

gene.relative.velocity.estimates(GetAssayData(seu, slot = "data", assay = "spliced"),
                                 GetAssayData(seu, slot = "data", assay = "unspliced"),
                                 cell.emb = Embeddings(seu, "umap"),
                                 show.gene = gns$gene[gns$gene_name == "Arpp21"],
                                 old.fit = Tool(seu, slot = "RunVelocity"),
                                 cell.colors = cell_colors)
calculating convolved matrices ... done

Version Author Date
cba7dc4 Lambda Moses 2019-08-27
84f0381 Lambda Moses 2019-08-22
e0ec72a Lambda Moses 2019-07-26
[1] 1

This is Arpp21 (cyclic AMP-regulated phosphoprotein, 21), which according to ENCODE RNA-seq data, is increasingly expressed in the mouse CNS through development. Here most cells are above the line that is the putative steady state, meaning that this gene is upregulated, which is consistent with the ENCODE data.


sessionInfo()
R version 3.6.0 (2019-04-26)
Platform: x86_64-redhat-linux-gnu (64-bit)
Running under: CentOS Linux 7 (Core)

Matrix products: default
BLAS/LAPACK: /usr/lib64/R/lib/libRblas.so

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [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    parallel  stats     graphics  grDevices utils     datasets 
[8] methods   base     

other attached packages:
 [1] ensembldb_2.9.5                    AnnotationFilter_1.9.0            
 [3] GenomicFeatures_1.37.4             AnnotationDbi_1.47.1              
 [5] plotly_4.9.0                       scales_1.0.0                      
 [7] SingleR_1.0.1                      velocyto.R_0.6                    
 [9] GGally_1.4.0                       uwot_0.1.3                        
[11] Matrix_1.2-17                      forcats_0.4.0                     
[13] stringr_1.4.0                      dplyr_0.8.3                       
[15] purrr_0.3.2                        readr_1.3.1                       
[17] tidyr_0.8.3                        tibble_2.1.3                      
[19] ggplot2_3.2.1                      tidyverse_1.2.1                   
[21] DropletUtils_1.5.7                 SingleCellExperiment_1.7.7        
[23] SummarizedExperiment_1.15.8        DelayedArray_0.11.4               
[25] BiocParallel_1.19.2                matrixStats_0.54.0                
[27] Biobase_2.45.0                     zeallot_0.1.0                     
[29] AnnotationHub_2.17.7               BiocFileCache_1.9.1               
[31] dbplyr_1.4.2                       BSgenome.Mmusculus.UCSC.mm10_1.4.0
[33] BSgenome_1.53.1                    rtracklayer_1.45.4                
[35] Biostrings_2.53.2                  XVector_0.25.0                    
[37] GenomicRanges_1.37.14              GenomeInfoDb_1.21.1               
[39] IRanges_2.19.14                    S4Vectors_0.23.20                 
[41] BiocGenerics_0.31.5                SeuratWrappers_0.1.0              
[43] Seurat_3.1.0                       BUSpaRse_0.99.23                  

loaded via a namespace (and not attached):
  [1] rappdirs_0.3.1                R.methodsS3_1.7.1            
  [3] bit64_0.9-7                   knitr_1.24                   
  [5] irlba_2.3.3                   R.utils_2.9.0                
  [7] data.table_1.12.2             doParallel_1.0.15            
  [9] RCurl_1.95-4.12               generics_0.0.2               
 [11] metap_1.1                     cowplot_1.0.0                
 [13] RSQLite_2.1.2                 RANN_2.6.1                   
 [15] future_1.14.0                 bit_1.1-14                   
 [17] xml2_1.2.2                    lubridate_1.7.4              
 [19] httpuv_1.5.1                  assertthat_0.2.1             
 [21] xfun_0.9                      hms_0.5.1                    
 [23] evaluate_0.14                 promises_1.0.1               
 [25] progress_1.2.2                caTools_1.17.1.2             
 [27] readxl_1.3.1                  igraph_1.2.4.1               
 [29] DBI_1.0.0                     geneplotter_1.63.0           
 [31] htmlwidgets_1.3               reshape_0.8.8                
 [33] RSpectra_0.15-0               crosstalk_1.0.0              
 [35] backports_1.1.4               annotate_1.63.0              
 [37] gbRd_0.4-11                   RcppParallel_4.4.3           
 [39] biomaRt_2.41.8                vctrs_0.2.0                  
 [41] remotes_2.1.0                 ROCR_1.0-7                   
 [43] withr_2.1.2                   doFuture_0.8.1               
 [45] sctransform_0.2.0             GenomicAlignments_1.21.5     
 [47] prettyunits_1.0.2             RcppProgress_0.4.1           
 [49] cluster_2.1.0                 ape_5.3                      
 [51] lazyeval_0.2.2                crayon_1.3.4                 
 [53] labeling_0.3                  edgeR_3.27.12                
 [55] pkgconfig_2.0.2               nlme_3.1-141                 
 [57] ProtGenerics_1.17.4           rlang_0.4.0                  
 [59] globals_0.12.4                modelr_0.1.5                 
 [61] rsvd_1.0.2                    cellranger_1.1.0             
 [63] rprojroot_1.3-2               GSVA_1.33.1                  
 [65] lmtest_0.9-37                 graph_1.63.0                 
 [67] singscore_1.5.0               Rhdf5lib_1.7.4               
 [69] zoo_1.8-6                     whisker_0.3-2                
 [71] ggridges_0.5.1                pheatmap_1.0.12              
 [73] png_0.1-7                     viridisLite_0.3.0            
 [75] bitops_1.0-6                  R.oo_1.22.0                  
 [77] KernSmooth_2.23-15            blob_1.2.0                   
 [79] workflowr_1.4.0               memoise_1.1.0                
 [81] GSEABase_1.47.0               magrittr_1.5                 
 [83] plyr_1.8.4                    ica_1.0-2                    
 [85] gplots_3.0.1.1                bibtex_0.4.2                 
 [87] gdata_2.18.0                  zlibbioc_1.31.0              
 [89] compiler_3.6.0                lsei_1.2-0                   
 [91] dqrng_0.2.1                   RColorBrewer_1.1-2           
 [93] pcaMethods_1.77.0             fitdistrplus_1.0-14          
 [95] Rsamtools_2.1.3               cli_1.1.0                    
 [97] listenv_0.7.0                 pbapply_1.4-1                
 [99] MASS_7.3-51.4                 mgcv_1.8-28                  
[101] tidyselect_0.2.5              stringi_1.4.3                
[103] yaml_2.2.0                    askpass_1.1                  
[105] locfit_1.5-9.1                ggrepel_0.8.1                
[107] pbmcapply_1.5.0               grid_3.6.0                   
[109] tools_3.6.0                   future.apply_1.3.0           
[111] rstudioapi_0.10               foreach_1.4.7                
[113] git2r_0.26.1                  outliers_0.14                
[115] gridExtra_2.3                 plyranges_1.5.12             
[117] Rtsne_0.15                    digest_0.6.20                
[119] BiocManager_1.30.4            shiny_1.3.2                  
[121] Rcpp_1.0.2                    broom_0.5.2                  
[123] SDMTools_1.1-221.1            later_0.8.0                  
[125] RcppAnnoy_0.0.12              httr_1.4.1                   
[127] npsurv_0.4-0                  Rdpack_0.11-0                
[129] colorspace_1.4-1              rvest_0.3.4                  
[131] XML_3.98-1.20                 fs_1.3.1                     
[133] reticulate_1.13               splines_3.6.0                
[135] shinythemes_1.1.2             xtable_1.8-4                 
[137] jsonlite_1.6                  R6_2.4.0                     
[139] pillar_1.4.2                  htmltools_0.3.6              
[141] mime_0.7                      glue_1.3.1                   
[143] interactiveDisplayBase_1.23.0 codetools_0.2-16             
[145] tsne_0.1-3                    lattice_0.20-38              
[147] curl_4.0                      leiden_0.3.1                 
[149] gtools_3.8.1                  openssl_1.4.1                
[151] survival_2.44-1.1             limma_3.41.15                
[153] rmarkdown_1.15                munsell_0.5.0                
[155] rhdf5_2.29.0                  GenomeInfoDbData_1.2.1       
[157] iterators_1.0.12              HDF5Array_1.13.5             
[159] haven_2.1.1                   reshape2_1.4.3               
[161] gtable_0.3.0