├── data ├── sim.rda └── kidneyTabulaMuris.rda ├── genesorteR.pdf ├── R ├── sim.R ├── kidneyTabulaMuris.R ├── plotMarkerScores.R ├── plotCorrelationHeat.R ├── write.files.R ├── plotTopMarkerHeat.R ├── plotTopBinaryHeat.R ├── getTable.R ├── getClassAUC.R ├── getMarkers.R ├── getPValues.R ├── bkend.R ├── plotBinaryHeat.R ├── plotMarkerHeat.R └── sortGenes.R ├── man ├── sim.Rd ├── kidneyTabulaMuris.Rd ├── plotMarkerScores.Rd ├── write.files.Rd ├── plotCorrelationHeat.Rd ├── plotTopBinaryHeat.Rd ├── getTable.Rd ├── plotTopMarkerHeat.Rd ├── getClassAUC.Rd ├── getMarkers.Rd ├── getPValues.Rd ├── plotBinaryHeat.Rd ├── plotMarkerHeat.Rd └── sortGenes.Rd ├── NAMESPACE ├── DESCRIPTION ├── README.md └── LICENSE /data/sim.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mahmoudibrahim/genesorteR/HEAD/data/sim.rda -------------------------------------------------------------------------------- /genesorteR.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mahmoudibrahim/genesorteR/HEAD/genesorteR.pdf -------------------------------------------------------------------------------- /data/kidneyTabulaMuris.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mahmoudibrahim/genesorteR/HEAD/data/kidneyTabulaMuris.rda -------------------------------------------------------------------------------- /R/sim.R: -------------------------------------------------------------------------------- 1 | #' Simulated single cell RNA-seq data with 500 cells. 2 | #' 3 | #' A simulated dataset containing 500 cells and 3999 genes. There are two 4 | #' cell types, one with 245 cells and the other with 255 cells. 5 | #' 6 | #' @format A list with two components: 7 | #' \describe{\item{exp}{Gene expression matrix, with raw counts. Rows are genes, columns are cells} \item{cellType}{A numeric vector containing the cell types}} 8 | "sim" 9 | -------------------------------------------------------------------------------- /man/sim.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sim.R 3 | \docType{data} 4 | \name{sim} 5 | \alias{sim} 6 | \title{Simulated single cell RNA-seq data with 500 cells.} 7 | \format{ 8 | A list with two components: 9 | \describe{\item{exp}{Gene expression matrix, with raw counts. Rows are genes, columns are cells} \item{cellType}{A numeric vector containing the cell types}} 10 | } 11 | \usage{ 12 | sim 13 | } 14 | \description{ 15 | A simulated dataset containing 500 cells and 3999 genes. There are two 16 | cell types, one with 245 cells and the other with 255 cells. 17 | } 18 | \keyword{datasets} 19 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | export(getClassAUC) 2 | export(getMarkers) 3 | export(getPValues) 4 | export(plotCorrelationHeat) 5 | export(plotMarkerHeat) 6 | export(plotTopMarkerHeat) 7 | export(plotBinaryHeat) 8 | export(plotTopBinaryHeat) 9 | export(plotMarkerScores) 10 | export(sortGenes) 11 | export(getTable) 12 | export(write.files) 13 | 14 | importFrom("grDevices", "colorRampPalette") 15 | importFrom("graphics", "legend", "lines", "par", "plot") 16 | importFrom("methods", "as") 17 | importFrom("stats", "cor", "ecdf", "kmeans", "median", "p.adjust", "quantile") 18 | importFrom("utils", "write.table") 19 | importFrom("mclust", "Mclust", "mclustBIC") 20 | importFrom("parallel", "mclapply") 21 | importFrom("pheatmap", "pheatmap") 22 | importFrom("Matrix", "sparseMatrix") 23 | -------------------------------------------------------------------------------- /R/kidneyTabulaMuris.R: -------------------------------------------------------------------------------- 1 | #' A subset of the Tabula Muris SmartSeq2 data, restricted to three cell types from Kidney. 2 | #' 3 | #' A subset of the Tabula Muris data with 215 cells and 23341 genes. There are three 4 | #' cell types, endothelial cells: 122 cells, kidney collecting duct epithelial cell: 78 cells and leukoocytes 15 cells. 5 | #' 6 | #' @format A list with two components: 7 | #' \describe{\item{exp}{Gene expression sparse matrix of class dgCMatrix, with normalized log expression values. Rows are genes, columns are cells.} \item{cellType}{A character vector containing the cell types.}} 8 | #' @references The Tabula Muris Consortium Single-cell transcriptomics of 20 mouse organs creates a Tabula Muris. Nature, 562:7727, 2018 9 | "kidneyTabulaMuris" 10 | -------------------------------------------------------------------------------- /man/kidneyTabulaMuris.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/kidneyTabulaMuris.R 3 | \docType{data} 4 | \name{kidneyTabulaMuris} 5 | \alias{kidneyTabulaMuris} 6 | \title{A subset of the Tabula Muris SmartSeq2 data, restricted to three cell types from Kidney.} 7 | \format{ 8 | A list with two components: 9 | \describe{\item{exp}{Gene expression sparse matrix of class dgCMatrix, with normalized log expression values. Rows are genes, columns are cells.} \item{cellType}{A character vector containing the cell types.}} 10 | } 11 | \usage{ 12 | kidneyTabulaMuris 13 | } 14 | \description{ 15 | A subset of the Tabula Muris data with 215 cells and 23341 genes. There are three 16 | cell types, endothelial cells: 122 cells, kidney collecting duct epithelial cell: 78 cells and leukoocytes 15 cells. 17 | } 18 | \references{ 19 | The Tabula Muris Consortium Single-cell transcriptomics of 20 mouse organs creates a Tabula Muris. Nature, 562:7727, 2018 20 | } 21 | \keyword{datasets} 22 | -------------------------------------------------------------------------------- /man/plotMarkerScores.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plotMarkerScores.R 3 | \name{plotMarkerScores} 4 | \alias{plotMarkerScores} 5 | \title{plotMarkerScores} 6 | \usage{ 7 | plotMarkerScores( 8 | mm, 9 | gs, 10 | markers = mm$markers, 11 | colors = c("#99999920", "orangered4") 12 | ) 13 | } 14 | \arguments{ 15 | \item{mm}{The output of \code{getMarkers}} 16 | 17 | \item{gs}{The output of \code{sortGenes}} 18 | 19 | \item{markers}{A character vector containing the genes to highlight in the 20 | scatter plot.} 21 | 22 | \item{colors}{A color palette to use for the scatter plot.} 23 | } 24 | \description{ 25 | plotMarkerScores plots scatter plots of the specificity score and the gene 26 | specificity Shannon index to investigate \code{getMarkers} results. 27 | } 28 | \examples{ 29 | data(kidneyTabulaMuris) 30 | gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 31 | mm = getMarkers(gs,quant=0.99) 32 | plotMarkerScores(mm, gs) 33 | } 34 | \author{ 35 | Mahmoud M Ibrahim 36 | } 37 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: genesorteR 2 | Type: Package 3 | Title: Feature Ranking in Clustered Single Cell Data 4 | Version: 0.4.3 5 | Author: Mahmoud M Ibrahim 6 | Maintainer: Mahmoud M Ibrahim 7 | Description: The main purpose of this R extension is to select features in (possibly very large) single cell data including scRNA-Seq and scATAC-Seq. 8 | The main idea is that the dropout rate of a gene is a good measure of its expression, and that empirical statistics calculated based on binarized expression matrices are sufficient to select marker genes in a way that is consistent with the expected definition of "marker gene" in experimental biology research. 9 | It can provide a ranking of genes specificity in each cell cluster, as well as select large or small sets of marker genes by a permutation test or using entropy-based feature selection. 10 | To assess cell clustering quality, some functions can also compute cell cluster quality metrics. 11 | License: GPL-3 + file LICENSE 12 | Encoding: UTF-8 13 | LazyData: true 14 | RoxygenNote: 7.1.0 15 | URL: http://github.com/mahmoudibrahim/genesorteR 16 | BugReports: http://github.com/mahmoudibrahim/genesorteR/issues 17 | Imports: 18 | mclust, 19 | parallel, 20 | pheatmap, 21 | methods 22 | Depends: 23 | R (>= 2.10), 24 | Matrix 25 | -------------------------------------------------------------------------------- /R/plotMarkerScores.R: -------------------------------------------------------------------------------- 1 | #' plotMarkerScores 2 | #' 3 | #' plotMarkerScores plots scatter plots of the specificity score and the gene 4 | #' specificity Shannon index to investigate \code{getMarkers} results. 5 | #' @param mm The output of \code{getMarkers} 6 | #' @param gs The output of \code{sortGenes} 7 | #' @param markers A character vector containing the genes to highlight in the 8 | #' scatter plot. 9 | #' @param colors A color palette to use for the scatter plot. 10 | #' @author Mahmoud M Ibrahim 11 | #' 12 | #' @export 13 | #' @examples 14 | #' data(kidneyTabulaMuris) 15 | #' gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 16 | #' mm = getMarkers(gs,quant=0.99) 17 | #' plotMarkerScores(mm, gs) 18 | plotMarkerScores = function(mm, gs, markers = mm$markers, colors = c("#99999920","orangered4")) { 19 | coloring = rep(colors[1],length(mm$gene_shannon_index)) 20 | coloring[which(names(mm$gene_shannon_index) %in% markers)] = colors[2] 21 | 22 | par(mfrow = c(1,2)) 23 | plot(mm$gene_shannon_index, mm$maxScaledSpecScore, col = coloring, pch = 19, xlab = "Specificity Shannon Index", ylab = "Max. Scaled Specificity Score") 24 | plot(mm$gene_shannon_index, apply(gs$specScore, 1, max), col = coloring, pch = 19, xlab = "Specificity Shannon Index", ylab = "Max. Specificity Score") 25 | } 26 | -------------------------------------------------------------------------------- /man/write.files.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/write.files.R 3 | \name{write.files} 4 | \alias{write.files} 5 | \title{write.files} 6 | \usage{ 7 | write.files(gs, prefix = "genesorteROuts", markers = NULL, eachCluster = FALSE) 8 | } 9 | \arguments{ 10 | \item{gs}{The output of \code{sortGenes()}.} 11 | 12 | \item{prefix}{The prefix for saving the files.} 13 | 14 | \item{markers}{Additionally, output files restricted to these genes. A 15 | character vector.} 16 | 17 | \item{eachCluster}{Also write individual files for each cluster?} 18 | } 19 | \description{ 20 | write.files saves gene-cluster sorting information obtained from 21 | \code{sortGenes} to disk. 22 | } 23 | \details{ 24 | Three files will be saved to disk, including the specificity score matrix, 25 | the posterior cluster probability given the gene and the conditional 26 | probability of observing the gene in a cluster. If \code{markers} is not 27 | NULL, three additional files will be created and indicated with "_markers" in 28 | their name. If \code{eachCluster} is \code{TRUE}, additional files (one per 29 | cluster will be written which includes all genes and their scaled specificity 30 | score for each cluster, with genes sorted by their score. 31 | } 32 | \examples{ 33 | data(sim) 34 | gs = sortGenes(sim$exp, sim$cellType) 35 | \dontrun{write.files(gs)} #write all files for all genes. 36 | \dontrun{write.files(gs, markers = c("g1","g2"))} #additionally write files that are restricted to genes g1 and g2. 37 | } 38 | \author{ 39 | Mahmoud M Ibrahim 40 | } 41 | -------------------------------------------------------------------------------- /man/plotCorrelationHeat.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plotCorrelationHeat.R 3 | \name{plotCorrelationHeat} 4 | \alias{plotCorrelationHeat} 5 | \title{plotCorrelationHeat} 6 | \usage{ 7 | plotCorrelationHeat( 8 | gs, 9 | markers = NULL, 10 | corMethod = "pearson", 11 | colors = colorRampPalette(rev(c("orangered4", "orangered", "gray90", "dodgerblue", 12 | "dodgerblue4")))(n = 100), 13 | outs = FALSE, 14 | displayNumbers = TRUE 15 | ) 16 | } 17 | \arguments{ 18 | \item{gs}{The output of \code{sortGenes}.} 19 | 20 | \item{markers}{Restrict correlation analysis to those genes. A character 21 | vector.} 22 | 23 | \item{corMethod}{Correlation method, will passed to \code{method} in the 24 | function \code{cor}.} 25 | 26 | \item{colors}{Color palette for drawing the heatmap} 27 | 28 | \item{outs}{Should the \code{pheatmap} object and correlation matrix be 29 | returned? FALSE by default.} 30 | 31 | \item{displayNumbers}{Should correlation values be displayed on the heatmap? 32 | TRUE by default.} 33 | } 34 | \value{ 35 | If \code{outs} is TRUE, the pheatmap object and the correlation matrix will 36 | be returned. 37 | } 38 | \description{ 39 | \code{plotCorrelationHeat} uses the specificity scores returned by \code{sortGenes} to 40 | correlate cell clusters with each other and plot a heatmap. 41 | } 42 | \examples{ 43 | data(kidneyTabulaMuris) 44 | gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 45 | plotCorrelationHeat(gs) 46 | 47 | #user only marker genes and spearman correlation 48 | mm = getMarkers(gs, quant = 0.95) 49 | plotCorrelationHeat(gs, markers = mm$markers, corMethod = "spearman") 50 | 51 | #do not write correlation values, useful if there are many cell clusters 52 | plotCorrelationHeat(gs, markers = mm$markers, corMethod = "spearman", displayNumbers = FALSE) 53 | } 54 | \author{ 55 | Mahmoud M Ibrahim 56 | } 57 | -------------------------------------------------------------------------------- /R/plotCorrelationHeat.R: -------------------------------------------------------------------------------- 1 | #' plotCorrelationHeat 2 | #' 3 | #' \code{plotCorrelationHeat} uses the specificity scores returned by \code{sortGenes} to 4 | #' correlate cell clusters with each other and plot a heatmap. 5 | #' 6 | #' @param gs The output of \code{sortGenes}. 7 | #' @param markers Restrict correlation analysis to those genes. A character 8 | #' vector. 9 | #' @param corMethod Correlation method, will passed to \code{method} in the 10 | #' function \code{cor}. 11 | #' @param colors Color palette for drawing the heatmap 12 | #' @param outs Should the \code{pheatmap} object and correlation matrix be 13 | #' returned? FALSE by default. 14 | #' @param displayNumbers Should correlation values be displayed on the heatmap? 15 | #' TRUE by default. 16 | #' @return If \code{outs} is TRUE, the pheatmap object and the correlation matrix will 17 | #' be returned. 18 | #' @export 19 | #' @author Mahmoud M Ibrahim 20 | #' @examples 21 | #' data(kidneyTabulaMuris) 22 | #' gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 23 | #' plotCorrelationHeat(gs) 24 | #' 25 | #' #user only marker genes and spearman correlation 26 | #' mm = getMarkers(gs, quant = 0.95) 27 | #' plotCorrelationHeat(gs, markers = mm$markers, corMethod = "spearman") 28 | #' 29 | #' #do not write correlation values, useful if there are many cell clusters 30 | #' plotCorrelationHeat(gs, markers = mm$markers, corMethod = "spearman", displayNumbers = FALSE) 31 | plotCorrelationHeat = function(gs, markers = NULL, corMethod = "pearson", colors = colorRampPalette(rev(c("orangered4","orangered","gray90","dodgerblue","dodgerblue4")))(n=100), outs = FALSE, displayNumbers = TRUE) { 32 | 33 | if (is.null(markers)) { 34 | cc = cor(as.matrix(gs$specScore), method = corMethod) 35 | } else { 36 | cc = cor(as.matrix(gs$specScore[which(rownames(gs$specScore) %in% markers),]), method = corMethod) 37 | } 38 | 39 | rownames(cc) = colnames(gs$specScore) 40 | colnames(cc) = colnames(gs$specScore) 41 | 42 | p=pheatmap(cc, breaks = seq(-1,1,length.out = 99), show_rownames=T, show_colnames=T, display_numbers=displayNumbers, color = colors) 43 | 44 | if (outs) { 45 | return(list(pheat = p, corr = cc)) 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /man/plotTopBinaryHeat.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plotTopBinaryHeat.R 3 | \name{plotTopBinaryHeat} 4 | \alias{plotTopBinaryHeat} 5 | \title{plotTopBinaryHeat} 6 | \usage{ 7 | plotTopBinaryHeat( 8 | sg, 9 | top_n = 10, 10 | colors = colorRampPalette(c("white", "black"))(n = 100), 11 | newOrder = 1:length(unique(sg$inputClass)), 12 | averageCells = 0, 13 | gaps = TRUE, 14 | outs = FALSE, 15 | plotheat = TRUE 16 | ) 17 | } 18 | \arguments{ 19 | \item{sg}{A list, typically the output of \code{sortGenes}.} 20 | 21 | \item{top_n}{The number of top genes to plot for each cluster.} 22 | 23 | \item{colors}{Color palette used for the heatmap.} 24 | 25 | \item{newOrder}{Reorder the clusters in the heatmap? See Examples.} 26 | 27 | \item{averageCells}{Plot averages of cells instead of individual cells. You 28 | can use this when you have a large number of cells. See Details.} 29 | 30 | \item{gaps}{Should the heatmap have gaps between cell types and gene clusters? 31 | TRUE by default.} 32 | 33 | \item{outs}{Should the top genes names be returned? FALSE by default.} 34 | 35 | \item{plotheat}{Should the heatmap be drawn? TRUE by default.} 36 | } 37 | \value{ 38 | If \code{outs} is TRUE, \code{plotMarkerHeat} returns a list containing 39 | the top \code{n} marker genes for each cluster. 40 | } 41 | \description{ 42 | Plot a heatmap of binarized values for the top genes or peaks in each cluster, 43 | defined by \code{sortGenes()}. 44 | } 45 | \details{ 46 | \code{plotTopMarkerHeat} is similar to \code{plotTopMarkerHeat} but works on 47 | the binarized matrix, plotting only 0s and 1s (for scRNA-Seq, this means ignoring 48 | expression values and just plotting whether the gene is expressed or not). 49 | If \code{averageCells} is > 1, the fraction of the averaged cells where the gene 50 | or peak was detected will be plotted (a number between 0 and 1). 51 | } 52 | \examples{ 53 | data(kidneyTabulaMuris) 54 | gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 55 | plotTopBinaryHeat(gs) # plots the top 10 genes for each cluster 56 | 57 | #now plot the top 20 genes and average every 5 cells 58 | plotTopBinaryHeat(gs, top_n= 20, averageCells=5) 59 | 60 | } 61 | \seealso{ 62 | plotTopMarkerHeat 63 | } 64 | \author{ 65 | Mahmoud M Ibrahim 66 | } 67 | -------------------------------------------------------------------------------- /man/getTable.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/getTable.R 3 | \name{getTable} 4 | \alias{getTable} 5 | \title{getTable} 6 | \usage{ 7 | getTable( 8 | gs, 9 | pp, 10 | fc_cutoff = 0, 11 | adjpval_cutoff = 0.05, 12 | islog = TRUE, 13 | pseudocount = 1 14 | ) 15 | } 16 | \arguments{ 17 | \item{gs}{The output of \code{sortGenes}.} 18 | 19 | \item{pp}{The output of \code{getPValues}.} 20 | 21 | \item{fc_cutoff}{Default is 0, which means only genes that have an average 22 | fold-change higher than 0 for a given cluster are reported. Positive and negative 23 | numbers are allowed. Set to FALSE to switch off filtering on the average fold-change 24 | value.} 25 | 26 | \item{adjpval_cutoff}{A numeric adjusted p-value cutoff value. Default is 0.05.} 27 | 28 | \item{islog}{A logical value. TRUE (default) means the expression matrix supplied 29 | previously to \code{sortGenes} is in log space.} 30 | 31 | \item{pseudocount}{A numeric value. A pseudocount to add to the expression matrix before 32 | taking the log if \code{islog} is FALSE.} 33 | } 34 | \value{ 35 | \code{getTable} returns a data frame containing the gene name, the average log fold 36 | change, the adjusted p-value and the specificity score for all variable genes in each cluster. 37 | The data frame is sorted by the specificity score. Note that a gene may appear multiple times 38 | for multiple clusters. 39 | } 40 | \description{ 41 | Summarize \code{sortGenes} and \code{getPValues} results in one data frame. 42 | } 43 | \details{ 44 | \code{getTable} combines the results of sortGenes and getPValues in one table 45 | and also calculates the average fold-change of expression, allowing to select 46 | a fold-change cutoff and a p-value cutoff to determine variable genes. 47 | } 48 | \examples{ 49 | data(kidneyTabulaMuris) 50 | gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 51 | pp = getPValues(gs) 52 | tab = getTable(gs, pp) 53 | 54 | #A quick diagnostic plot (fold change correlates with specificity score) 55 | plot(tab$Average.Log.Fold.Change, tab$Specificity.Score, col = as.factor(tab$Cluster), pch = 20) 56 | 57 | #all variable genes 58 | unique(tab$Gene.Name) 59 | 60 | #To get all genes without any cutoffs, set adjpval_cutoff to >1 and fc_cutoff to FALSE 61 | tab = getTable(gs, pp, fc_cutoff = FALSE, adjpval_cutoff = 1.1) 62 | } 63 | \author{ 64 | Mahmoud M Ibrahim 65 | } 66 | -------------------------------------------------------------------------------- /man/plotTopMarkerHeat.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plotTopMarkerHeat.R 3 | \name{plotTopMarkerHeat} 4 | \alias{plotTopMarkerHeat} 5 | \title{plotTopMarkerHeat} 6 | \usage{ 7 | plotTopMarkerHeat( 8 | sg, 9 | top_n = 10, 10 | colors = colorRampPalette(rev(c("orangered4", "orangered", "gray90", "dodgerblue", 11 | "dodgerblue4")))(n = 100), 12 | newOrder = 1:length(unique(sg$inputClass)), 13 | averageCells = 0, 14 | gaps = TRUE, 15 | outs = FALSE, 16 | plotheat = TRUE 17 | ) 18 | } 19 | \arguments{ 20 | \item{sg}{A list, typically the output of \code{sortGenes}.} 21 | 22 | \item{top_n}{The number of top genes to plot for each cluster.} 23 | 24 | \item{colors}{Color palette used for the heatmap.} 25 | 26 | \item{newOrder}{Reorder the clusters in the heatmap? See Examples.} 27 | 28 | \item{averageCells}{Plot averages of cells instead of individual cells. You 29 | can use this when you have a large number of cells. See Details.} 30 | 31 | \item{gaps}{Should the heatmap have gaps between cell types and gene clusters? 32 | TRUE by default.} 33 | 34 | \item{outs}{Should the top genes names be returned? FALSE by default.} 35 | 36 | \item{plotheat}{Should the heatmap be drawn? TRUE by default.} 37 | } 38 | \value{ 39 | If \code{outs} is TRUE, \code{plotMarkerHeat} returns a list containing 40 | the top \code{n} marker genes for each cluster. 41 | } 42 | \description{ 43 | Plot a heatmap of expression values for the top genes in each cluster, 44 | defined by \code{sortGenes()}. 45 | } 46 | \details{ 47 | \code{plotTopMarkerHeat} is a convenience wrapper around \code{plotMarkerHeat} 48 | that plots a heatmap of the top \code{top_n} (10 by default) genes in each cell 49 | cluster. Unlike \code{plotMarkerHeat}, \code{plotTopMarkerHeat} takes the output 50 | of \code{sortGenes} as the only required input. 51 | } 52 | \examples{ 53 | data(kidneyTabulaMuris) 54 | gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 55 | plotTopMarkerHeat(gs) # plots the top 10 genes for each cluster 56 | 57 | #now plot the top 20 genes and average every 5 cells 58 | plotTopMarkerHeat(gs, top_n= 20, averageCells=5) 59 | 60 | #just identify the top 20 genes, do not make a plot 61 | plotTopMarkerHeat(gs, top_n= 20, averageCells=5, outs = TRUE, plotheat = FALSE) 62 | 63 | } 64 | \seealso{ 65 | plotMarkerHeat 66 | } 67 | \author{ 68 | Mahmoud M Ibrahim 69 | } 70 | -------------------------------------------------------------------------------- /R/write.files.R: -------------------------------------------------------------------------------- 1 | #' write.files 2 | #' 3 | #' write.files saves gene-cluster sorting information obtained from 4 | #' \code{sortGenes} to disk. 5 | #' 6 | #' Three files will be saved to disk, including the specificity score matrix, 7 | #' the posterior cluster probability given the gene and the conditional 8 | #' probability of observing the gene in a cluster. If \code{markers} is not 9 | #' NULL, three additional files will be created and indicated with "_markers" in 10 | #' their name. If \code{eachCluster} is \code{TRUE}, additional files (one per 11 | #' cluster will be written which includes all genes and their scaled specificity 12 | #' score for each cluster, with genes sorted by their score. 13 | #' 14 | #' @param gs The output of \code{sortGenes()}. 15 | #' @param prefix The prefix for saving the files. 16 | #' @param markers Additionally, output files restricted to these genes. A 17 | #' character vector. 18 | #' @param eachCluster Also write individual files for each cluster? 19 | #' @author Mahmoud M Ibrahim 20 | #' 21 | #' @examples 22 | #' data(sim) 23 | #' gs = sortGenes(sim$exp, sim$cellType) 24 | #' \dontrun{write.files(gs)} #write all files for all genes. 25 | #' \dontrun{write.files(gs, markers = c("g1","g2"))} #additionally write files that are restricted to genes g1 and g2. 26 | write.files = function(gs, prefix = "genesorteROuts", markers = NULL, eachCluster = FALSE) { 27 | 28 | write.table(round(as.matrix(gs$condGeneProb),3), sep = "\t", file = paste0(prefix, "_condProbOfExp.csv"), quote = FALSE) 29 | write.table(round(as.matrix(gs$postClustProb),3), sep = "\t", file = paste0(prefix, "_postClustProb.csv"), quote = FALSE) 30 | write.table(round(as.matrix(gs$specScore),3), sep = "\t", file = paste0(prefix, "_specifictyScore.csv"), quote = FALSE) 31 | 32 | if (eachCluster) { 33 | for (i in 1:ncol(gs$specScore)) { 34 | tt = as.matrix(gs$specScore[order(gs$specScore[,i], decreasing = TRUE),]) 35 | write(paste(rownames(tt), round(score(tt[,i]),3), sep = ","), ncolumns = 1, file = paste0(prefix, "_genes_by_scaledSpecScore_", gsub("/", "_", colnames(gs$specScore)[i], fixed = TRUE), ".csv")) 36 | } 37 | } 38 | 39 | if (!(is.null(markers))) { 40 | ww = which(rownames(gs$condGeneProb) %in% markers) 41 | write.table(round(as.matrix(gs$condGeneProb[ww,]),3), sep = "\t", file = paste0(prefix, "_condProbOfExp_markers.csv"), quote = FALSE) 42 | write.table(round(as.matrix(gs$postClustProb[ww,]),3), sep = "\t", file = paste0(prefix, "_postClustProb_markers.csv"), quote = FALSE) 43 | write.table(round(as.matrix(gs$specScore[ww,]),3), sep = "\t", file = paste0(prefix, "_specificityScore_markers.csv"), quote = FALSE) 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /man/getClassAUC.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/getClassAUC.R 3 | \name{getClassAUC} 4 | \alias{getClassAUC} 5 | \title{getClassAUC} 6 | \usage{ 7 | getClassAUC(gs, markers = NULL, plotCurves = TRUE, colors = NULL) 8 | } 9 | \arguments{ 10 | \item{gs}{A list containing \code{$specScore} sparse matrix. Typically the 11 | output of \code{sortGenes()}.} 12 | 13 | \item{markers}{A character vector of gene names to restrict this analysis to. 14 | See Details.} 15 | 16 | \item{plotCurves}{Should a plot be drawn? default value is TRUE.} 17 | 18 | \item{colors}{Color palette for the plot.} 19 | } 20 | \value{ 21 | \code{getClassAUC} returns a numeric vector of length 22 | \code{ncol($specScore)} that contains the AUC for each cell cluster. 23 | } 24 | \description{ 25 | getClassAUC implements one way to investigate clustering quality. It processes the 26 | output of \code{sortGenes} to obtain a curve for each cell cluster for all 27 | gene specificity scores against their ranking in the cluster. The Area Under 28 | the Curve (AUC) can be used as a measure of clustering quality in terms of the 29 | possibility to identify cell clusters using a few marker genes. See Details. 30 | } 31 | \details{ 32 | Given the specificity score for all genes in a certain cell cluster, we can 33 | assume that a well-separated easily-identified cell cluster will have a 34 | relatively small number of genes that have a very high specificity score. Top 35 | marker genes for a cluster that is poorly separated from other cell 36 | clusters will have average or low specificity scores. Sorting the genes for 37 | each cell cluster by their specificity scores and plotting the scaled scores 38 | in order creates a curve that should be far from the diagonal for 39 | well-separated clusters but close to the diagonal for poorly-separated 40 | clusters. The AUC of this curve can be used to quantify this intuition and 41 | estimate a clustering quality metric. 42 | } 43 | \examples{ 44 | #randomly generated expression matrix and cell clusters 45 | set.seed(1234) 46 | exp = matrix(sample(0:20,1000,replace=TRUE), ncol = 20) 47 | rownames(exp) = sapply(1:50, function(x) paste0("g", x)) 48 | cellType = sample(c("cell type 1","cell type 2"),20,replace=TRUE) 49 | sg = sortGenes(exp, cellType) 50 | classAUC = getClassAUC(sg) 51 | 52 | #"reasonably" separated clusters 53 | data(sim) 54 | sg = sortGenes(sim$exp, sim$cellType) 55 | classAUC = getClassAUC(sg) 56 | 57 | #real data with three well separated clusters 58 | data(kidneyTabulaMuris) 59 | sg = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 60 | classAUC = getClassAUC(sg) 61 | } 62 | \seealso{ 63 | \code{getMarkers} returns a cell cluster Shannon index that tends to 64 | correlate well with the AUC metric returned by \code{getClassAUC}. 65 | } 66 | \author{ 67 | Mahmoud M Ibrahim 68 | } 69 | -------------------------------------------------------------------------------- /man/getMarkers.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/getMarkers.R 3 | \name{getMarkers} 4 | \alias{getMarkers} 5 | \title{getMarkers} 6 | \usage{ 7 | getMarkers(gs, quant = 0.99, mutualInfo = FALSE, classEnt = FALSE) 8 | } 9 | \arguments{ 10 | \item{gs}{The output of \code{sortGenes()}.} 11 | 12 | \item{quant}{A number greater than zero and smaller than one. 0.99 by 13 | default. See Details.} 14 | 15 | \item{mutualInfo}{Logical. If \code{TRUE}, the mutual information between 16 | gene expression and cell clustering will be returned for each gene. \code{FALSE} 17 | by default.} 18 | 19 | \item{classEnt}{Logical. If \code{TRUE}, a "Cluster Shannon Index" is 20 | returned for each cluster. See Details. \code{FALSE} by default.} 21 | } 22 | \value{ 23 | \code{getMarkers} returns a list with the following components: 24 | \item{markers}{A character vector containing the names of selected marker 25 | features.} \item{maxScaledSpecScore}{A numeric vector of length 26 | \code{nrow(gs$specScore)}, including the maximum scaled specificity score for 27 | each gene across all cell clusters.} \item{gene_shannon_index}{A numeric vector 28 | of the same length as \code{maxScaledSpecScore}, including the Gene Shannon 29 | Index for each gene. See Details.} \item{mutInfo}{A numeric vector of the 30 | same length as \code{maxScaledSpecScore}, including the mutual information 31 | between the expression of each gene and the cell clustering.} 32 | \item{classEntropy}{A numeric vector of the same length as 33 | \code{ncol(specScore)}, including the Class Shannon Index for each cluster 34 | based on the selected marker genes.} 35 | } 36 | \description{ 37 | getMarkers processes the output of \code{sortGenes} to select a relatively 38 | small set of marker genes. 39 | } 40 | \details{ 41 | 42 | } 43 | \examples{ 44 | #randomly generated data and cell clusters, almost no markers are found 45 | set.seed(1234) 46 | exp = matrix(sample(0:20,1000,replace=TRUE), ncol = 20) 47 | rownames(exp) = sapply(1:50, function(x) paste0("g", x)) 48 | cellType = sample(c("cell type 1","cell type 2"),20,replace=TRUE) 49 | sg = sortGenes(exp, cellType) 50 | mm = getMarkers(sg,quant=0.95) 51 | length(mm$markers) #only one marker gene was found 52 | 53 | 54 | #"reasonably" separated clusters, with a few clear markers 55 | data(sim) 56 | gs = sortGenes(sim$exp, sim$cellType) 57 | mm = getMarkers(gs,quant=0.95) 58 | length(mm$markers) 59 | 60 | #real data with three well separated clusters 61 | data(kidneyTabulaMuris) 62 | gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 63 | mm = getMarkers(gs, quant = 0.99) 64 | length(mm$markers) #we found 109 candidate markers 65 | #we want to get a more focused list: 66 | mm = getMarkers(gs, quant = 0.999) 67 | length(mm$markers) #11 genes that can alone descriminate between the cell types 68 | } 69 | \seealso{ 70 | getPValues 71 | } 72 | \author{ 73 | Mahmoud M Ibrahim 74 | } 75 | -------------------------------------------------------------------------------- /man/getPValues.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/getPValues.R 3 | \name{getPValues} 4 | \alias{getPValues} 5 | \title{getPValues} 6 | \usage{ 7 | getPValues( 8 | gs, 9 | numPerm = 5, 10 | correctMethod = "BH", 11 | testGenes = NULL, 12 | subsetCells = NULL, 13 | cores = 1, 14 | seed = 111 15 | ) 16 | } 17 | \arguments{ 18 | \item{gs}{The output of \code{sortGenes()}.} 19 | 20 | \item{numPerm}{The number of permutations to do. The default value 5 is to 21 | ensure quick running time for very large datasets but can be increased to 22 | increase the power of the permutation test, see Details.} 23 | 24 | \item{correctMethod}{The method used to correct p-values for multiple 25 | hypothesis testing. Any valid input to "method" in \code{p.adjust} is 26 | allowed. p-value correction is done on a gene-by-gene basis.} 27 | 28 | \item{testGenes}{A character vector of gene names to restrict the output 29 | p-values to.} 30 | 31 | \item{subsetCells}{A numeric vector of cell indeces to restrict the 32 | permutation to. Note that the selected cells should still contain at least 33 | one cell from each of the cell clusters contained in \code{$specScore}. 34 | Note this option is still experimental and might not give consistent 35 | results.} 36 | 37 | \item{cores}{An integer greater than zero (1 by default) that indicates how 38 | many cores to use for parallelization using mclapply.} 39 | 40 | \item{seed}{The seed for random permutations.} 41 | } 42 | \value{ 43 | \code{getPValues} returns a list with the following components: 44 | \item{permuteVal}{A sparse matrix with as many rows as genes and as many 45 | columns as \code{ncol($specScore) * numPerm}, containing the specificity 46 | score matrices for all permutations concatenated after each other 47 | column-wise.} \item{startIndeces}{A numeric vector of length \code{numPerm} 48 | that indicates the starting column for each performed permutation in 49 | \code{permuteVal}} \item{pval}{A matrix with as many rows as genes and 50 | columns as \code{ncol($specScore)}, containing the p-values for the null 51 | hypothesis that the gene is not highly specific to a cell cluster is true.} 52 | \item{adjpval}{A matrix with the same size as \code{pval}, containing the 53 | corrected p-values using the method specified in \code{correctMethod}} 54 | } 55 | \description{ 56 | getPValues performs a permutation test on the gene-cell type specificity 57 | score to obtain a p-value value on each gene-cell type specificity score. The 58 | permutation keeps everything the same except that cell type assignments are 59 | permuted between the cells (but note that cell type proportions are also kept 60 | the same). This function is a way to select all differentially expressed 61 | genes between all cell classes globally in a dataset in one go or to define 62 | differentially expressed genes in a specific cell cluster. 63 | } 64 | \examples{ 65 | data(kidneyTabulaMuris) 66 | gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 67 | pp = getPValues(gs) 68 | #obtain genes that are "differentially expressed" in at least one cluster 69 | markers = names(which(apply(pp$adjpval, 1, function(x) any(x < 0.01)))) 70 | 71 | } 72 | \seealso{ 73 | getMarkers 74 | } 75 | \author{ 76 | Mahmoud M Ibrahim 77 | } 78 | -------------------------------------------------------------------------------- /man/plotBinaryHeat.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plotBinaryHeat.R 3 | \name{plotBinaryHeat} 4 | \alias{plotBinaryHeat} 5 | \title{plotBinaryHeat} 6 | \usage{ 7 | plotBinaryHeat( 8 | exp, 9 | classes, 10 | markers, 11 | colors = colorRampPalette(c("white", "black"))(n = 100), 12 | newOrder = 1:length(unique(classes)), 13 | clusterGenes = FALSE, 14 | clusterGenesK = length(unique(classes)), 15 | averageCells = 0, 16 | outs = FALSE, 17 | plotheat = TRUE, 18 | gaps = TRUE, 19 | seed = 10 20 | ) 21 | } 22 | \arguments{ 23 | \item{exp}{A matrix of *binary* (0s and 1s) expression values. For example, the one 24 | found in \code{sortGenes(...)$binary}.} 25 | 26 | \item{classes}{A vector or factor of cell classes, whose length is equal to 27 | \code{ncol(exp)}.} 28 | 29 | \item{markers}{A character vector of gene or peak names to plot in the heatmap.} 30 | 31 | \item{colors}{Color palette used for the heatmap.} 32 | 33 | \item{newOrder}{Reorder the clusters in the heatmap? See Examples.} 34 | 35 | \item{clusterGenes}{Cluster genes before plotting?} 36 | 37 | \item{clusterGenesK}{How many clusters should genes by clustered into? See 38 | Details.} 39 | 40 | \item{averageCells}{Plot averages of cells instead of individual cells. You 41 | can use this when you have a large number of cells. See Details.} 42 | 43 | \item{outs}{Should gene cluster output and pheatmap object be returned? FALSE 44 | by default.} 45 | 46 | \item{plotheat}{Should the heatmap be drawn? TRUE by default.} 47 | 48 | \item{gaps}{Should the heatmap have gaps between cell types and gene clusters? 49 | TRUE by default.} 50 | 51 | \item{seed}{Randomization seed used for gene clustering initialization.} 52 | } 53 | \value{ 54 | If \code{outs} is TRUE, \code{plotMarkerHeat} returns a list 55 | containing: \item{p}{The pheatmap object corresponding to the plot.} 56 | \item{gene_class_info}{Gene cluster assignments if gene clustering was 57 | requested. See Details.} \item{new_class_info}{The new order of cell 58 | clusters. See Examples.} 59 | } 60 | \description{ 61 | Plot a heatmap binarized values for a select set of genes or peaks across all 62 | cells. Optionally also cluster those genes. 63 | } 64 | \details{ 65 | \code{plotBinaryHeat} is similar to \code{plotMarkerHeat} but works on 66 | the binarized matrix, plotting only 0s and 1s (for scRNA-Seq, this means ignoring 67 | expression values and just plotting whether the gene is expressed or not). 68 | If \code{averageCells} is > 1, the fraction of the averaged cells where the gene 69 | or peak was detected will be plotted (a number between 0 and 1). 70 | 71 | \code{clusterGenesK} parameter controls the number of gene clusters when 72 | \code{clusterGenes} is \code{TRUE}. By default, it is equal to the number of 73 | cell types/clusters. 74 | 75 | By default, the heatmap plots every single cell in one column, this might 76 | take forever if you have a lot of cells (would say >10k) or it can crash when 77 | you do not have enough RAM. If so, it might be good to set \code{averageCells} 78 | to \code{n} where \code{n} is the number of cells you 79 | want to average. For example, if \code{averageCells = 10}, every 10 cells will 80 | be averaged (without averaging across cell clusters) before plotting the heatmap. 81 | if \code{averageCells =< 1}, no averaging happens. Hints: (1) If you want one column 82 | per cell cluster, set \code{averageCells} to a very high number (larger than the 83 | number of cells in the largest cluster). (2) Gene clustering occurs after cell 84 | averaging, so averaging will be useful in this case to prevent running k-means on 85 | binary values. 86 | } 87 | \examples{ 88 | data(kidneyTabulaMuris) 89 | gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 90 | mm = getMarkers(gs, quant = 0.999) 91 | 92 | #this plots a heatmap without reordering genes 93 | plotBinaryHeat(gs$binary, gs$inputClass, mm$markers) 94 | 95 | } 96 | \seealso{ 97 | plotMarkerHeat 98 | } 99 | \author{ 100 | Mahmoud M Ibrahim 101 | } 102 | -------------------------------------------------------------------------------- /R/plotTopMarkerHeat.R: -------------------------------------------------------------------------------- 1 | #' plotTopMarkerHeat 2 | #' 3 | #' Plot a heatmap of expression values for the top genes in each cluster, 4 | #' defined by \code{sortGenes()}. 5 | #' 6 | #' 7 | #' \code{plotTopMarkerHeat} is a convenience wrapper around \code{plotMarkerHeat} 8 | #' that plots a heatmap of the top \code{top_n} (10 by default) genes in each cell 9 | #' cluster. Unlike \code{plotMarkerHeat}, \code{plotTopMarkerHeat} takes the output 10 | #' of \code{sortGenes} as the only required input. 11 | #' 12 | #' 13 | #' @param sg A list, typically the output of \code{sortGenes}. 14 | #' @param top_n The number of top genes to plot for each cluster. 15 | #' @param colors Color palette used for the heatmap. 16 | #' @param newOrder Reorder the clusters in the heatmap? See Examples. 17 | #' @param averageCells Plot averages of cells instead of individual cells. You 18 | #' can use this when you have a large number of cells. See Details. 19 | #' @param gaps Should the heatmap have gaps between cell types and gene clusters? 20 | #' TRUE by default. 21 | #' @param outs Should the top genes names be returned? FALSE by default. 22 | #' @param plotheat Should the heatmap be drawn? TRUE by default. 23 | #' @return If \code{outs} is TRUE, \code{plotMarkerHeat} returns a list containing 24 | #' the top \code{n} marker genes for each cluster. 25 | #' @author Mahmoud M Ibrahim 26 | #' @export 27 | #' @examples 28 | #' data(kidneyTabulaMuris) 29 | #' gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 30 | #' plotTopMarkerHeat(gs) # plots the top 10 genes for each cluster 31 | #' 32 | #' #now plot the top 20 genes and average every 5 cells 33 | #' plotTopMarkerHeat(gs, top_n= 20, averageCells=5) 34 | #' 35 | #' #just identify the top 20 genes, do not make a plot 36 | #' plotTopMarkerHeat(gs, top_n= 20, averageCells=5, outs = TRUE, plotheat = FALSE) 37 | #' 38 | #' @seealso 39 | #' plotMarkerHeat 40 | plotTopMarkerHeat = function(sg, top_n = 10, colors = colorRampPalette(rev(c("orangered4","orangered","gray90","dodgerblue","dodgerblue4")))(n=100), newOrder = 1:length(unique(sg$inputClass)), averageCells = 0, gaps = TRUE, outs = FALSE, plotheat = TRUE) { 41 | 42 | classes = as.integer(as.factor(sg$inputClass)) 43 | map = data.frame(oldO = 1:length(unique(classes)), newO = newOrder) 44 | classes = map$oldO[match(classes, map$newO)] 45 | 46 | markers = list() 47 | for (i in 1:length(unique(classes))) { 48 | markers[[i]] = rownames(sg$specScore[order(sg$specScore[,map[i,2]], decreasing = T),])[1:top_n] 49 | } 50 | final_sel_odd = unique(unlist(markers)) 51 | names(markers) = colnames(sg$specScore[,newOrder]) 52 | 53 | 54 | temp = sg$inputMat[which(rownames(sg$inputMat) %in% final_sel_odd),order(classes, decreasing = FALSE)] 55 | temp = temp[order(match(rownames(temp), final_sel_odd)),] #catch error here? all clusters should be present after marker selection 56 | 57 | classesTemp = classes[order(classes, decreasing = FALSE)] 58 | if (averageCells > 1) { 59 | neh = lapply( 1:length(table(classesTemp)), function(i) rbind(apply(t(as.matrix(temp[,which(classesTemp == i)])), 2, function(x) binMean(x, averageCells))) ) 60 | 61 | nah = unlist(sapply(1:length(neh), function(x) rep(x,nrow(neh[[x]])))) 62 | temp = t( do.call(rbind, neh) ) 63 | colnames(temp) = nah 64 | } else { 65 | colnames(temp) = classesTemp 66 | } 67 | 68 | 69 | if (plotheat) { 70 | club = colnames(temp) #save column names 71 | temp = t(apply(temp, 1, scale)) 72 | cut = quantile(as.vector(abs(temp)), probs = 0.95, na.rm = TRUE) 73 | temp[temp > cut] = cut 74 | temp[temp < -cut] = -cut 75 | colnames(temp) = club #reassign column names 76 | } 77 | 78 | 79 | if (plotheat) { 80 | if (gaps) { 81 | p=pheatmap(temp, cluster_rows = FALSE, cluster_cols = FALSE, scale = "none", color = colors, display_numbers = F, fontsize = 5, show_colnames=FALSE, show_rownames=TRUE, breaks = seq(-cut,cut,length.out = 101), gaps_col = cumsum(table(as.integer(colnames(temp)))), border_color = NA) 82 | } else { 83 | p=pheatmap(temp, cluster_rows = FALSE, cluster_cols = FALSE, scale = "none", color = colors, display_numbers = F, fontsize = 5, show_colnames=FALSE, show_rownames=TRUE, breaks = seq(-cut,cut,length.out = 101), border_color = NA) 84 | } 85 | } 86 | 87 | if (outs) { 88 | return(markers) 89 | } 90 | 91 | 92 | } 93 | -------------------------------------------------------------------------------- /R/plotTopBinaryHeat.R: -------------------------------------------------------------------------------- 1 | #' plotTopBinaryHeat 2 | #' 3 | #' Plot a heatmap of binarized values for the top genes or peaks in each cluster, 4 | #' defined by \code{sortGenes()}. 5 | #' 6 | #' 7 | #' \code{plotTopMarkerHeat} is similar to \code{plotTopMarkerHeat} but works on 8 | #' the binarized matrix, plotting only 0s and 1s (for scRNA-Seq, this means ignoring 9 | #' expression values and just plotting whether the gene is expressed or not). 10 | #' If \code{averageCells} is > 1, the fraction of the averaged cells where the gene 11 | #' or peak was detected will be plotted (a number between 0 and 1). 12 | #' 13 | #' 14 | #' @param sg A list, typically the output of \code{sortGenes}. 15 | #' @param top_n The number of top genes to plot for each cluster. 16 | #' @param colors Color palette used for the heatmap. 17 | #' @param newOrder Reorder the clusters in the heatmap? See Examples. 18 | #' @param averageCells Plot averages of cells instead of individual cells. You 19 | #' can use this when you have a large number of cells. See Details. 20 | #' @param gaps Should the heatmap have gaps between cell types and gene clusters? 21 | #' TRUE by default. 22 | #' @param outs Should the top genes names be returned? FALSE by default. 23 | #' @param plotheat Should the heatmap be drawn? TRUE by default. 24 | #' @return If \code{outs} is TRUE, \code{plotMarkerHeat} returns a list containing 25 | #' the top \code{n} marker genes for each cluster. 26 | #' @author Mahmoud M Ibrahim 27 | #' @export 28 | #' @examples 29 | #' data(kidneyTabulaMuris) 30 | #' gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 31 | #' plotTopBinaryHeat(gs) # plots the top 10 genes for each cluster 32 | #' 33 | #' #now plot the top 20 genes and average every 5 cells 34 | #' plotTopBinaryHeat(gs, top_n= 20, averageCells=5) 35 | #' 36 | #' @seealso 37 | #' plotTopMarkerHeat 38 | plotTopBinaryHeat = function(sg, top_n = 10, colors = colorRampPalette(c("white","black"))(n=100), newOrder = 1:length(unique(sg$inputClass)), averageCells = 0, gaps = TRUE, outs = FALSE, plotheat = TRUE) { 39 | 40 | classes = as.integer(as.factor(sg$inputClass)) 41 | map = data.frame(oldO = 1:length(unique(classes)), newO = newOrder) 42 | classes = map$oldO[match(classes, map$newO)] 43 | 44 | markers = list() 45 | for (i in 1:length(unique(classes))) { 46 | markers[[i]] = rownames(sg$specScore[order(sg$specScore[,map[i,2]], decreasing = T),])[1:top_n] 47 | } 48 | final_sel_odd = unique(unlist(markers)) 49 | names(markers) = colnames(sg$specScore[,newOrder]) 50 | 51 | 52 | temp = sg$binary[which(rownames(sg$binary) %in% final_sel_odd),order(classes, decreasing = FALSE)] 53 | temp = temp[order(match(rownames(temp), final_sel_odd)),] #catch error here? all clusters should be present after marker selection 54 | 55 | classesTemp = classes[order(classes, decreasing = FALSE)] 56 | if (averageCells > 1) { 57 | neh = lapply( 1:length(table(classesTemp)), function(i) rbind(apply(t(as.matrix(temp[,which(classesTemp == i)])), 2, function(x) binMean(x, averageCells))) ) 58 | 59 | nah = unlist(sapply(1:length(neh), function(x) rep(x,nrow(neh[[x]])))) 60 | temp = t( do.call(rbind, neh) ) 61 | colnames(temp) = nah 62 | } else { 63 | colnames(temp) = classesTemp 64 | } 65 | 66 | if (plotheat & (averageCells > 1)) { 67 | club = colnames(temp) #save column names 68 | cut = quantile(as.vector(temp), probs = 0.95, na.rm = TRUE) 69 | if (cut == 0) { 70 | cut = quantile(as.vector(temp), probs = 0.99, na.rm = TRUE) 71 | } 72 | if (cut == 0) { 73 | cut = 1 74 | warning("Could not find an appropriate value to threshold color scale. Matrix may be too sparse. Please consider reporting this warning to mmibrahim@pm.me or at https://github.com/mahmoudibrahim/genesorteR/issues (preferred)") 75 | } 76 | temp[temp > cut] = cut 77 | colnames(temp) = club #reassign column names 78 | } else {cut = 1} 79 | 80 | 81 | 82 | if (plotheat) { 83 | if (gaps) { 84 | p=pheatmap(temp, cluster_rows = FALSE, cluster_cols = FALSE, scale = "none", color = colors, display_numbers = F, fontsize = 5, show_colnames=FALSE, show_rownames=TRUE, breaks = seq(0,cut,length.out = 101), gaps_col = cumsum(table(as.integer(colnames(temp)))), border_color = NA) 85 | } else { 86 | p=pheatmap(temp, cluster_rows = FALSE, cluster_cols = FALSE, scale = "none", color = colors, display_numbers = F, fontsize = 5, show_colnames=FALSE, show_rownames=TRUE, breaks = seq(0,cut,length.out = 101), border_color = NA) 87 | } 88 | } 89 | 90 | if (outs) { 91 | return(markers) 92 | } 93 | 94 | 95 | } 96 | -------------------------------------------------------------------------------- /man/plotMarkerHeat.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plotMarkerHeat.R 3 | \name{plotMarkerHeat} 4 | \alias{plotMarkerHeat} 5 | \title{plotMarkerHeat} 6 | \usage{ 7 | plotMarkerHeat( 8 | exp, 9 | classes, 10 | markers, 11 | colors = colorRampPalette(rev(c("orangered4", "orangered", "gray90", "dodgerblue", 12 | "dodgerblue4")))(n = 100), 13 | newOrder = 1:length(unique(classes)), 14 | clusterGenes = FALSE, 15 | clusterGenesK = length(unique(classes)), 16 | averageCells = 0, 17 | outs = FALSE, 18 | plotheat = TRUE, 19 | gaps = TRUE, 20 | seed = 10 21 | ) 22 | } 23 | \arguments{ 24 | \item{exp}{A matrix of expression values. Typically the one supplied to 25 | \code{sortGenes}.} 26 | 27 | \item{classes}{A vector or factor of cell classes, whose length is equal to 28 | \code{ncol(exp)}.} 29 | 30 | \item{markers}{A character vector of gene names to plot in the heatmap.} 31 | 32 | \item{colors}{Color palette used for the heatmap.} 33 | 34 | \item{newOrder}{Reorder the clusters in the heatmap? See Examples.} 35 | 36 | \item{clusterGenes}{Cluster genes before plotting?} 37 | 38 | \item{clusterGenesK}{How many clusters should genes by clustered into? See 39 | Details.} 40 | 41 | \item{averageCells}{Plot averages of cells instead of individual cells. You 42 | can use this when you have a large number of cells. See Details.} 43 | 44 | \item{outs}{Should gene cluster output and pheatmap object be returned? FALSE 45 | by default.} 46 | 47 | \item{plotheat}{Should the heatmap be drawn? TRUE by default.} 48 | 49 | \item{gaps}{Should the heatmap have gaps between cell types and gene clusters? 50 | TRUE by default.} 51 | 52 | \item{seed}{Randomization seed used for gene clustering initialization.} 53 | } 54 | \value{ 55 | If \code{outs} is TRUE, \code{plotMarkerHeat} returns a list 56 | containing: \item{p}{The pheatmap object corresponding to the plot.} 57 | \item{gene_class_info}{Gene cluster assignments if gene clustering was 58 | requested. See Details.} \item{new_class_info}{The new order of cell 59 | clusters. See Examples.} 60 | } 61 | \description{ 62 | Plot a heatmap of expression values for a select set of genes across all cells. 63 | Optionally also cluster those genes. 64 | } 65 | \details{ 66 | \code{clusterGenesK} parameter controls the number of gene clusters when 67 | \code{clusterGenes} is \code{TRUE}. By default, it is equal to the number of 68 | cell types/clusters. This is usually a good initial guess, the optimal 69 | number of clusters (what does that even mean?) is typically somewhere around 70 | this value in my subjective experience, unless there are many cell clusters. 71 | 72 | By default, the heatmap plots every single cell in one column, this might 73 | take forever if you have a lot of cells (would say >10k) or it can crash when 74 | you do not have enough RAM. If so, it might be good to set \code{averageCells} 75 | to \code{n} where \code{n} is the number of cells you 76 | want to average. For example, if \code{averageCells = 10}, every 10 cells will 77 | be averaged (without averaging across cell clusters) before plotting the heatmap. 78 | if \code{averageCells =< 1}, no averaging happens. Hints: (1) If you want one column 79 | per cell cluster, set \code{averageCells} to a very high number (larger than the 80 | number of cells in the largest cluster). (2) Gene clustering occurs after cell 81 | averaging, so averaging might be useful if the gene clusters you get do not make much sense 82 | without averaging (averaging will smooth out zeros). 83 | } 84 | \examples{ 85 | data(kidneyTabulaMuris) 86 | gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 87 | mm = getMarkers(gs, quant = 0.999) 88 | 89 | #this plots a heatmap without reordering genes 90 | plotMarkerHeat(gs$inputMat, gs$inputClass, mm$markers) 91 | 92 | #so now cluster genes and return the clustering: a better looking plot 93 | pp = plotMarkerHeat(gs$inputMat, gs$inputClass, mm$markers, clusterGenes=TRUE, outs=TRUE) 94 | pp$gene_class_info #cell clusters 95 | 96 | #reorder cell clusters in the heatmap 97 | plotMarkerHeat(gs$inputMat, gs$inputClass, mm$markers, clusterGenes=TRUE, newOrder = c(3,1,2)) 98 | 99 | #average every 4 cells to make a less intense heatmap 100 | plotMarkerHeat(gs$inputMat, gs$inputClass, mm$markers, clusterGenes=TRUE, newOrder = c(3,1,2), 101 | averageCells = 4) 102 | 103 | #only cluster genes, do not make plots 104 | pp = plotMarkerHeat(gs$inputMat, gs$inputClass, mm$markers, clusterGenes=TRUE, 105 | outs=TRUE, plotheat=FALSE) 106 | 107 | } 108 | \seealso{ 109 | plotTopMarkerHeat 110 | } 111 | \author{ 112 | Mahmoud M Ibrahim 113 | } 114 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | genesorteR: Feature Ranking for Single Cell Data 2 | ====== 3 | 4 | **genesorteR is an R package for single cell data analysis. It calculates a specificity score to rank all genes in each cell cluster. It can then use this ranking to find sets of marker genes or to find highly variable or differentially expressed genes. genesorteR is applicable to scRNA-Seq data as well as other sparse single cell data like scATAC-Seq** 5 | 6 | **genesorteR is relatively quick, just seconds for 100k cells, few minutes for millions of cells. Read more [in genesorteR's pre-print](https://www.biorxiv.org/content/10.1101/676379v2).** 7 | 8 | **If you have questions or need help running genesorteR please email us at [this email](http://scr.im/jammpro), we will be happy to help you. For bugs or feature requests, please post [here](https://github.com/mahmoudibrahim/genesorteR/issues).** 9 | 10 | genesorteR was developed at the RWTH Aachen University Hospital. 11 | 12 | 13 | What genesorteR Can Do 14 | ------ 15 | * Rank genes (scRNA-Seq) or open chromatin regions (snATAC-Seq) by "specificity" in cell clusters 16 | * Find small sets of marker genes and differentially expressed / highly variable genes or accessible regions 17 | * Cluster genes/open chromatin regions and make heatmap summaries of single cell data 18 | 19 | 20 | Cited by... 21 | ------ 22 | 23 | * [Cook & Vanderhyden, bioRxiv 2021](https://www.biorxiv.org/content/10.1101/2021.03.05.434142v1.full) 24 | * [Kuppe, Ibrahim et al., Nature 2021](https://www.nature.com/articles/s41586-020-2941-1) 25 | * [Vargo & Gilbert, BMC Bioinformatics 2020](https://bmcbioinformatics.biomedcentral.com/articles/10.1186/s12859-020-03641-z) 26 | * [De Boeck, Ahn et al., Nature Communications 2020](https://www.nature.com/articles/s41467-020-18569-4) 27 | * [Lu, Shiau, Yi et al., Dev. Cell 2020](https://doi.org/10.1016/j.devcel.2020.04.009) 28 | * [Berg et al. bioRxiv 2020](https://www.biorxiv.org/content/10.1101/2020.03.31.018820v1) 29 | 30 | 31 | 32 | Install genesorteR 33 | ------ 34 | ```R 35 | #install devtools package from CRAN 36 | install.packages("devtools") 37 | 38 | #install genesorteR from the Github repository 39 | devtools::install_github("mahmoudibrahim/genesorteR") 40 | ``` 41 | 42 | 43 | genesorteR Documentation 44 | ------ 45 | 46 | Here is the [PDF manual for genesorteR](https://github.com/mahmoudibrahim/genesorteR/blob/master/genesorteR.pdf). 47 | 48 | You can of course also access the documentation of each function like so `?sortGenes`. 49 | 50 | 51 | Wiki (Tutorials & FAQs) 52 | ------ 53 | 54 | * [Comparing genesorteR Specificity Scores to TF-IDF on the Cell Cluster Level in Single Cell Data](https://github.com/mahmoudibrahim/genesorteR/wiki/Specificity-Scores-versus-TF-IDF) (19 Apr. 2020) 55 | 56 | * [Finding Genre-specific Actors and Clustering Film Genres](https://github.com/mahmoudibrahim/genesorteR/wiki/Finding-Genre-specific-Actors-and-Clustering-Film-Genres-(data-from-IMDB)) (21 Jan. 2020) 57 | 58 | * [Pathway and gene set enrichment analysis in large single cell RNA-Seq data](https://github.com/mahmoudibrahim/genesorteR/wiki/From-Cluster-to-Pathway-Enrichment-in-Large-scRNA-Seq-Data) (02 Jan. 2020) 59 | 60 | * [CorrNet: Plot beautiful networks from single cell data clustering results using genesorteR & ggraph](https://github.com/mahmoudibrahim/genesorteR/wiki/Visualize-single-cell-data-in-R-using-genesorteR-&-ggraph) (18 Oct. 2019) 61 | 62 | more Wiki pages coming soon... 63 | 64 | 65 | Quick Tutorial 66 | ------ 67 | 68 | ```R 69 | library(genesorteR) 70 | 71 | data(kidneyTabulaMuris) #three cell types from kidney (Tabula Muris data) 72 | 73 | #get specificity scores for each cell type 74 | sg = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 75 | 76 | head(sg$specScore) #specificity scores for each gene in each cluster 77 | 78 | #define a small set of markers 79 | mm = getMarkers(sg, quant = 0.99) 80 | 81 | #cluster genes and make a heatmap 82 | pp = plotMarkerHeat(sg$inputMat, sg$inputClass, mm$markers, clusterGenes=TRUE, outs = TRUE) 83 | 84 | pp$gene_class_info #gene clusters 85 | ``` 86 | Check [this post](https://github.com/mahmoudibrahim/genesorteR/issues/1) for more info. Also check out the examples in each function's documentation. Vignettes coming soon. 87 | 88 | Note that genesorteR does not currently accept expression matrices with negative entries. 89 | 90 | 91 | Fits with Seurat? 92 | ------ 93 | 94 | Yes it does! 95 | 96 | ```R 97 | #if "seuratObject" is the Seurat object that contains your data, I think this should work: 98 | gs = sortGenes(seuratObject@assays$RNA@data, Idents(seuratObject)) 99 | ``` 100 | 101 | 102 | --- 103 | 104 | *Hint: some real sorting here (click the picture!)...* 105 | 106 | 107 | [![IMAGE ALT TEXT HERE](http://img.youtube.com/vi/kPRA0W1kECg/0.jpg)](https://www.youtube.com/watch?v=kPRA0W1kECg) 108 | -------------------------------------------------------------------------------- /R/getTable.R: -------------------------------------------------------------------------------- 1 | #' getTable 2 | #' 3 | #' Summarize \code{sortGenes} and \code{getPValues} results in one data frame. 4 | #' 5 | #' \code{getTable} combines the results of sortGenes and getPValues in one table 6 | #' and also calculates the average fold-change of expression, allowing to select 7 | #' a fold-change cutoff and a p-value cutoff to determine variable genes. 8 | #' 9 | #' 10 | #' @param gs The output of \code{sortGenes}. 11 | #' @param pp The output of \code{getPValues}. 12 | #' @param fc_cutoff Default is 0, which means only genes that have an average 13 | #' fold-change higher than 0 for a given cluster are reported. Positive and negative 14 | #' numbers are allowed. Set to FALSE to switch off filtering on the average fold-change 15 | #' value. 16 | #' @param adjpval_cutoff A numeric adjusted p-value cutoff value. Default is 0.05. 17 | #' @param islog A logical value. TRUE (default) means the expression matrix supplied 18 | #' previously to \code{sortGenes} is in log space. 19 | #' @param pseudocount A numeric value. A pseudocount to add to the expression matrix before 20 | #' taking the log if \code{islog} is FALSE. 21 | #' 22 | #' @return \code{getTable} returns a data frame containing the gene name, the average log fold 23 | #' change, the adjusted p-value and the specificity score for all variable genes in each cluster. 24 | #' The data frame is sorted by the specificity score. Note that a gene may appear multiple times 25 | #' for multiple clusters. 26 | #' 27 | #' @author Mahmoud M Ibrahim 28 | #' @export 29 | #' @examples 30 | #' data(kidneyTabulaMuris) 31 | #' gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 32 | #' pp = getPValues(gs) 33 | #' tab = getTable(gs, pp) 34 | #' 35 | #' #A quick diagnostic plot (fold change correlates with specificity score) 36 | #' plot(tab$Average.Log.Fold.Change, tab$Specificity.Score, col = as.factor(tab$Cluster), pch = 20) 37 | #' 38 | #' #all variable genes 39 | #' unique(tab$Gene.Name) 40 | #' 41 | #' #To get all genes without any cutoffs, set adjpval_cutoff to >1 and fc_cutoff to FALSE 42 | #' tab = getTable(gs, pp, fc_cutoff = FALSE, adjpval_cutoff = 1.1) 43 | getTable = function(gs, pp, fc_cutoff = 0, adjpval_cutoff = 0.05, islog = TRUE, pseudocount = 1) { 44 | 45 | #pval 46 | tooearly = apply(pp$adjpval, 2, function(x) length(x[x < adjpval_cutoff])) 47 | toolate = which(tooearly == 0) 48 | 49 | if (length(toolate) > 0) { 50 | cl = getClassIndeces(gs$inputClass[-(which(gs$inputClass %in% names(tooearly[toolate])))]) 51 | nomen = names(gs$classProb[-toolate]) 52 | sp = gs$specScore[,-toolate] 53 | 54 | tooearly = names(which(apply(pp$adjpval[,-toolate], 1, function(x) any(x < adjpval_cutoff)))) 55 | } else { 56 | cl = getClassIndeces(gs$inputClass) 57 | nomen = names(gs$classProb) 58 | sp = gs$specScore 59 | 60 | tooearly = names(which(apply(pp$adjpval, 1, function(x) any(x < adjpval_cutoff)))) 61 | } 62 | 63 | 64 | if (length(tooearly) > 0) { 65 | pv = pp$adjpval[which(rownames(pp$adjpval) %in% tooearly),] 66 | } else { 67 | stop("No genes passing the p-value cutoff were found!") 68 | } 69 | 70 | 71 | 72 | #fc 73 | toolate = which(rownames(gs$inputMat) %in% tooearly) 74 | if (!islog) { 75 | mat = log(gs$inputMat[toolate,] + pseudocount) 76 | } else { 77 | mat = gs$inputMat[toolate,] 78 | } 79 | 80 | fc = do.call(cbind, lapply(cl, function(clx) (Matrix::rowMeans(mat[,clx])) - (Matrix::rowMeans(mat[,-clx])))) 81 | colnames(fc) = nomen 82 | if (is.numeric(fc_cutoff)) { 83 | tooearly = names(which(apply(fc, 1, function(x) any(x > fc_cutoff)))) 84 | toolate = which(rownames(fc) %in% tooearly) 85 | if (length(toolate) > 0) { 86 | fc = fc[toolate,] 87 | } else { 88 | stop("No genes passing the p-value and fold-change cutoffs were found!") 89 | } 90 | } 91 | 92 | #table 93 | pv = pv[,which(colnames(pv) %in% colnames(fc))] 94 | nm = intersect(rownames(fc), rownames(pv)) 95 | fc = fc[which(rownames(fc) %in% nm),] 96 | pv = pv[which(rownames(pv) %in% nm),] 97 | sp = sp[which(rownames(sp) %in% nm),] 98 | fc = fc[order(rownames(fc)),] 99 | pv = pv[order(rownames(pv)),] 100 | sp = sp[order(rownames(sp)),] 101 | 102 | tab = data.frame(rep(rownames(fc), ncol(fc)), c(fc), c(pv), c(as.matrix(sp)), rep(colnames(fc), each = nrow(fc))) 103 | colnames(tab) = c("Gene.Name", "Average.Log.Fold.Change","Adjusted.pvalue","Specificity.Score","Cluster") 104 | 105 | if (is.numeric(fc_cutoff)) { 106 | toolate = which((tab[,2] > fc_cutoff) & (tab[,3] < adjpval_cutoff)) 107 | tab = tab[toolate,] 108 | } else { 109 | toolate = which(tab[,3] < adjpval_cutoff) 110 | tab = tab[toolate,] 111 | } 112 | tab = tab[order(tab$Specificity.Score, decreasing = TRUE),] 113 | 114 | 115 | return(tab) 116 | } 117 | -------------------------------------------------------------------------------- /R/getClassAUC.R: -------------------------------------------------------------------------------- 1 | #' getClassAUC 2 | #' 3 | #' getClassAUC implements one way to investigate clustering quality. It processes the 4 | #' output of \code{sortGenes} to obtain a curve for each cell cluster for all 5 | #' gene specificity scores against their ranking in the cluster. The Area Under 6 | #' the Curve (AUC) can be used as a measure of clustering quality in terms of the 7 | #' possibility to identify cell clusters using a few marker genes. See Details. 8 | #' 9 | #' Given the specificity score for all genes in a certain cell cluster, we can 10 | #' assume that a well-separated easily-identified cell cluster will have a 11 | #' relatively small number of genes that have a very high specificity score. Top 12 | #' marker genes for a cluster that is poorly separated from other cell 13 | #' clusters will have average or low specificity scores. Sorting the genes for 14 | #' each cell cluster by their specificity scores and plotting the scaled scores 15 | #' in order creates a curve that should be far from the diagonal for 16 | #' well-separated clusters but close to the diagonal for poorly-separated 17 | #' clusters. The AUC of this curve can be used to quantify this intuition and 18 | #' estimate a clustering quality metric. 19 | #' 20 | #' 21 | #' @param gs A list containing \code{$specScore} sparse matrix. Typically the 22 | #' output of \code{sortGenes()}. 23 | #' @param markers A character vector of gene names to restrict this analysis to. 24 | #' See Details. 25 | #' @param plotCurves Should a plot be drawn? default value is TRUE. 26 | #' @param colors Color palette for the plot. 27 | #' 28 | #' @seealso \code{getMarkers} returns a cell cluster Shannon index that tends to 29 | #' correlate well with the AUC metric returned by \code{getClassAUC}. 30 | #' @return \code{getClassAUC} returns a numeric vector of length 31 | #' \code{ncol($specScore)} that contains the AUC for each cell cluster. 32 | #' @export 33 | #' @author Mahmoud M Ibrahim 34 | #' @examples 35 | #' #randomly generated expression matrix and cell clusters 36 | #' set.seed(1234) 37 | #' exp = matrix(sample(0:20,1000,replace=TRUE), ncol = 20) 38 | #' rownames(exp) = sapply(1:50, function(x) paste0("g", x)) 39 | #' cellType = sample(c("cell type 1","cell type 2"),20,replace=TRUE) 40 | #' sg = sortGenes(exp, cellType) 41 | #' classAUC = getClassAUC(sg) 42 | #' 43 | #' #"reasonably" separated clusters 44 | #' data(sim) 45 | #' sg = sortGenes(sim$exp, sim$cellType) 46 | #' classAUC = getClassAUC(sg) 47 | #' 48 | #' #real data with three well separated clusters 49 | #' data(kidneyTabulaMuris) 50 | #' sg = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 51 | #' classAUC = getClassAUC(sg) 52 | getClassAUC = function(gs, markers = NULL, plotCurves = TRUE, colors = NULL) { 53 | 54 | 55 | if (is.null(colors)) { 56 | colors = c("#d64e3c7F","#7dd5547F","#8641c67F","#cfca457F","#7778cb7F","#59803d7F","#d04d9c7F","#73d6a87F","#492f607F","#ccc4977F","#7f343b7F","#72acc07F","#b97d407F","#c796b57F","#45483a7F", "#A020F07F","#00FF007F","#FFFF007F") 57 | } 58 | 59 | auc = rep(0, length = ncol(gs$specScore)) 60 | if (is.null(markers)) { 61 | for (i in 1:ncol(gs$specScore)) { 62 | auc[i] = fastAUC((score(gs$specScore[order(gs$specScore[,i], decreasing=F),i])),(score(1:nrow(gs$specScore)))) 63 | } 64 | 65 | if (plotCurves == TRUE) { 66 | plot((score(gs$specScore[order(gs$specScore[,1], decreasing=F),1])), (score(1:nrow(gs$specScore))), type = "l", col = colors[1], lwd = 4, ylab = "Genes (Increasing Specificity Score)", xlab = "Scaled Specificity Score") 67 | lines(seq(0,1,length.out = 100), (seq(0,1,length.out=100)), lty = 2, col = "#99999940", lwd = 3) 68 | for (i in 2:ncol(gs$specScore)) { 69 | lines((score(gs$specScore[order(gs$specScore[,i], decreasing=F),i])), (score(1:nrow(gs$specScore))), type = "l", col = colors[i], lwd = 4) 70 | } 71 | legend("bottomright", legend = colnames(gs$specScore), pch=23, col=colors, pt.bg=colors, pt.cex=2, cex=1, bty="n") 72 | } 73 | 74 | } else { 75 | temp = gs$specScore[which(rownames(gs$specScore) %in% markers),] 76 | for (i in 1:ncol(gs$specScore)) { 77 | auc[i] = fastAUC((score(temp[order(temp[,i], decreasing=F),i])), score(1:nrow(temp))) 78 | } 79 | 80 | if (plotCurves == TRUE) { 81 | plot((score(temp[order(temp[,1], decreasing=F),1])), score(1:nrow(temp)), type = "l", col = colors[1], lwd = 4, ylab = "Genes (Increasing Specificity Score)", xlab = "Scaled Specificity Score") 82 | lines(seq(0,1,length.out = 100), (seq(0,1,length.out=100)), lty = 2, col = "#99999940", lwd = 3) 83 | for (i in 2:ncol(gs$specScore)) { 84 | lines((score(temp[order(temp[,i], decreasing=F),i])), score(1:nrow(temp)), type = "l", col = colors[i], lwd = 4) 85 | } 86 | legend("bottomright", legend = colnames(gs$specScore), pch=23, col=colors, pt.bg=colors, pt.cex=2, cex=1, bty="n") 87 | } 88 | } 89 | 90 | names(auc) = colnames(gs$specScore) 91 | return(auc) 92 | 93 | } 94 | -------------------------------------------------------------------------------- /R/getMarkers.R: -------------------------------------------------------------------------------- 1 | #' getMarkers 2 | #' 3 | #' getMarkers processes the output of \code{sortGenes} to select a relatively 4 | #' small set of marker genes. 5 | #' 6 | #' 7 | #' getMarkers relies on calculating an entropy-like metric (called here the Gene 8 | #' Specificity Shannon Index) calculated on the scaled gene-cluster specificity 9 | #' score. The intuition is that genes with low Shannon Index are either lowly 10 | #' expressed or highly specific to one or few cell clusters. Therefore, we select 11 | #' the top n\% of genes according to the scaled specificity score and then cluster 12 | #' those genes based on their Shannon Index into genes with high Shannon Index 13 | #' and genes with low Shannon Index. \code{n} is controlled by \code{quant}, 14 | #' the default value 0.99 means top 1 \code{%} of genes. Using lower values up to 15 | #' 0.95 may be ok but lower values than 0.95 are not recommended nor necessary. It 16 | #' can be increased to 0.999 for example to obtain a smaller set of genes, especially 17 | #' for data with many cell clusters. Scaling the specificity score for each cluster 18 | #' is done to try to guarantee that markers for each cluster will eventually be 19 | #' selected even if the cluster is not absolutely well-separated. 20 | #' 21 | #' It can also return the mutual information between each gene and cell clusters, 22 | #' as well as a Cluster Shannon Index, indicating how well separated cell clusters are 23 | #' from each other. Cluster Shannon Index is calculated on the scaled specificity score 24 | #' of selected marker genes for each cluster. The intuition is that, when restricted to 25 | #' top marker genes, well-defined clusters will have few high scoring genes 26 | #' (low Cluster Shannon Index). 27 | #' 28 | #' @param gs The output of \code{sortGenes()}. 29 | #' @param quant A number greater than zero and smaller than one. 0.99 by 30 | #' default. See Details. 31 | #' @param mutualInfo Logical. If \code{TRUE}, the mutual information between 32 | #' gene expression and cell clustering will be returned for each gene. \code{FALSE} 33 | #' by default. 34 | #' @param classEnt Logical. If \code{TRUE}, a "Cluster Shannon Index" is 35 | #' returned for each cluster. See Details. \code{FALSE} by default. 36 | #' @return \code{getMarkers} returns a list with the following components: 37 | #' \item{markers}{A character vector containing the names of selected marker 38 | #' features.} \item{maxScaledSpecScore}{A numeric vector of length 39 | #' \code{nrow(gs$specScore)}, including the maximum scaled specificity score for 40 | #' each gene across all cell clusters.} \item{gene_shannon_index}{A numeric vector 41 | #' of the same length as \code{maxScaledSpecScore}, including the Gene Shannon 42 | #' Index for each gene. See Details.} \item{mutInfo}{A numeric vector of the 43 | #' same length as \code{maxScaledSpecScore}, including the mutual information 44 | #' between the expression of each gene and the cell clustering.} 45 | #' \item{classEntropy}{A numeric vector of the same length as 46 | #' \code{ncol(specScore)}, including the Class Shannon Index for each cluster 47 | #' based on the selected marker genes.} 48 | #' @author Mahmoud M Ibrahim 49 | #' @export 50 | #' @examples 51 | #' #randomly generated data and cell clusters, almost no markers are found 52 | #' set.seed(1234) 53 | #' exp = matrix(sample(0:20,1000,replace=TRUE), ncol = 20) 54 | #' rownames(exp) = sapply(1:50, function(x) paste0("g", x)) 55 | #' cellType = sample(c("cell type 1","cell type 2"),20,replace=TRUE) 56 | #' sg = sortGenes(exp, cellType) 57 | #' mm = getMarkers(sg,quant=0.95) 58 | #' length(mm$markers) #only one marker gene was found 59 | #' 60 | #' 61 | #' #"reasonably" separated clusters, with a few clear markers 62 | #' data(sim) 63 | #' gs = sortGenes(sim$exp, sim$cellType) 64 | #' mm = getMarkers(gs,quant=0.95) 65 | #' length(mm$markers) 66 | #' 67 | #' #real data with three well separated clusters 68 | #' data(kidneyTabulaMuris) 69 | #' gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 70 | #' mm = getMarkers(gs, quant = 0.99) 71 | #' length(mm$markers) #we found 109 candidate markers 72 | #' #we want to get a more focused list: 73 | #' mm = getMarkers(gs, quant = 0.999) 74 | #' length(mm$markers) #11 genes that can alone descriminate between the cell types 75 | #' @seealso 76 | #' getPValues 77 | getMarkers = function(gs, quant = 0.99, mutualInfo = FALSE, classEnt = FALSE) { 78 | 79 | scored = apply(gs$specScore, 2, score) 80 | ent = apply(scored, 1, getEntropy) 81 | maxi = apply(scored, 1, max) 82 | ww = which(maxi > quantile(maxi, probs=quant)) 83 | m = Mclust(ent[ww], 2, modelNames="E", verbose = FALSE) 84 | markers = names( which(m$classification == (which.min(m$parameters$mean)) ) ) 85 | 86 | mutInfo = NULL 87 | if (mutualInfo == TRUE) { 88 | mutInfo = apply(gs$binary, 1, function(x) getMutInfo(x,gs$inputClass)) 89 | } 90 | 91 | classEntropy = NULL 92 | if (classEnt == TRUE) { 93 | classEntropy = apply(scored, 2, getEntropy) 94 | names(classEntropy) = colnames(gs$specScore) 95 | } 96 | 97 | return(list(gene_shannon_index = ent, maxScaledSpecScore = maxi, markers = markers, mutInfo = mutInfo, classEntropy = classEntropy)) 98 | 99 | } 100 | -------------------------------------------------------------------------------- /R/getPValues.R: -------------------------------------------------------------------------------- 1 | #' getPValues 2 | #' 3 | #' getPValues performs a permutation test on the gene-cell type specificity 4 | #' score to obtain a p-value value on each gene-cell type specificity score. The 5 | #' permutation keeps everything the same except that cell type assignments are 6 | #' permuted between the cells (but note that cell type proportions are also kept 7 | #' the same). This function is a way to select all differentially expressed 8 | #' genes between all cell classes globally in a dataset in one go or to define 9 | #' differentially expressed genes in a specific cell cluster. 10 | #' 11 | #' @param gs The output of \code{sortGenes()}. 12 | #' @param numPerm The number of permutations to do. The default value 5 is to 13 | #' ensure quick running time for very large datasets but can be increased to 14 | #' increase the power of the permutation test, see Details. 15 | #' @param correctMethod The method used to correct p-values for multiple 16 | #' hypothesis testing. Any valid input to "method" in \code{p.adjust} is 17 | #' allowed. p-value correction is done on a gene-by-gene basis. 18 | #' @param testGenes A character vector of gene names to restrict the output 19 | #' p-values to. 20 | #' @param subsetCells A numeric vector of cell indeces to restrict the 21 | #' permutation to. Note that the selected cells should still contain at least 22 | #' one cell from each of the cell clusters contained in \code{$specScore}. 23 | #' Note this option is still experimental and might not give consistent 24 | #' results. 25 | #' @param cores An integer greater than zero (1 by default) that indicates how 26 | #' many cores to use for parallelization using mclapply. 27 | #' @param seed The seed for random permutations. 28 | #' 29 | #' @return \code{getPValues} returns a list with the following components: 30 | #' \item{permuteVal}{A sparse matrix with as many rows as genes and as many 31 | #' columns as \code{ncol($specScore) * numPerm}, containing the specificity 32 | #' score matrices for all permutations concatenated after each other 33 | #' column-wise.} \item{startIndeces}{A numeric vector of length \code{numPerm} 34 | #' that indicates the starting column for each performed permutation in 35 | #' \code{permuteVal}} \item{pval}{A matrix with as many rows as genes and 36 | #' columns as \code{ncol($specScore)}, containing the p-values for the null 37 | #' hypothesis that the gene is not highly specific to a cell cluster is true.} 38 | #' \item{adjpval}{A matrix with the same size as \code{pval}, containing the 39 | #' corrected p-values using the method specified in \code{correctMethod}} 40 | #' @export 41 | #' @author Mahmoud M Ibrahim 42 | #' @examples 43 | #' data(kidneyTabulaMuris) 44 | #' gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 45 | #' pp = getPValues(gs) 46 | #' #obtain genes that are "differentially expressed" in at least one cluster 47 | #' markers = names(which(apply(pp$adjpval, 1, function(x) any(x < 0.01)))) 48 | #' 49 | #' @seealso 50 | #' getMarkers 51 | getPValues = function(gs, numPerm = 5, correctMethod = "BH", testGenes = NULL, subsetCells = NULL, cores = 1, seed = 111) { 52 | 53 | #recompute without non-binary genes 54 | takeout = which(Matrix::rowSums(gs$binary) == ncol(gs$binary)) 55 | if (length(takeout) > 0) { 56 | gs = sortGenes(gs$binary[-takeout,], gs$inputClass, binarizeMethod = "naive", cores = cores) 57 | } 58 | 59 | ngroup = ncol(gs$specScore) 60 | ngene = nrow(gs$specScore) 61 | mm = Matrix::sparseMatrix(1, 1, dims = c(ngene, (ngroup * numPerm))) 62 | mm = mm * 1 63 | dd1L = rep(0, length = numPerm) 64 | 65 | #permutation 66 | set.seed(seed) 67 | for (i in 1:numPerm) { 68 | dd1 = (ngroup * i) - (ngroup - 1) 69 | dd2 = (ngroup * i) 70 | mm[,dd1:dd2] = getPerma(gs, subsetCells = subsetCells, cores = cores) 71 | dd1L[i] = dd1 72 | } 73 | rownames(mm) = rownames(gs$specScore) 74 | ee = ecdf(as.vector(mm@x)) 75 | nn = length(as.vector(mm@x)) 76 | 77 | #getting pvalues 78 | if (is.null(testGenes)) { 79 | pval = matrix(ee(as.matrix(gs$specScore)), ncol = ncol(gs$specScore), byrow = FALSE) * nn 80 | pval = nn - pval 81 | pval = (pval + 1) / (nn + 1) 82 | 83 | if (cores == 1) { 84 | padj = do.call(rbind, lapply(1:ngene, function(k) p.adjust(pval[k,], method = correctMethod))) 85 | } else { 86 | padj = do.call(rbind, mclapply(1:ngene, function(k) p.adjust(pval[k,], method = correctMethod), mc.cores = cores)) 87 | } 88 | rownames(padj) = rownames(gs$specScore) 89 | rownames(pval) = rownames(gs$specScore) 90 | 91 | } else { 92 | wgene = which(rownames(gs$specScore) %in% testGenes) 93 | ngeneT = length(wgene) 94 | if (ngeneT != length(testGenes)) { 95 | warning("Some of the genes you specified with 'testGenes' were not found. Were they filtered out by 'sortGenes()?'") 96 | } 97 | namesT = rownames(gs$specScore)[wgene] 98 | 99 | pval = matrix(ee(as.matrix(gs$specScore[wgene,])), ncol = ncol(gs$specScore), byrow = FALSE) * nn 100 | pval = nn - pval 101 | pval = (pval + 1) / (nn + 1) 102 | 103 | 104 | if (cores == 1) { 105 | padj = do.call(rbind, lapply(1:ngeneT, function(k) p.adjust(pval[k,], method = correctMethod))) 106 | } else { 107 | padj = do.call(rbind, mclapply(1:ngeneT, function(k) p.adjust(pval[k,], method = correctMethod), mc.cores = cores)) 108 | } 109 | rownames(padj) = namesT 110 | rownames(pval) = namesT 111 | } 112 | 113 | colnames(padj) = colnames(gs$specScore) 114 | colnames(pval) = colnames(gs$specScore) 115 | colnames(mm) = rep(colnames(gs$specScore), numPerm) 116 | return(list(permuteVal = mm, startIndeces = dd1L, pval = pval, adjpval = padj)) 117 | 118 | } 119 | -------------------------------------------------------------------------------- /man/sortGenes.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sortGenes.R 3 | \name{sortGenes} 4 | \alias{sortGenes} 5 | \title{sortGenes} 6 | \usage{ 7 | sortGenes( 8 | x, 9 | classLabels, 10 | binarizeMethod = "median", 11 | TF_IDF = FALSE, 12 | returnInput = TRUE, 13 | cores = 1 14 | ) 15 | } 16 | \arguments{ 17 | \item{x}{A numeric (sparse) matrix. It will be coerced to a dgCMatrix sparse 18 | matrix. Rows represent genes, columns represent cells.} 19 | 20 | \item{classLabels}{A numeric or character vector or a factor of the same 21 | length as ncol(x) that represents cell cluster assignments. It will be 22 | coerced to a factor whose levels are the cell cluster names.} 23 | 24 | \item{binarizeMethod}{Either "median" (default) or "naive" or "adaptiveMedian" or a numeric cutoff. 25 | See Details.} 26 | 27 | \item{TF_IDF}{Return the TF-IDF weigts on the cluster level? \code{FALSE} by 28 | default. See Details.} 29 | 30 | \item{returnInput}{Return the input matrix and cell classes? \code{TRUE} by 31 | default. See Details.} 32 | 33 | \item{cores}{An integer greater than zero (1 by default) that indicates how 34 | many cores to use for parallelization using mclapply.} 35 | } 36 | \value{ 37 | \code{sortGenes} returns a list with the following components: 38 | \item{binary}{The binarized gene expression matrix. A sparse matrix of 39 | class dgCMatrix.} \item{cutoff}{The cutoff value 40 | used to binarize the gene expression matrix. Anything lower than this value 41 | was set to zero.} \item{removed}{A numeric vector containing the row 42 | indeces of genes that were removed because they were not expressed in any 43 | cells after binarization. If none were removed, this will be \code{NULL}.} 44 | \item{geneProb}{A numeric vector whose length is equal to nrow(binary) that 45 | lists the fraction of cells in which a gene was detected.} \item{condGeneProb}{A 46 | sparse matrix of class dgCMatrix with as many rows as nrow(binary) and as 47 | many columns as the number of cell clusters. It includes the conditional 48 | probability of observing a gene in a cluster.} \item{postClustProb}{A 49 | sparse matrix of class dgCMatrix with the same size as \code{condGeneProb}, 50 | containing the posterior probability that a cell belongs to a certain 51 | cluster or type given that the gene was observed.} \item{specScore}{A 52 | sparse matrix of class dgCMatrix with the same size as \code{condGeneProb}, 53 | containing a specificity score for each gene in each cell cluster. See 54 | Details.} \item{classProb}{A numeric vector whose length is equal to the 55 | number of cell clusters, containing the fraction of cells belonging to each 56 | cluster.} \item{inputMat}{the input \code{x} matrix, after being coerced 57 | to a sparse matrix of class dgCMatrix.} \item{inputClass}{the input 58 | \code{classLabels} after being coerced to a factor.} 59 | } 60 | \description{ 61 | sortGenes is the main function of the genesorteR package. It takes a gene 62 | expression matrix and cell cluster assignments. It binarizes the expression 63 | matrix and calculates empirical statistics on gene expression in each 64 | cluster including a specificity score that can be used to rank genes in cell 65 | clusters. 66 | } 67 | \details{ 68 | When \code{binarizeMethod} is "median", expression matrix binarization is 69 | done by estimating a cutoff value uniformly on all values in the matrix. 70 | This is equal to the median of all non-zero entries in the matrix and is 71 | returned in \code{cutoff}. When binarizeMethod is "adaptiveMedian", 72 | expression values of genes are clustered to obtain groups of genes based 73 | on expression level, then the "median" method is applied to each group 74 | separately. This assumes the matrix supplied in \code{x} is log scaled. 75 | When binarizeMethod is "naive", all non-zero entries are kept and the 76 | minimum value of non-zero entries is returned in \code{cutoff}. When the 77 | input matrix \code{x} has already been binarized, set \code{binarizeMethod} 78 | to "naive". You can set a specific cutoff value for binarization, by 79 | setting \code{binarizeMethod} to a numeric value >= 0. 80 | 81 | The specificity scores balance the posterior probability of observing a cell 82 | cluster given the gene (gene-cluster specificity) with its conditional 83 | probability given the cluster (a measure of gene expression). This ensures 84 | that highly specific genes are also highly expressed. The \code{specScore} 85 | matrix is considered the main output of this function, and on which many of the 86 | remaining calculations by other functions in the \code{genesorteR} package 87 | are performed. The values in this matrix can be used to rank features 88 | (genes in scRNA-Seq) in clusters. 89 | 90 | When \code{TF_IDF} is "TRUE", Term Frequency-Inverse Document Frequency weights 91 | for each gene in each cell cluster will also be returned. The analogy here is 92 | that each cell cluster represents a "document", and each gene a "term". TF-IDF 93 | was proposed in the famous paper by KF Jones, 1972 (doi:10.1108/eb026526). 94 | 95 | Note that if returnInput is set to FALSE (input expression matrix will no be 96 | returned in the output), many of the other functions that accept the output of 97 | \code{sortGenes} will break. 98 | 99 | \code{sortGenes} can in principle be applied to both a raw count matrix or a 100 | normalized log-count expression matrix. 101 | } 102 | \examples{ 103 | data(kidneyTabulaMuris) 104 | #basic functionality 105 | gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 106 | 107 | #the top 10 genes for each cluster by specificity scores 108 | top_genes = apply(gs$specScore, 2, function(x) names(head(sort(x, decreasing = TRUE), n = 10))) 109 | 110 | #the same top 10 genes but using the plotTopMarkerHeat function 111 | plotTopMarkerHeat(gs, top_n = 10, outs = TRUE, plotheat = FALSE) 112 | 113 | #naive binarization keeps any non-zero input in the input matrix 114 | gs_naive = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType, binarizeMethod = "naive") 115 | 116 | #different genes? 117 | plotTopMarkerHeat(gs_naive, top_n = 10, outs=TRUE, plotheat=FALSE) 118 | } 119 | \author{ 120 | Mahmoud M Ibrahim 121 | } 122 | -------------------------------------------------------------------------------- /R/bkend.R: -------------------------------------------------------------------------------- 1 | #rescale a vector so that the highest value is 1 and lowest is 0 2 | score = function(x) { 3 | x = ((x-min(x))/(max(x)-min(x))) 4 | return(x) 5 | } 6 | 7 | #binarize a gene expression matrix 8 | binarize = function(x, method = "median") { 9 | 10 | if (method == "median") { 11 | pi = median(x@x) 12 | } else if (method == "mean") { 13 | pi = mean(x@x) 14 | } else if (method == "naive") { 15 | pi = min(x@x) 16 | } else if (method == "adaptiveMedian") { 17 | mm = Mclust(Matrix::rowSums(x), 1:20, modelNames=c("V"), verbose = FALSE) 18 | if (mm$G == 1) { 19 | stop("Error: you set binarizeMethod to adaptiveMedian but the optimal number of gene groups based on average expression is 1. Please use a different binarization method or use a different gene expression normalization. Also please consider reporting this error to mmibrahim@pm.me or on https://github.com/mahmoudibrahim/genesorteR/issues (preferred).") 20 | } else { 21 | pi = rep(0, mm$G) 22 | for (i in 1:mm$G) { 23 | pi[i] = median(x[which(mm$classification == i),]@x) 24 | } 25 | } 26 | } else if ((is.numeric(method)) & (method >= 0)) { 27 | pi = method 28 | } else { 29 | stop("Unrecognized binarization method! genesorteR stopped.") 30 | } 31 | 32 | 33 | if (method == "adaptiveMedian") { 34 | 35 | mat = list() 36 | for (i in 1:mm$G) { 37 | tx = x[which(mm$classification == i),] 38 | ww = which(tx@x >= pi[i]) 39 | dp = diff(tx@p) 40 | colInd = (rep(seq_along(dp),dp))[ww] 41 | rowInd = (tx@i+1)[ww] 42 | genes = rownames(tx) 43 | mat[[i]] = Matrix::sparseMatrix(rowInd[1], colInd[1], dims=tx@Dim) 44 | mat[[i]][cbind(rowInd,colInd)] = 1 45 | mat[[i]] = as(mat[[i]], "dgCMatrix") 46 | rownames(mat[[i]]) = genes 47 | } 48 | mat = do.call(rbind, mat) 49 | x = mat[match(rownames(x),rownames(mat)),] 50 | 51 | } else { 52 | 53 | ww = which(x@x >= pi) 54 | dp = diff(x@p) 55 | colInd = (rep(seq_along(dp),dp))[ww] 56 | rowInd = (x@i+1)[ww] 57 | genes = rownames(x) 58 | x = Matrix::sparseMatrix(rowInd[1], colInd[1], dims=x@Dim) 59 | x[cbind(rowInd,colInd)] = 1 60 | x = as(x, "dgCMatrix") 61 | rownames(x) = genes 62 | } 63 | 64 | return(list(mat = x, cutoff = pi)) 65 | } 66 | 67 | 68 | #get prior probability for each gene across the entire data set 69 | getGeneProb = function(x) { 70 | ncell = ncol(x) 71 | 72 | probs = as.vector( (Matrix::rowSums(x)) / ncell ) 73 | names(probs) = rownames(x) 74 | 75 | return(probs) 76 | } 77 | 78 | 79 | #get the prior probability of each cluster across the entire data set 80 | getClassProb = function(x) { 81 | probs = table(x) / length(x) 82 | 83 | return(probs) 84 | } 85 | 86 | 87 | 88 | #get gene probability conditional on cluster 89 | getGeneConditionalCluster_stats = function(mat, classProb, classLabels, cores = 1) { 90 | 91 | lab = names(classProb) 92 | 93 | if (cores > 1) { 94 | geneProb = do.call(cbind, mclapply(1:length(lab), function(i) Matrix::rowMeans(mat[,which(classLabels == lab[i])]), mc.cores = cores)) 95 | } else { 96 | geneProb = do.call(cbind, lapply(1:length(lab), function(i) Matrix::rowMeans(mat[,which(classLabels == lab[i])]))) 97 | } 98 | 99 | geneProb = as(geneProb, "dgCMatrix") 100 | colnames(geneProb) = lab 101 | 102 | return(geneProb) 103 | 104 | } 105 | 106 | 107 | #get gene probability conditional on cluster 108 | getClusterPostGene = function(condMat, geneProb, classProb) { 109 | 110 | postProb = t(apply(log(condMat), 1, function(x) x + log(classProb))) 111 | postProb = exp(apply(postProb, 2, function(x) x - log(geneProb))) 112 | 113 | colnames(postProb) = names(classProb) 114 | postProb = as(postProb, "dgCMatrix") 115 | 116 | return(postProb) 117 | 118 | } 119 | 120 | 121 | #get gene-cluster specificity score 122 | getSpecScore = function(postMat, condMat) { 123 | 124 | specScore = exp(log(postMat) + log(condMat)) 125 | 126 | colnames(specScore) = colnames(condMat) 127 | specScore = as(specScore, "dgCMatrix") 128 | return(specScore) 129 | 130 | } 131 | 132 | 133 | #get scaled gene-cluster specificity score 134 | getScaledSpecScore = function(postMat, condMat) { 135 | 136 | specScore = postMat * condMat 137 | specScore = apply(specScore, 2, score) 138 | 139 | colnames(specScore) = colnames(condMat) 140 | specScore = as(specScore, "dgCMatrix") 141 | return(specScore) 142 | 143 | } 144 | 145 | #get entropy of a probability vector 146 | getEntropy = function(x) { 147 | ent = 0 148 | w = which(x > 0) 149 | if (length(w) > 0) { 150 | w = x[w] 151 | ent = -(sum(w * (log(w)))) 152 | } 153 | return(ent) 154 | } 155 | 156 | #get TF-IDF on a cell cluter level 157 | getClusterTFIDF = function(condMat) { 158 | idf = log(ncol(condMat)) - log(Matrix::rowSums(binarize(condMat, method = "naive")$mat)) 159 | tf_idf = exp(log(condMat) + log(idf)) 160 | tf_idf = as(tf_idf, "dgCMatrix") 161 | return(tf_idf) 162 | } 163 | 164 | #get mutual information from two vectors 165 | getMutInfo = function(x, y) { 166 | 167 | ##check lengths of both vectors is equal 168 | if (length(y) == length(x)) { 169 | hx = getEntropy(table(x) / length(x)) 170 | hy = getEntropy(table(y) / length(y)) 171 | hxy = getEntropy(table(x,y) / length(y)) 172 | 173 | mutInfo = hx + hy - hxy 174 | } else { 175 | stop("Couldn't calculate mutual information!") 176 | } 177 | 178 | return(mutInfo) 179 | } 180 | 181 | #perform permutations 182 | getPerma = function(gs, subsetCells = NULL, cores = 1) { 183 | 184 | if (is.null(subsetCells)) { 185 | shuff = base::sample(gs$inputClass, length(gs$inputClass), replace = FALSE) 186 | condGeneCluster = getGeneConditionalCluster_stats(gs$binary, gs$classProb, shuff, cores = cores) 187 | clusterPostGene = getClusterPostGene(condGeneCluster, gs$geneProb, gs$classProb) 188 | specScore = getSpecScore(clusterPostGene, condGeneCluster) 189 | } else { 190 | shuff = base::sample(gs$inputClass[subsetCells], length(gs$inputClass[subsetCells]), replace = FALSE) 191 | condGeneCluster = getGeneConditionalCluster_stats(gs$binary[,subsetCells], gs$classProb, shuff, cores = cores) 192 | clusterPostGene = getClusterPostGene(condGeneCluster, gs$geneProb, gs$classProb) 193 | specScore = getSpecScore(clusterPostGene, condGeneCluster) 194 | } 195 | return(specScore) 196 | } 197 | 198 | #return area under the curve 199 | fastAUC = function(x, y) { 200 | da = ( (sum( (y - x) )) / length(x) ) * 2 201 | return(da) 202 | } 203 | 204 | #bin means of a vector, thanks to the mysterious user on stackoverflow: https://stackoverflow.com/a/43635971/2435654 205 | binMean = function (vec, every, na.rm = FALSE) { 206 | n = length(vec) 207 | x = .colMeans(vec, every, n %/% every, na.rm) 208 | r = n %% every 209 | if (r) { 210 | x = c(x, mean.default(vec[(n - r + 1):n], na.rm = na.rm)) 211 | } 212 | return(x) 213 | } 214 | 215 | #getClassIndeces 216 | getClassIndeces = function(x) { 217 | uniq = unique(x) 218 | x = lapply(1:length(uniq), function(a) which(!is.na(match(x, uniq[a])))) 219 | return(x) 220 | } 221 | -------------------------------------------------------------------------------- /R/plotBinaryHeat.R: -------------------------------------------------------------------------------- 1 | #' plotBinaryHeat 2 | #' 3 | #' Plot a heatmap binarized values for a select set of genes or peaks across all 4 | #' cells. Optionally also cluster those genes. 5 | #' 6 | #'\code{plotBinaryHeat} is similar to \code{plotMarkerHeat} but works on 7 | #' the binarized matrix, plotting only 0s and 1s (for scRNA-Seq, this means ignoring 8 | #' expression values and just plotting whether the gene is expressed or not). 9 | #' If \code{averageCells} is > 1, the fraction of the averaged cells where the gene 10 | #' or peak was detected will be plotted (a number between 0 and 1). 11 | #' 12 | #' \code{clusterGenesK} parameter controls the number of gene clusters when 13 | #' \code{clusterGenes} is \code{TRUE}. By default, it is equal to the number of 14 | #' cell types/clusters. 15 | #' 16 | #' By default, the heatmap plots every single cell in one column, this might 17 | #' take forever if you have a lot of cells (would say >10k) or it can crash when 18 | #' you do not have enough RAM. If so, it might be good to set \code{averageCells} 19 | #' to \code{n} where \code{n} is the number of cells you 20 | #' want to average. For example, if \code{averageCells = 10}, every 10 cells will 21 | #' be averaged (without averaging across cell clusters) before plotting the heatmap. 22 | #' if \code{averageCells =< 1}, no averaging happens. Hints: (1) If you want one column 23 | #' per cell cluster, set \code{averageCells} to a very high number (larger than the 24 | #' number of cells in the largest cluster). (2) Gene clustering occurs after cell 25 | #' averaging, so averaging will be useful in this case to prevent running k-means on 26 | #' binary values. 27 | #' 28 | #' @param exp A matrix of *binary* (0s and 1s) expression values. For example, the one 29 | #' found in \code{sortGenes(...)$binary}. 30 | #' @param classes A vector or factor of cell classes, whose length is equal to 31 | #' \code{ncol(exp)}. 32 | #' @param markers A character vector of gene or peak names to plot in the heatmap. 33 | #' @param colors Color palette used for the heatmap. 34 | #' @param newOrder Reorder the clusters in the heatmap? See Examples. 35 | #' @param clusterGenes Cluster genes before plotting? 36 | #' @param clusterGenesK How many clusters should genes by clustered into? See 37 | #' Details. 38 | #' @param averageCells Plot averages of cells instead of individual cells. You 39 | #' can use this when you have a large number of cells. See Details. 40 | #' @param outs Should gene cluster output and pheatmap object be returned? FALSE 41 | #' by default. 42 | #' @param plotheat Should the heatmap be drawn? TRUE by default. 43 | #' @param gaps Should the heatmap have gaps between cell types and gene clusters? 44 | #' TRUE by default. 45 | #' @param seed Randomization seed used for gene clustering initialization. 46 | #' @return If \code{outs} is TRUE, \code{plotMarkerHeat} returns a list 47 | #' containing: \item{p}{The pheatmap object corresponding to the plot.} 48 | #' \item{gene_class_info}{Gene cluster assignments if gene clustering was 49 | #' requested. See Details.} \item{new_class_info}{The new order of cell 50 | #' clusters. See Examples.} 51 | #' @author Mahmoud M Ibrahim 52 | #' @export 53 | #' @examples 54 | #' data(kidneyTabulaMuris) 55 | #' gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 56 | #' mm = getMarkers(gs, quant = 0.999) 57 | #' 58 | #' #this plots a heatmap without reordering genes 59 | #' plotBinaryHeat(gs$binary, gs$inputClass, mm$markers) 60 | #' 61 | #' @seealso 62 | #' plotMarkerHeat 63 | plotBinaryHeat = function(exp, classes, markers, colors = colorRampPalette(c("white","black"))(n=100), newOrder = 1:length(unique(classes)), clusterGenes = FALSE, clusterGenesK = length(unique(classes)), averageCells = 0, outs = FALSE, plotheat = TRUE, gaps = TRUE, seed = 10) { 64 | 65 | classes = as.integer(as.factor(classes)) 66 | map = data.frame(oldO = 1:length(unique(classes)), newO = newOrder) 67 | classes = map$oldO[match(classes, map$newO)] 68 | 69 | 70 | temp = exp[which(rownames(exp) %in% markers),order(classes, decreasing = FALSE)] 71 | temp = temp[order(match(rownames(temp), markers)),] #catch error here? all clusters should be present after marker selection 72 | 73 | classesTemp = classes[order(classes, decreasing = FALSE)] 74 | if (averageCells > 1) { 75 | neh = lapply( 1:length(table(classesTemp)), function(i) rbind(apply(t(as.matrix(temp[,which(classesTemp == i)])), 2, function(x) binMean(x, averageCells))) ) 76 | 77 | nah = unlist(sapply(1:length(neh), function(x) rep(x,nrow(neh[[x]])))) 78 | temp = t( do.call(rbind, neh) ) 79 | colnames(temp) = nah 80 | } else { 81 | colnames(temp) = classesTemp 82 | } 83 | 84 | if (clusterGenes) { 85 | go = t(apply(temp, 1, function(x) x / (sqrt(sum(x^2))))) 86 | set.seed(seed) 87 | kk = kmeans(go, clusterGenesK, nstart = 10)$cluster 88 | temp = temp[order(kk, decreasing = FALSE),] 89 | } 90 | 91 | 92 | if (plotheat & (averageCells > 1)) { 93 | club = colnames(temp) #save column names 94 | cut = quantile(as.vector(temp), probs = 0.95, na.rm = TRUE) 95 | if (cut == 0) { 96 | cut = quantile(as.vector(temp), probs = 0.99, na.rm = TRUE) 97 | } 98 | if (cut == 0) { 99 | cut = 1 100 | warning("Could not find an appropriate value to threshold color scale. Matrix may be too sparse. Please consider reporting this warning to mmibrahim@pm.me or at https://github.com/mahmoudibrahim/genesorteR/issues (preferred)") 101 | } 102 | temp[temp > cut] = cut 103 | colnames(temp) = club #reassign column names 104 | } else {cut = 1} 105 | 106 | if (clusterGenes) { 107 | if (plotheat) { 108 | if (gaps) { 109 | p=pheatmap(temp, cluster_rows = FALSE, cluster_cols = FALSE, scale = "none", color = colors, display_numbers = F, fontsize = 5, show_colnames=FALSE, show_rownames=TRUE, breaks = seq(0,cut,length.out = 101), gaps_col = cumsum(table(as.integer(colnames(temp)))), gaps_row = cumsum(table(kk)), border_color = NA) 110 | } else { 111 | p=pheatmap(temp, cluster_rows = FALSE, cluster_cols = FALSE, scale = "none", color = colors, display_numbers = F, fontsize = 5, show_colnames=FALSE, show_rownames=TRUE, breaks = seq(0,cut,length.out = 101), border_color = NA) 112 | } 113 | } else {p = NULL} 114 | if (outs) { 115 | return(list(pheat = p, new_class_info = classes, gene_class_info = kk)) 116 | } 117 | } else { 118 | if (plotheat) { 119 | if (gaps) { 120 | p=pheatmap(temp, cluster_rows = FALSE, cluster_cols = FALSE, scale = "none", color = colors, display_numbers = F, fontsize = 5, show_colnames=FALSE, show_rownames=TRUE, breaks = seq(0,cut,length.out = 101), gaps_col = cumsum(table(as.integer(colnames(temp)))), border_color = NA) 121 | } else { 122 | p=pheatmap(temp, cluster_rows = FALSE, cluster_cols = FALSE, scale = "none", color = colors, display_numbers = F, fontsize = 5, show_colnames=FALSE, show_rownames=TRUE, breaks = seq(0,cut,length.out = 101), border_color = NA) 123 | } 124 | } else {p = NULL} 125 | if (outs) { 126 | return(list(pheat = p, new_class_info = classes)) 127 | } 128 | } 129 | 130 | } 131 | -------------------------------------------------------------------------------- /R/plotMarkerHeat.R: -------------------------------------------------------------------------------- 1 | #' plotMarkerHeat 2 | #' 3 | #' Plot a heatmap of expression values for a select set of genes across all cells. 4 | #' Optionally also cluster those genes. 5 | #' 6 | #' \code{clusterGenesK} parameter controls the number of gene clusters when 7 | #' \code{clusterGenes} is \code{TRUE}. By default, it is equal to the number of 8 | #' cell types/clusters. This is usually a good initial guess, the optimal 9 | #' number of clusters (what does that even mean?) is typically somewhere around 10 | #' this value in my subjective experience, unless there are many cell clusters. 11 | #' 12 | #' By default, the heatmap plots every single cell in one column, this might 13 | #' take forever if you have a lot of cells (would say >10k) or it can crash when 14 | #' you do not have enough RAM. If so, it might be good to set \code{averageCells} 15 | #' to \code{n} where \code{n} is the number of cells you 16 | #' want to average. For example, if \code{averageCells = 10}, every 10 cells will 17 | #' be averaged (without averaging across cell clusters) before plotting the heatmap. 18 | #' if \code{averageCells =< 1}, no averaging happens. Hints: (1) If you want one column 19 | #' per cell cluster, set \code{averageCells} to a very high number (larger than the 20 | #' number of cells in the largest cluster). (2) Gene clustering occurs after cell 21 | #' averaging, so averaging might be useful if the gene clusters you get do not make much sense 22 | #' without averaging (averaging will smooth out zeros). 23 | #' 24 | #' @param exp A matrix of expression values. Typically the one supplied to 25 | #' \code{sortGenes}. 26 | #' @param classes A vector or factor of cell classes, whose length is equal to 27 | #' \code{ncol(exp)}. 28 | #' @param markers A character vector of gene names to plot in the heatmap. 29 | #' @param colors Color palette used for the heatmap. 30 | #' @param newOrder Reorder the clusters in the heatmap? See Examples. 31 | #' @param clusterGenes Cluster genes before plotting? 32 | #' @param clusterGenesK How many clusters should genes by clustered into? See 33 | #' Details. 34 | #' @param averageCells Plot averages of cells instead of individual cells. You 35 | #' can use this when you have a large number of cells. See Details. 36 | #' @param outs Should gene cluster output and pheatmap object be returned? FALSE 37 | #' by default. 38 | #' @param plotheat Should the heatmap be drawn? TRUE by default. 39 | #' @param gaps Should the heatmap have gaps between cell types and gene clusters? 40 | #' TRUE by default. 41 | #' @param seed Randomization seed used for gene clustering initialization. 42 | #' @return If \code{outs} is TRUE, \code{plotMarkerHeat} returns a list 43 | #' containing: \item{p}{The pheatmap object corresponding to the plot.} 44 | #' \item{gene_class_info}{Gene cluster assignments if gene clustering was 45 | #' requested. See Details.} \item{new_class_info}{The new order of cell 46 | #' clusters. See Examples.} 47 | #' @author Mahmoud M Ibrahim 48 | #' @export 49 | #' @examples 50 | #' data(kidneyTabulaMuris) 51 | #' gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 52 | #' mm = getMarkers(gs, quant = 0.999) 53 | #' 54 | #' #this plots a heatmap without reordering genes 55 | #' plotMarkerHeat(gs$inputMat, gs$inputClass, mm$markers) 56 | #' 57 | #' #so now cluster genes and return the clustering: a better looking plot 58 | #' pp = plotMarkerHeat(gs$inputMat, gs$inputClass, mm$markers, clusterGenes=TRUE, outs=TRUE) 59 | #' pp$gene_class_info #cell clusters 60 | #' 61 | #' #reorder cell clusters in the heatmap 62 | #' plotMarkerHeat(gs$inputMat, gs$inputClass, mm$markers, clusterGenes=TRUE, newOrder = c(3,1,2)) 63 | #' 64 | #' #average every 4 cells to make a less intense heatmap 65 | #' plotMarkerHeat(gs$inputMat, gs$inputClass, mm$markers, clusterGenes=TRUE, newOrder = c(3,1,2), 66 | #' averageCells = 4) 67 | #' 68 | #' #only cluster genes, do not make plots 69 | #' pp = plotMarkerHeat(gs$inputMat, gs$inputClass, mm$markers, clusterGenes=TRUE, 70 | #' outs=TRUE, plotheat=FALSE) 71 | #' 72 | #' @seealso 73 | #' plotTopMarkerHeat 74 | plotMarkerHeat = function(exp, classes, markers, colors = colorRampPalette(rev(c("orangered4","orangered","gray90","dodgerblue","dodgerblue4")))(n=100), newOrder = 1:length(unique(classes)), clusterGenes = FALSE, clusterGenesK = length(unique(classes)), averageCells = 0, outs = FALSE, plotheat = TRUE, gaps = TRUE, seed = 10) { 75 | 76 | classes = as.integer(as.factor(classes)) 77 | map = data.frame(oldO = 1:length(unique(classes)), newO = newOrder) 78 | classes = map$oldO[match(classes, map$newO)] 79 | 80 | 81 | temp = exp[which(rownames(exp) %in% markers),order(classes, decreasing = FALSE)] 82 | temp = temp[order(match(rownames(temp), markers)),] #catch error here? all clusters should be present after marker selection 83 | 84 | classesTemp = classes[order(classes, decreasing = FALSE)] 85 | if (averageCells > 1) { 86 | neh = lapply( 1:length(table(classesTemp)), function(i) rbind(apply(t(as.matrix(temp[,which(classesTemp == i)])), 2, function(x) binMean(x, averageCells))) ) 87 | 88 | nah = unlist(sapply(1:length(neh), function(x) rep(x,nrow(neh[[x]])))) 89 | temp = t( do.call(rbind, neh) ) 90 | colnames(temp) = nah 91 | } else { 92 | colnames(temp) = classesTemp 93 | } 94 | 95 | if (clusterGenes) { 96 | go = t(apply(temp, 1, function(x) x / (sqrt(sum(x^2))))) 97 | set.seed(seed) 98 | kk = kmeans(go, clusterGenesK, nstart = 10)$cluster 99 | temp = temp[order(kk, decreasing = FALSE),] 100 | } 101 | 102 | 103 | if (plotheat) { 104 | club = colnames(temp) #save column names 105 | temp = t(apply(temp, 1, scale)) 106 | cut = quantile(as.vector(abs(temp)), probs = 0.95, na.rm = TRUE) 107 | temp[temp > cut] = cut 108 | temp[temp < -cut] = -cut 109 | colnames(temp) = club #reassign column names 110 | } 111 | 112 | 113 | if (clusterGenes) { 114 | if (plotheat) { 115 | if (gaps) { 116 | p=pheatmap(temp, cluster_rows = FALSE, cluster_cols = FALSE, scale = "none", color = colors, display_numbers = F, fontsize = 5, show_colnames=FALSE, show_rownames=TRUE, breaks = seq(-cut,cut,length.out = 101), gaps_col = cumsum(table(as.integer(colnames(temp)))), gaps_row = cumsum(table(kk)), border_color = NA) 117 | } else { 118 | p=pheatmap(temp, cluster_rows = FALSE, cluster_cols = FALSE, scale = "none", color = colors, display_numbers = F, fontsize = 5, show_colnames=FALSE, show_rownames=TRUE, breaks = seq(-cut,cut,length.out = 101), border_color = NA) 119 | } 120 | } else {p = NULL} 121 | if (outs) { 122 | return(list(pheat = p, new_class_info = classes, gene_class_info = kk)) 123 | } 124 | } else { 125 | if (plotheat) { 126 | if (gaps) { 127 | p=pheatmap(temp, cluster_rows = FALSE, cluster_cols = FALSE, scale = "none", color = colors, display_numbers = F, fontsize = 5, show_colnames=FALSE, show_rownames=TRUE, breaks = seq(-cut,cut,length.out = 101), gaps_col = cumsum(table(as.integer(colnames(temp)))), border_color = NA) 128 | } else { 129 | p=pheatmap(temp, cluster_rows = FALSE, cluster_cols = FALSE, scale = "none", color = colors, display_numbers = F, fontsize = 5, show_colnames=FALSE, show_rownames=TRUE, breaks = seq(-cut,cut,length.out = 101), border_color = NA) 130 | } 131 | } else {p = NULL} 132 | if (outs) { 133 | return(list(pheat = p, new_class_info = classes)) 134 | } 135 | } 136 | 137 | } 138 | -------------------------------------------------------------------------------- /R/sortGenes.R: -------------------------------------------------------------------------------- 1 | #' sortGenes 2 | #' 3 | #' sortGenes is the main function of the genesorteR package. It takes a gene 4 | #' expression matrix and cell cluster assignments. It binarizes the expression 5 | #' matrix and calculates empirical statistics on gene expression in each 6 | #' cluster including a specificity score that can be used to rank genes in cell 7 | #' clusters. 8 | #' 9 | #' When \code{binarizeMethod} is "median", expression matrix binarization is 10 | #' done by estimating a cutoff value uniformly on all values in the matrix. 11 | #' This is equal to the median of all non-zero entries in the matrix and is 12 | #' returned in \code{cutoff}. When binarizeMethod is "adaptiveMedian", 13 | #' expression values of genes are clustered to obtain groups of genes based 14 | #' on expression level, then the "median" method is applied to each group 15 | #' separately. This assumes the matrix supplied in \code{x} is log scaled. 16 | #' When binarizeMethod is "naive", all non-zero entries are kept and the 17 | #' minimum value of non-zero entries is returned in \code{cutoff}. When the 18 | #' input matrix \code{x} has already been binarized, set \code{binarizeMethod} 19 | #' to "naive". You can set a specific cutoff value for binarization, by 20 | #' setting \code{binarizeMethod} to a numeric value >= 0. 21 | #' 22 | #' The specificity scores balance the posterior probability of observing a cell 23 | #' cluster given the gene (gene-cluster specificity) with its conditional 24 | #' probability given the cluster (a measure of gene expression). This ensures 25 | #' that highly specific genes are also highly expressed. The \code{specScore} 26 | #' matrix is considered the main output of this function, and on which many of the 27 | #' remaining calculations by other functions in the \code{genesorteR} package 28 | #' are performed. The values in this matrix can be used to rank features 29 | #' (genes in scRNA-Seq) in clusters. 30 | #' 31 | #' When \code{TF_IDF} is "TRUE", Term Frequency-Inverse Document Frequency weights 32 | #' for each gene in each cell cluster will also be returned. The analogy here is 33 | #' that each cell cluster represents a "document", and each gene a "term". TF-IDF 34 | #' was proposed in the famous paper by Karen Spärk Jones, 1972 (doi:10.1108/eb026526). 35 | #' 36 | #' Note that if returnInput is set to FALSE (input expression matrix will no be 37 | #' returned in the output), many of the other functions that accept the output of 38 | #' \code{sortGenes} will break. 39 | #' 40 | #' \code{sortGenes} can in principle be applied to both a raw count matrix or a 41 | #' normalized log-count expression matrix. 42 | #' @param x A numeric (sparse) matrix. It will be coerced to a dgCMatrix sparse 43 | #' matrix. Rows represent genes, columns represent cells. 44 | #' @param classLabels A numeric or character vector or a factor of the same 45 | #' length as ncol(x) that represents cell cluster assignments. It will be 46 | #' coerced to a factor whose levels are the cell cluster names. 47 | #' @param binarizeMethod Either "median" (default) or "naive" or "adaptiveMedian" 48 | #' or a numeric cutoff. 49 | #' See Details. 50 | #' @param TF_IDF Return the TF-IDF weigts on the cluster level? \code{FALSE} by 51 | #' default. See Details. 52 | #' @param returnInput Return the input matrix and cell classes? \code{TRUE} by 53 | #' default. See Details. 54 | #' @param cores An integer greater than zero (1 by default) that indicates how 55 | #' many cores to use for parallelization using mclapply. 56 | #' @return \code{sortGenes} returns a list with the following components: 57 | #' \item{binary}{The binarized gene expression matrix. A sparse matrix of 58 | #' class dgCMatrix.} \item{cutoff}{The cutoff value 59 | #' used to binarize the gene expression matrix. Anything lower than this value 60 | #' was set to zero.} \item{removed}{A numeric vector containing the row 61 | #' indeces of genes that were removed because they were not expressed in any 62 | #' cells after binarization. If none were removed, this will be \code{NULL}.} 63 | #' \item{geneProb}{A numeric vector whose length is equal to nrow(binary) that 64 | #' lists the fraction of cells in which a gene was detected.} \item{condGeneProb}{A 65 | #' sparse matrix of class dgCMatrix with as many rows as nrow(binary) and as 66 | #' many columns as the number of cell clusters. It includes the conditional 67 | #' probability of observing a gene in a cluster.} \item{postClustProb}{A 68 | #' sparse matrix of class dgCMatrix with the same size as \code{condGeneProb}, 69 | #' containing the posterior probability that a cell belongs to a certain 70 | #' cluster or type given that the gene was observed.} \item{specScore}{A 71 | #' sparse matrix of class dgCMatrix with the same size as \code{condGeneProb}, 72 | #' containing a specificity score for each gene in each cell cluster. See 73 | #' Details.} \item{classProb}{A numeric vector whose length is equal to the 74 | #' number of cell clusters, containing the fraction of cells belonging to each 75 | #' cluster.} \item{inputMat}{the input \code{x} matrix, after being coerced 76 | #' to a sparse matrix of class dgCMatrix.} \item{inputClass}{the input 77 | #' \code{classLabels} after being coerced to a factor. \item{tf_idf}{If TF_IDF 78 | #' is TRUE, this will be a sparse matrix with TF-IDF weights, NULL otherwise.} 79 | #' @author Mahmoud M Ibrahim 80 | #' @export 81 | #' @examples 82 | #' data(kidneyTabulaMuris) 83 | #' #basic functionality 84 | #' gs = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType) 85 | #' 86 | #' #the top 10 genes for each cluster by specificity scores 87 | #' top_genes = apply(gs$specScore, 2, function(x) names(head(sort(x, decreasing = TRUE), n = 10))) 88 | #' 89 | #' #the same top 10 genes but using the plotTopMarkerHeat function 90 | #' plotTopMarkerHeat(gs, top_n = 10, outs = TRUE, plotheat = FALSE) 91 | #' 92 | #' #naive binarization keeps any non-zero input in the input matrix 93 | #' gs_naive = sortGenes(kidneyTabulaMuris$exp, kidneyTabulaMuris$cellType, binarizeMethod = "naive") 94 | #' 95 | #' #different genes? 96 | #' plotTopMarkerHeat(gs_naive, top_n = 10, outs=TRUE, plotheat=FALSE) 97 | sortGenes = function(x, classLabels, binarizeMethod = "median", TF_IDF = FALSE, returnInput = TRUE, cores = 1) { 98 | 99 | if (length(classLabels) != ncol(x)) { stop("Length of classLabels is not equal to the number of columns in the expression matrix.") } 100 | 101 | 102 | classLabels = as.factor(classLabels) 103 | if (length(setdiff(levels(classLabels), classLabels)) > 0) { 104 | classLabels = classLabels[,drop = TRUE] #drop nonoccuring levels 105 | warning("A Friendly Warning: The cell type factor had some empty levels. You probably don't need to do anything. Cell types were likely filtered beforehand.") 106 | } 107 | 108 | if (length(levels(classLabels)) < 2) { 109 | stop("Sorry but that's an error. classLabels specifies only one cell cluster!") 110 | } 111 | 112 | ww = which(as.vector(table(classLabels)) == 1) 113 | if (length(ww) > 0) { 114 | stop("Sorry but that's an error. sortGenes() won't continue. There were some cell types comprised of only one cell. Although it's technically possible to have this, something is likely off with your cell clustering.") 115 | } 116 | 117 | classLabelsNum = as.integer(classLabels) 118 | classLabelsLab = levels(classLabels) 119 | 120 | x = as(x, "dgCMatrix") 121 | 122 | xbin = binarize(x, method = binarizeMethod) 123 | 124 | rem = which((Matrix::rowSums(xbin$mat)) == 0) 125 | if (length(rem) > 0) { 126 | xbin$mat = xbin$mat[-rem,] 127 | warning("A Friendly Warning: Some genes were removed because they were zeros in all cells after binarization. You probably don't need to do anything but you might want to look into this. Maybe you forgot to pre-filter the genes? You can also use a different binarization method. Excluded genes are available in the output under '$removed'.") 128 | } 129 | 130 | classProb = getClassProb(classLabelsNum) 131 | names(classProb) = classLabelsLab 132 | 133 | geneProb = getGeneProb(xbin$mat) 134 | 135 | condGeneCluster = getGeneConditionalCluster_stats(xbin$mat, classProb, classLabels, cores = cores) 136 | clusterPostGene = getClusterPostGene(condGeneCluster, geneProb, classProb) 137 | specScore = getSpecScore(clusterPostGene, condGeneCluster) 138 | 139 | tf_idf = NULL 140 | if (TF_IDF) { 141 | tf_idf = getClusterTFIDF(condGeneCluster) 142 | } 143 | 144 | if (returnInput) { 145 | return(list(binary = xbin$mat, cutoff = xbin$cutoff, removed = rem, geneProb = geneProb, condGeneProb = condGeneCluster, postClustProb = clusterPostGene, specScore = specScore, classProb = classProb, inputMat = x, inputClass = classLabels, tf_idf = tf_idf)) 146 | } else { 147 | return(list(binary = xbin$mat, cutoff = xbin$cutoff, removed = rem, geneProb = geneProb, condGeneProb = condGeneCluster, postClustProb = clusterPostGene, specScore = specScore, classProb = classProb, tf_idf = tf_idf)) 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------