Vignette built on r format(Sys.time(), "%b %d, %Y") with cisTopic version r packageVersion("cisTopic").

Installation

R < 3.5

If your R version is below 3.5, you will need to install manually the following packages:

devtools::install_github("aertslab/AUCell")
devtools::install_github("aertslab/RcisTarget")
source("https://bioconductor.org/biocLite.R")
biocLite('GenomicRanges')

cisTopic package

For installing cisTopic run:

devtools::install_github("aertslab/cisTopic")

Vignette packages

In this vignette, you will require additional packages:

source("https://bioconductor.org/biocLite.R")
biocLite(c('Rsubread', 'umap', 'Rtsne', 'ComplexHeatmap', 'fastcluster', 'data.table', 'rGREAT', 'ChIPseeker', 'TxDb.Hsapiens.UCSC.hg19.knownGene', 'org.Hs.eg.db'))

What is cisTopic?

cisTopic is an R/Bioconductor package for the simulataneous identification of cis-regulatory topics and cell states from single cell epigenomics data. cisTopic relies on an algorithm called Latent Dirichlet Allocation (LDA), a robust Bayesian method used in text mining to group documents addressing similar topics and related words into topics. Interestingly, this model has a series of assumptions that are fulfilled in single-cell epigenomics data, such as non-ordered features ('bag of words') and the allowance of overlapping topics (i.e. a regulatory region can be co-accessible with different other regions depending on the context, namely, the cell type or state).

cisTopic uses LDA with a collapsed Gibbs sampler (Griffiths & Steyvers, 2004), where each region in each cell is assigned to a topic based on (1) to which topic the region is assigned in other cells and (2) to which topics the regions are assigned in that cell. After a number of iterations through the data set, these assignments are used to estimate the probability of a region belonging to a cis-regulatory topic (region-topic distribution) and the contributions of a topic within each cell (topic-cell distribution). These distributions can in turn be used to cluster cells and identify cell types, and to analyse the regulatory sequences in each topic.

cisTopic consists of 4 main steps: (1) generation of a binary accessibility matrix as input for LDA; (2) LDA and model selection; (3) cell state identification using the topic-cell distributions from LDA and (4) exploration of the region-topic distributions.

Figure 1. cisTopic workflow. a. The input for cisTopic is a binary accessibility matrix. This matrix can be formed from single-cell BAM files and a set of genome-wide regulatory regions (e.g., from peak calling on the bulk or aggregate data). b. Latent Dirichlet Allocation (LDA) is applied on the binary accessibility matrix to obtain the topic-cell distributions (contributions of each topic per cell) and the region-topic distributions (contributions of each region to a topic). Note that a region can contribute to more than one topic (represented by the purple peaks). c. The topic-cell distributions are used for dimensionality reduction (e.g. PCA, tSNE, diffusion maps) and clustering to identify cell states. d. The region-topic distributions can be used to predict the regulatory code underlying the topic. For example, topics can be compared with known epigenomic signatures using a recovery curve approach; regions can be annotated and linked to genes; and, after topic binarisation, enriched motifs can be identified via RcisTarget.

If you do not want to run some of the steps in the tutorial, you can load the precomputed cisTopic object:

cisTopicObject <- readRDS('cisTopicObject_melanoma.Rds')

Running cisTopic

Input data

Some steps in this tutorial might take a few minutes to run, as reference we mention the running time for this dataset and settings in our system. Your actual running time will depend on your computer and dataset. In this tutorial, we will run cisTopic in 100 simulated epigenomes from bulk H3K27Ac melanoma cell line profiles (20 cells per line, using 3 melanocyte-like [MM001, MM011 and MM034] and 2 mesenchymal-like [MM029, MM047] cell lines). The coverage of these simulated cells is between 26,940 and 59,580 reads.

First, load cisTopic:

suppressWarnings(library(cisTopic))

The cisTopic object can be initialized either from (a) single cell epigenome profile bam files per cell and defined regulatory regions (e.g. from peak calling with MACS2 in the aggregate or bulk); or (b) a precomputed matrix with cells as columns, regions as cells and fragments/reads counts as values.

The cisTopic object contains all the information and outputs from the analysis. For more information, run:

?`cisTopic-class`

For initializing the cisTopic object:

pathToBams <- 'data/bamfiles/'
bamFiles <- paste(pathToBams, list.files(pathToBams), sep='')
regions <- 'data/regions.bed'
cisTopicObject <- createcisTopicObjectFromBAM(bamFiles, regions, project.name='scH3K27Ac_melanoma')

# If you want to rename cells
cell.names <- cisTopicObject@cell.names
new.cell.names <- sapply(strsplit(cell.names, split = ".", fixed=TRUE), "[", 3)
cisTopicObject <- renameCells(cisTopicObject, new.cell.names)
data(counts_mel) 
cisTopicObject <- createcisTopicObject(counts_mel, project.name='scH3K27Ac_melanoma')
rm(counts_mel)

By default, the slots @cell.data and @region.data will be initialized with the number of reads and accessible regions (depending on the selected threshold) per cell and region, respectively. Extra metadata can be added using the functions addCellMetadata (e.g. phenotype information) and addRegionMetadata. For example, in this case we are interested in adding information about the cell type of origin and the type of cell-line (Mesenchymal-like or Melanocyte-like).

data(cellData_mel)
cisTopicObject <- addCellMetadata(cisTopicObject, cell.data = cellData_mel)
rm(cellData_mel)

Building the models

The next step in the cisTopic workflow is to use Latent Dirichlet Allocation (LDA) for the modelling of cis-regulatory topics. LDA allows to derive, from the original high-dimensional and sparse data, (1) the probability distributions over the topics for each cell in the data set and (2) the probability distributions over the regions for each topic (Blei et al., 2003). These distributions indicate, respectively, how important a regulatory topic is for a cell, and how important regions are for the regulatory topic. Here, we use a collapsed Gibbs sampler (Griffiths and Steyvers, 2004), in which we assign regions to a certain topic by randomly sampling from a distribution where the probability of a region being assigned to a topic is proportional to the contributions of that region to the topic and the contributions of that topic in a cell.

To do this, runModels() builds several models (e.g. with diferent numbers of topics) using Latent Dirichlet Allocation (LDA) on the binary accessibility matrix (automatically stored in the initialized cisTopicObject). We can then select the best model using selectModel() and logLikelihoodByIter().

The main parameters for running the models (runModels) are:

NOTE: For large data sets it may not be feasible to keep all models simultaneously in memory. An alternative is to run the models and only save their likelihoods and the model with the highest likelihood (see the argument returnType in runModels). If after checking the likelihood plot another model is preferred, the function can be re-run only for that number of topics.

In this tutorial, we will test models with 2, 5 to 15, 20 and 25 topics [Reference running time for the example data set (100 cells; ~110,000 regions): 3 minutes].

cisTopicObject <- runModels(cisTopicObject, topic=c(2, 5:15, 20, 25), seed=987, nCores=13, burnin = 120, iterations = 150, addModels=FALSE)

Selection of the best model

The log likelihood can be used to estimate the plausibility of a model parameter value, given the observed data. selectModel will select the model with the highest log likelihood (P(D|T)) at the last iteration.

cisTopicObject <- selectModel(cisTopicObject)

This plot shows that a model with 10 topics is suitable. If two or more models have comparable log likelihoods, we recommend to pick the one with the lower number of topics (i.e. lower complexity). By default, this function selects the model with the highest likelihood, but the user can select a certain topic with the select parameter in this function. In cases were the topic selection is not clear, the user can rerun the models using a different seed to select the best number of topics. We will continue with the model with 10 topics.

Another way of visualizing the likelihood of the models is to plot their changes through the different iterations. It is important to check that the likelihood of the models is stabilised in the recording iterations, and the area under these curves can also be useful for model selection.

logLikelihoodByIter(cisTopicObject, select=c(2,5,10,15,20,25))

If the models are stabilized after burnin (grey line), we can conclude that the selection of the number of iterations and burnin was suitable.

Interpreting the models

A. Identification of cell states using the cell-cisTopic distributions

LDA returns two distributions that represent (1) the topic contributions per cell and (2) the region contribution to a topic. We can interpret these values as a dimensinality reduction method, after which the data is re-represented as a matrix with cells as columns, topics as rows and contributions as values. The recorded topic assignments to the cells (not normalised) are stored in cisTopicObject@selected.model$document_expects (see lda package).

Different methods can be used for clustering and/or visualization. cisTopic includes wrapper functions to easily run Umap, tSNE, diffussion maps and PCA (the results are saved in the slot @dr$cell):

cisTopicObject <- runUmap(cisTopicObject, target='cell')

Once calculations are done, cisTopic offers a unified visualization function (plotFeatures), which allows to visualize tSNE, diffussion maps, principal components and biplots (in 2/3D), colored by metadata and/or topic enrichment.

par(mfrow=c(1,3))
plotFeatures(cisTopicObject, method='Umap', target='cell', topic_contr=NULL, colorBy=c('cellLine', 'LineType','pct_ReadsInPeaks'), cex.legend = 0.8, factor.max=.75, dim=2, legend=TRUE, col.low='darkgreen', col.mid='yellow', col.high='brown1', intervals=20)

par(mfrow=c(2,5))
plotFeatures(cisTopicObject, method='Umap', target='cell', topic_contr='Probability', colorBy=NULL, cex.legend = 0.8, factor.max=.75, dim=2, legend=TRUE)

We can also generate a heatmap based on the cell-cisTopic distributions.

cellTopicHeatmap(cisTopicObject, method='Probability', colorBy=c('LineType', 'cellLine'))

- Enrichment of epigenomic signatures in the cells

By multiplying the cell and topic assignments, the likelihood of each region in each cell (i.e. predictive distribution). This matrix is stored in object@predictive.distribution. These distributions can be used to estimate drop-outs and build cell-specific region rankings that can be used with AUCell for estimating the enrichment of epigenomic signatures within the cells.

pred.matrix <- predictiveDistribution(cisTopicObject)

For example, we can evaluate which cells are more enriched for certain ChIP-seq signatures. First, epigenomic regions are intersected and mapped to regions in the dataset (by default, with at least 40% overlap). To test the enrichment of these signatures in each cell, we use a GSEA-like recovery curve ranking-based approach. In each cell, regions are ranked based on their probability (x-axis), and when a region is present in the signature we increase one step in the y-axis. The Area Under the Curve (AUC) is used to evaluate the importance of that signature within that cell. The corresponding overlapping sets (which are stored in object@signatures) are used as input, together with the cell-specific region rankings, for the function signatureCellEnrichment. AUC values for each specific signature are stored in object@cell.data.

# Obtain signatures
path_to_signatures <- 'data/ChIP-seq_signatures/'
ChIP_Seq_signatures <- paste(path_to_signatures, list.files(path_to_signatures), sep='')
labels  <- c('MITF', 'SOX10', 'TFAP2A')
cisTopicObject <- getSignaturesRegions(cisTopicObject, ChIP_Seq_signatures, labels=labels, minOverlap = 0.4)

# Compute cell rankings
library(AUCell)
aucellRankings <- AUCell_buildRankings(pred.matrix, plot=FALSE, verbose=FALSE)

# Check signature enrichment in cells
cisTopicObject <- signatureCellEnrichment(cisTopicObject, aucellRankings, selected.signatures='all', aucMaxRank = 0.1*nrow(aucellRankings), plot=FALSE)
# Plot
par(mfrow=c(2,2))
plotFeatures(cisTopicObject, method='Umap', target='cell', topic_contr=NULL, colorBy=c('LineType', 'MITF', 'SOX10', 'TFAP2A'), cex.legend = 0.8, factor.max=.75, dim=2, legend=TRUE, intervals=20)

NOTE: The predictive distributions and the AUCell rankings are not stored in the cisTopic object as they have a big size.

B. Analysis of the regulatory topics

- Defining topics

To analyze the regions included in the cisTopics, the first step is always to derive a score that evaluates how likely is for a region to belong to a topic. getRegionsScores() calculates these scores based on the proportion of region specific assignments to a topic. These scores can be rescaled into the range [0,1], which will be useful for the binarization step (as it will force data to follow a gamma distribution shape).

cisTopicObject <- getRegionsScores(cisTopicObject, method='NormTop', scale=TRUE)

BigWig files for observing the scored regions in the genome can be generated. Note that information on the length of the chromosomes has to be provided. These files can be uploaded in IGV or UCSC for visualisation. This information can be easily found in the TxDb objects of the corresponding genomes, for example.

library(TxDb.Hsapiens.UCSC.hg19.knownGene)
txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene

getBigwigFiles(cisTopicObject, path='output/cisTopics_asBW', seqlengths=seqlengths(txdb))

However, many tools are limited to work with sets of regions rather than rankings of regions. Keywords, or the most contributing regions in a topic, can be used as a representative set of regions of the topic. binarizecisTopics() allows to select the top regions based on two methods:

a) method = "Predefined": to select a predefined number of regions (determined by the cutoffs argument)

b) method = "GammaFit" (default): to automatically select a threshold based on a fit of the scores to a gamma distribution. This is recommended when using method="NormTop" and scale=TRUE in getRegionScores(). Note that the probability threshold must be provided by the user and it must be taken after the density (based on the fitted gamma distribution) is stabilised (i.e. in the tail of the distribution).

par(mfrow=c(2,5))
cisTopicObject <- binarizecisTopics(cisTopicObject, thrP=0.975, plot=TRUE)

The regions sets selected and distributions for each cisTopic can then be analized in different ways (examples in next sections). They can also be exported to bed files to analyze with external tools:

getBedFiles(cisTopicObject, path='output/cisTopics_asBed')

- Topic visualization

Based on the topic scores for each region, different methods can be used for clustering and/or visualization (as shown for cells). cisTopic includes wrapper functions to easily run Umap, tSNE, diffussion maps and PCA (the results are saved in the slot @dr$region). In the case of regions, only high confidence regions (i.e. that pass the binarization threshold at least in 1 topic) are used:

cisTopicObject <- runtSNE(cisTopicObject, target='region', perplexity=200, check_duplicates=FALSE)

The function plotFeatures can also be used to visualize region-based tSNEs, diffussion maps, principal components and biplots (in 2/3D), colored by metadata and/or topic enrichment.

par(mfrow=c(1,2))
plotFeatures(cisTopicObject, method='tSNE', target='region', topic_contr=NULL, colorBy=c('nCounts', 'nCells'), cex.legend = 0.8, factor.max=.75, dim=2, legend=TRUE, col.low='darkgreen', col.mid='yellow', col.high='brown1', intervals=10)

par(mfrow=c(2,5))
plotFeatures(cisTopicObject, method='tSNE', target='region', topic_contr='Probability', colorBy=NULL, cex.legend = 0.8, factor.max=.75, dim=2, legend=TRUE)

- Enrichment of epigenomic signatures

Another way of exploring the topics is to check their overlap (i.e. the regions included in the topics) with predefined epigenomic signatures/datasets. For example, regions from ChIP-seq can point towards enrichment of binding sites of a given TF, regions from FAIRE- or ATAC-seq to regions generally open in a given cell type or tissue, etc.

First, epigenomic regions are intersected and mapped to regions in the dataset (by default, with at least 40% overlap). To test the enrichment of these signatures in each cell, we use a GSEA-like recovery curve ranking-based approach. In each topic, regions are ranked based on their topic probability (x-axis), and when a region is present in the signature we increase one step in the y-axis. The Area Under the Curve (AUC) is used to evaluate the importance of that signature within that topic. Signatures are also saved in object@region.data as logical columns (TRUE if the region is in the signature, otherwise FALSE). A heatmap showing the enrichment scores for each topic and signature can be obtained with signaturesHeatmap.

# Obtain signatures (if it has not been run before)
path_to_signatures <- 'data/ChIP-seq_signatures/'
ChIP_Seq_signatures <- paste(path_to_signatures, list.files(path_to_signatures), sep='')
labels  <- c('MITF', 'SOX10', 'TFAP2A')
cisTopicObject <- getSignaturesRegions(cisTopicObject, ChIP_Seq_signatures, labels=labels, minOverlap = 0.4)

We can visualize how these regions are enriched within each topic with signaturesHeatmap. With this function, we obtain a heatmap showing the row normalised AUC scores.

signaturesHeatmap(cisTopicObject)

Alternatively, we can also visualize the regions that are contained in each signature in the dimensionality reduction plot. Note that in this case, we only consider the high confidence topic regions and not the entire topic distribution.

colVars <- list()
colors <- c(adjustcolor('grey', alpha.f=0.05), 'black')
names(colors) <- c('FALSE', 'TRUE')
colVars[['MITF']] <- colors
colVars[['SOX10']] <- colors
colVars[['TFAP2A']] <- colors

par(mfrow=c(1,3))
plotFeatures(cisTopicObject, method='tSNE', target='region', topic_contr=NULL, colorBy=c('MITF', 'SOX10', 'TFAP2A'), cex.legend = 0.8, factor.max=.75, dim=2, legend=TRUE, col.low='darkgreen', col.mid='yellow', col.high='brown1', intervals=20, colVars = colVars)

- Annotation to genes and GO terms

Another way of gaining insight on the topics is to link the regions to genes, and to determine GO terms (or pathways or any other type of gene-set) that are enriched within them. cisTopic provides the function annotateRegions() to annotate regions to GO terms using the "TxDb" Bioconductor packages (replace 'TxDb.Hsapiens.UCSC.hg19.knownGene' by the appropiate organism package), and annotation databases ("OrgDb" packages).

library(org.Hs.eg.db)
cisTopicObject <- annotateRegions(cisTopicObject, txdb=TxDb.Hsapiens.UCSC.hg19.knownGene, annoDb='org.Hs.eg.db')

As we saw before, we can use the region type annotations as region sets/signatures to check whether a topic is more enriched in a certain type of region.

par(mfrow=c(1,1))
signaturesHeatmap(cisTopicObject, selected.signatures = 'annotation')
plotFeatures(cisTopicObject, method='tSNE', target='region', topic_contr=NULL, colorBy=c('annotation'), cex.legend = 0.8, factor.max=.75, dim=2, legend=TRUE, intervals=20, colVars = colVars)

For identifying enriched GO terms per topic, cisTopic provides a wrapper over r "rGREAT" (Gu Z, 2017) [Reference running time: 10 minutes]. The binarised topics (i.e. sets of top regions per topic) are used in this step. Results are stored in object@binarized.rGREAT.

cisTopicObject <- GREAT(cisTopicObject, genome='hg19', fold_enrichment=2, geneHits=1, sign=0.05, request_interval=10)

We can visualize the enrichment results:

ontologyDotPlot(cisTopicObject, top=5, topics=c(1,10), var.y='name', order.by='Binom_Adjp_BH')

- (Transcription factor) motif enrichment

It is also possible to identify enriched motifs within the topics and form cistromes (i.e. sets of sequences enriched for a given motif). To do this, we use r "RcisTarget" (Aibar et al., 2017). The current version provides databases for human (hg19). You can find the region-based database at: https://resources.aertslab.org/cistarget/

For this analysis, we first need to convert the cisTopic regions to the regions in the databases ("ctx regions"). We can do this in two ways:

a) Binarised, converting the binarised topic to a set of equivalent ctx regions (a region can map to more than one ctx region, and all regions which overlap more than the given threshold are taken).

cisTopicObject <- binarizedcisTopicsToCtx(cisTopicObject, genome='hg19')

b) Based on the maximum overlap. This is useful if we need to use the scores (a region is mapped to its most overlapping ctx region). This information is stored in object@region.data.

cisTopicObject <- scoredRegionsToCtx(cisTopicObject, genome='hg19')

We are now ready to run RcisTarget in each topic using the wrapper function topicsRcisTarget(). This function uses the binarised topic regions converted to ctx regions [Reference running time: 7 minutes]

date()
pathToFeather <- "feather/hg19-regions-9species.all_regions.mc8nr.feather"
cisTopicObject <- topicsRcisTarget(cisTopicObject, genome='hg19', pathToFeather, reduced_database=FALSE, nesThreshold=3, rocthr=0.005, maxRank=20000, nCores=5)
date()

Once RcisTarget is run, interactive motif enrichment tables can be explored (e.g. per topic):

Topic10_motif_enr <- cisTopicObject@binarized.RcisTarget[[10]]
DT::datatable(Topic10_motif_enr[,-c("enrichedRegions", "TF_lowConf"), with=FALSE], escape = FALSE, filter="top", options=list(pageLength=5))
- Formation of cistromes

RcisTarget results can be used to form cistromes. We define a cistrome as a set of sequences enriched for motifs linked to a certain transcription factor. In the case of cisTopic, we build topic-specific cistromes. cisTopic produces 3 different types of cistromes: ctx-regions based, original-regions based and gene based (based on region annotation). The annotation parameter decides whether only motifs linked with high confidence should be used or also motifs indirectly annotated should be considered (i.e. in this case, the *_extended cistromes will contain both annotations) [Reference running time: 5 minutes]

cisTopicObject <- getCistromes(cisTopicObject, annotation = 'Both', nCores=5)

Cistromes are useful to compare regions linked to a TF which have different spatio-temporal patterns, which may be caused i.e. by the presence of co-factors or different concentrations of the TF. Importantly, we can also estimate and visualize the enrichment of these topic specific cistromes in the cells (as shown above). For example, below we show the different enrichment pattern of cell line-specific JUN regions.

# Compute AUC rankings based on the predictive distribution
pred.matrix <- predictiveDistribution(cisTopicObject)

library(AUCell)
aucellRankings <- AUCell_buildRankings(pred.matrix, plot=FALSE, verbose=FALSE)
cisTopicObject <- getCistromeEnrichment(cisTopicObject, topic=4, TFname='JUN', aucellRankings = aucellRankings, aucMaxRank = 0.05*nrow(aucellRankings), plot=FALSE)
cisTopicObject <- getCistromeEnrichment(cisTopicObject, topic=5, TFname='JUN', aucellRankings = aucellRankings, aucMaxRank = 0.05*nrow(aucellRankings), plot=FALSE)
par(mfrow=c(1,2))
plotFeatures(cisTopicObject, method='Umap', target='cell', topic_contr=NULL, colorBy=c('Topic4_JUN (519p)','Topic5_JUN (214p)'), cex.legend = 0.8, factor.max=.75, dim=2, legend=TRUE, intervals=20)

Differential motif enrichment can be performed using RSAT or Homer (Medina-Rivera et al, 2015; Heinz et al, 2017); and shape features can be modelled per sequence using GBshape bigwig files (Chiu et al., 2015). These features can be used as input to Machine Learning methods (i.e. Random Forest) to determine their relevance in generating the different patterns.

Finally, you can save your cisTopic object:

saveRDS(cisTopicObject, file='cisTopicObject_melanoma.Rds')

References

  1. Blei, D. M., Ng, A. Y., & Jordan, M. I. (2003). Latent dirichlet allocation. Journal of machine Learning research, 3(Jan), 993-1022.
  2. Steyvers, M., & Griffiths, T. (2007). Probabilistic topic models. Handbook of latent semantic analysis, 427(7), 424-440.
  3. Aibar, S., Bravo González-Blas, C., Moerman, T., Imrichova, H., Hulselmans, G., Rambow, F., ... & Atak, Z. K. (2017). SCENIC: single-cell regulatory network inference and clustering. Nature methods, 14(11), 1083.
  4. Medina-Rivera, A., Defrance, M., Sand, O., Herrmann, C., Castro-Mondragon, J. A., Delerce, J., ... & Staines, D. M. (2015). RSAT 2015: regulatory sequence analysis tools. Nucleic acids research, 43(W1), W50-W56.
  5. Heinz, S., Benner, C., Spann, N., Bertolino, E., Lin, Y. C., Laslo, P., ... & Glass, C. K. (2010). Simple combinations of lineage-determining transcription factors prime cis-regulatory elements required for macrophage and B cell identities. Molecular cell, 38(4), 576-589.
  6. Chiu, T. P., Yang, L., Zhou, T., Main, B. J., Parker, S. C., Nuzhdin, S. V., ... & Rohs, R. (2014). GBshape: a genome browser database for DNA shape annotations. Nucleic acids research, 43(D1), D103-D109.

SessionInfo

sessionInfo()


aertslab/cisTopic documentation built on April 6, 2024, 9:31 p.m.