knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
The R package, nebula, provides fast algorithms for fitting negative binomial and Poisson mixed models for analyzing large-scale multi-subject single-cell data. The package nebula accounts for the hierarchical structure of the data by decomposing the total overdispersion into between-subject and within-subject components using a negative binomial mixed model (NBMM). The package nebula can be used for e.g., identifying marker genes, testing treatment effects, detecting genes with differentail expression, and performing cell-level co-expression analysis.
More details can be found in the manuscript "NEBULA: a fast negative binomial mixed model for differential expression and co-expression analyses of large-scale multi-subject single-cell data" (https://www.nature.com/articles/s42003-021-02146-6).
To install the lastest version from github:
install.packages("devtools") library(devtools) install_github("lhe17/nebula")
To install the lastest version from R-forge:
install.packages("nebula", repos="http://R-Forge.R-project.org")
Because the package nebula uses the R package Rfast, the installation process may first install Rfast, which requires that GSL is installed or available in the environment.
The installation has been tested on R-3.6 and R-3.5. Please contact liang.he@duke.edu for more information.
The current version provides the following functions.
nebula
: performs an association analysis using NBMMs given a count matrix and subject IDs.group_cell
: reorders cells to group them by the subject IDs.We use an example data set to illustrate how to use nebula to perform an association analysis of multi-subject single-cell data. The example data set attached to the R package can be loaded as follows.
library(nebula) data(sample_data)
The example data set includes a count matrix of 6030 cells and 10 genes from 30 subjects.
dim(sample_data$count)
The count matrix can be a matrix object or a sparse dgCMatrix object. The elements should be integers.
sample_data$count[1:5,1:5]
The subject IDs of each cell are stored in sample_data$sid
. The subject IDs can be a character or numeric vector, the length of which should equal the number of cells.
head(sample_data$sid) table(sample_data$sid)
The next step is to build a design matrix for the predictors. The example data set includes a data frame consisting of three predictors stored in sample_data$pred
. To build the design matrix, we can use the function model.matrix
. The intercept term must be included in the design matrix.
head(sample_data$pred) df = model.matrix(~X1+X2+cc, data=sample_data$pred) head(df)
The association analysis between the gene expression and the predictors can then be conducted using the function nebula
. The count matrix is an M by N matrix, where M is the number of genes, and N is the number of cells.
re = nebula(sample_data$count,sample_data$sid,pred=df) re
The function by default fitted the negative binomial gamma mixed model (NBGMM) for each of the genes, and return a list of summary statistics including the fold change, p-values, and both subject-level and cell-level overdispersions ($\sigma^2$ and $\phi^{-1}$). The cells need to be grouped by the subjects (that is, the cells of the same subject should be placed consecutively) before using as the input to the nebula
function. If the cells are not grouped, the group_cell
function can be used to first reorder the cells, as shwon below. If a scaling factor is specified by the user, it should also be included in group_cell
. If the cells are already grouped, group_cell
will return NULL.
data_g = group_cell(count=sample_data$count,id=sample_data$sid,pred=df) re = nebula(data_g$count,data_g$id,pred=data_g$pred)
If pred
is not specified, nebula
will fit the model with an intecept term by default. This can be used when only the overdispersions are of interest.
The scaling factor for each cell is specified in nebula
using the argument offset
. The argument offset
has to be a positive vector of length N. Note that log(offset
) will be the offset term in the NBMM. If not specified, nebula
will set offset
as 1 by default, which means that each cell is treated equally. Common scaling factors include the library size of a cell or a normalizing factor adjusted using e.g., TMM.
re = nebula(sample_data$count,sample_data$sid,pred=df,offset=sample_data$offset)
In nebula, a user can choose one of the two algorithms to fit an NBMM. NEBULA-LN uses an approximated likelihood based on the law of large numbers, and NEBULA-HL uses an h-likelihood. A user can select these methods through method='LN'
or method='HL'
. NEBULA-LN is faster and performs particularly well when the number of cells per subject (CPS) is large. In the following analysis of the example data set comprising ~200 cells per subject, the difference of the estimated cell-level overdispersions between NEBULA-LN and NEBULA-HL is ~5% for most genes.
re_ln = nebula(sample_data$count,sample_data$sid,pred=df,offset=sample_data$offset,method='LN') re_hl = nebula(sample_data$count,sample_data$sid,pred=df,offset=sample_data$offset,method='HL') ## compare the estimated overdispersions cbind(re_hl$overdispersion,re_ln$overdispersion)
Such difference has little impact on testing fixed-effects predictors under this sample size.
## compare the p-values for testing the predictors using NEBULA-LN and NEBULA-HL cbind(re_hl$summary[,10:12],re_ln$summary[,10:12])
The bias of NEBULA-LN in estimating the cell-level overdispersion gets larger when the CPS value becomes lower or the gene expression is more sparse. If the CPS value is <30, nebula
will set method='HL'
regardless of the user's input. In contrast, NEBULA-HL is slower, but its accuracy of estimating the overdispersions depends less on these factors.
When NEBULA-LN is used, the user can opt for better accuracy of estimating a smaller subject-level overdispersion through the argument $\kappa$. NEBULA first fits the data using NEBULA-LN. If the estimated $\kappa$ for a gene is smaller than the user-defined value, NEBULA-HL will be used to estimate the subject-level overdispersion for the gene. The default value of $\kappa$ is 800, which can provide a good estimate of the subject-level overdispersion as low as ~0.005. Our simulation results suggest that $\kappa=200$ is often sufficent for achieving a well controlled false positive rate of testing a cell-level predictor. We do not recommend using a smaller $\kappa$ than 200. Specifying a larger $\kappa$ can obtain a more accurate estimate of a smaller subject-level overdispersion when the cell-level overdispersion is large, but will be computationally slower. On the other hand, testing a subject-level predictor (i.e., a variable whose values are shared across all cells from a subject, such as age, sex, treatment, genotype, etc) is more sensitive to the accuracy of the estimated subject-level overdispersion. So we recommend using $\kappa=800$ (as default) or even larger when testing a subject-level predictor. Another option to testing a subject-level predictor is to use a Poisson gamma mixed model, which is extremely fast (>50x faster than NEBULA-LN) and will be described below.
NEBULA-HL automatically uses a higher-order Laplace approximation for low-expressed genes of which the average count per subject is less than 3. The higher-order Laplace approximation substantailly increases the accuracy for estimating the subject-level overdispersion for low-expressed genes and controls the false positive rate. Nevertheless, we recommend removing genes with very low expression from the analysis because there is little statistical power for these genes. Filtering out low-expressed genes can be specified by cpc=0.005
(i.e., counts per cell<0.5%). The argument cpc
is defined by the ratio between the total count of the gene and the number of cells.
nebula reports convergence information about the estimation algorithm for each gene along with the summary statistics. This is useful and important information for quality control to filter out genes of which the estimation procedure potentially does not converge. Generally, a convergence code <= -20 suggests that the algorithm does not converge well. If the convergence code is -30, which indicates a failure of convergence, their summary statistics should NOT be used. If the convergence code is -20 or -40, it indicates that the optimization algorithm stops at the maximum step limit before the complete convergence. The results should be interpreted with caution in this case. The failure of convergence may occur when the sample size is very small, there are too few positive counts, or the gene has huge overdispersions, in which case the likelihood is flat or the optimization is sensitive to the initial values. For those genes that have a bad convergence code, in many cases, trying a different negative binomial mixed model (e.g., NBLMM, see below for more details) may solve the problem.
In addition to the NBGMM, the nebula package provides efficient estimation implementation for a Poisson gamma mixed model and a negative binomial lognormal mixed model (NBLMM). This can be specified through model="PMM"
and model="NBLMM"
, respectively. The NBLMM is the same model as that adopted in the glmer.nb
function in the lme4 R package, but is computationally much more efficient by setting method='LN'
. The only difference between NBGMM and NBLMM is that NBGMM uses a gamma distribution for the random effects while the NBLMM uses a lognormal distribution. The PMM is the fastest among these models. Note that the Poisson mixed model (PMM) should not be used to test a cell-level predictor because it only estimates the subject-level overdispersion. Here is an example of using the PMM to fit the example data set.
re = nebula(sample_data$count,sample_data$sid,pred=df,offset=sample_data$offset,model='PMM')
knitr::kable(re$summary)
In some situations, a user may want to test a combination (contrast) of the log(FC) or perform a global test for multiple variables or levels. For example, a user may want to test whether the log(FC) of two variables are the same. Here, we show how nebula
can be used for this kind of analysis.
The first step is to tell nebula
to output the covariance matrix of the estimated log(FC). This can be done by specifying covariance=TRUE
in nebula
. To save storage, the covariance returned by nebula
only contains the elements in the lower triangular part including the diagonal. Here is an example to recover the covariance matrix from the output of nebula
.
df = model.matrix(~X1+X2+cc, data=sample_data$pred) re_ln = nebula(sample_data$count,sample_data$sid,pred=df,offset=sample_data$offset,method='LN',covariance=TRUE) cov= matrix(NA,4,4) cov[lower.tri(cov,diag=T)] = as.numeric(re_ln$covariance[1,]) cov[upper.tri(cov)] = t(cov)[upper.tri(cov)] cov
Note that if there are K variables, the covariance table in the output will have (K+1)K/2 columns. So, for a large K, substantial increase of computational intensity should be expected.
The second step is to build the contrast vector for your hypothesis. In this example, we want to test whether the log(FC) of X1 and cccontrol are equal for the first gene. This hypothesis leads to the contrast vector (0 1 -1 0)
. Thus, the test can be performed
using the following code.
df = model.matrix(~X1+X2+cc, data=sample_data$pred) ## the gene to test gene_i = 1 ## output covariance re_ln = nebula(sample_data$count,sample_data$sid,pred=df,offset=sample_data$offset,method='LN',covariance=TRUE) ## recover the covariance matrix cov= matrix(NA,4,4) cov[lower.tri(cov,diag=T)] = as.numeric(re_ln$covariance[gene_i,]) cov[upper.tri(cov)] = t(cov)[upper.tri(cov)] ## build the contrast vector contrast = c(0,1,-1,0) ## testing the hypothesis eff = sum(contrast*re_ln$summary[gene_i,1:4]) p = pchisq(eff^2/(t(contrast)%*%cov%*%contrast),1,lower.tail=FALSE) p
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.