├── LICENSE ├── R ├── globals.R ├── plot_eD.R ├── calculate_perp_bisector.R ├── fisher.R ├── emptydrops_with_barhop.R ├── aggr_p_values.R ├── find_tip.R ├── accept_k_means.R ├── cellranger_k_means_v2.R ├── emptydrops_multiome.R └── fit_3_normals.R ├── method_cartoon.png ├── NAMESPACE ├── eDv3.Rproj ├── tests ├── testthat.R └── testthat │ ├── test-calculate_perp_bisector.R │ ├── test-aggr_p_values.R │ ├── test-fischer.R │ ├── test-cellranger_k_means_v2.R │ ├── test-accept_k_means.R │ ├── test-emptydrops_with_barhop.R │ ├── test-fit_3_normals.R │ ├── test-emptydrops_multiome.R │ └── test-find_tip.R ├── man ├── log_transform_v2.Rd ├── log_transform.Rd ├── simpler_ordmag.Rd ├── fisher_v2.Rd ├── dist_point_to_line.Rd ├── mean_aggr.Rd ├── perp_bisector.Rd ├── cell_calling_plot.Rd ├── call_cells.Rd ├── balanced_aggr.Rd ├── calc_lower_line.Rd ├── transfer_labels_to_dedupl_v3.Rd ├── calc_intercept_of_parallel_line.Rd ├── fit_3_normals.Rd ├── find_tip.Rd ├── fit_3_normals_atac.Rd ├── equil_of_normals.Rd ├── accept_k_means.Rd ├── plot_counts.Rd ├── calc_ambiguous_above.Rd ├── emptydrops_with_barhop.Rd ├── aggr_p_values.Rd └── emptydrops_multiome.Rd ├── DESCRIPTION ├── README.md └── LICENSE.md /LICENSE: -------------------------------------------------------------------------------- 1 | YEAR: 2022 2 | COPYRIGHT HOLDER: EmptyDropsMultiome authors 3 | -------------------------------------------------------------------------------- /R/globals.R: -------------------------------------------------------------------------------- 1 | utils::globalVariables(c("nCount_RNA", "nCount_ATAC")) 2 | -------------------------------------------------------------------------------- /method_cartoon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarioniLab/EmptyDropsMultiome/HEAD/method_cartoon.png -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | export(accept_k_means) 4 | export(call_cells) 5 | export(cell_calling_plot) 6 | export(emptydrops_multiome) 7 | export(emptydrops_with_barhop) 8 | export(fit_3_normals) 9 | export(fit_3_normals_atac) 10 | export(plot_counts) 11 | -------------------------------------------------------------------------------- /eDv3.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: Sweave 13 | LaTeX: pdfLaTeX 14 | 15 | BuildType: Package 16 | PackageUseDevtools: Yes 17 | PackageInstallArgs: --no-multiarch --with-keep.source 18 | -------------------------------------------------------------------------------- /tests/testthat.R: -------------------------------------------------------------------------------- 1 | # This file is part of the standard setup for testthat. 2 | # It is recommended that you do not modify it. 3 | # 4 | # Where should you do additional test configuration? 5 | # Learn more about the roles of various files in: 6 | # * https://r-pkgs.org/tests.html 7 | # * https://testthat.r-lib.org/reference/test_package.html#special-files 8 | 9 | library(testthat) 10 | library(EmptyDropsMultiome) 11 | 12 | test_check("EmptyDropsMultiome") 13 | -------------------------------------------------------------------------------- /man/log_transform_v2.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/calculate_perp_bisector.R 3 | \name{log_transform_v2} 4 | \alias{log_transform_v2} 5 | \title{log-transform the data} 6 | \usage{ 7 | log_transform_v2(data) 8 | } 9 | \arguments{ 10 | \item{data}{Dataframe with column x and column y} 11 | } 12 | \value{ 13 | Dataframe with with log-transformed column values 14 | } 15 | \description{ 16 | log-transform the data 17 | } 18 | -------------------------------------------------------------------------------- /man/log_transform.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/cellranger_k_means_v2.R 3 | \name{log_transform} 4 | \alias{log_transform} 5 | \title{Log-transform the data.} 6 | \usage{ 7 | log_transform(data) 8 | } 9 | \arguments{ 10 | \item{data}{Dataframe with column atac_count and column rna_count} 11 | } 12 | \value{ 13 | Dataframe with with log-transformed column values 14 | } 15 | \description{ 16 | Log-transform the data. 17 | } 18 | -------------------------------------------------------------------------------- /man/simpler_ordmag.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/cellranger_k_means_v2.R 3 | \name{simpler_ordmag} 4 | \alias{simpler_ordmag} 5 | \title{Finds a nice initialization for the K-means clustering} 6 | \usage{ 7 | simpler_ordmag(x) 8 | } 9 | \arguments{ 10 | \item{x}{Vector of real values.} 11 | } 12 | \value{ 13 | Value roughly equal to 1/10 of the 99\% percentile of values. 14 | } 15 | \description{ 16 | Finds a nice initialization for the K-means clustering 17 | } 18 | -------------------------------------------------------------------------------- /man/fisher_v2.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fisher.R 3 | \name{fisher_v2} 4 | \alias{fisher_v2} 5 | \title{Use chi-squared function to aggregate p-values derived from different hypothesis tests} 6 | \usage{ 7 | fisher_v2(pvalues) 8 | } 9 | \arguments{ 10 | \item{pvalues}{Vector of real numbers.} 11 | } 12 | \value{ 13 | Real number of the aggregated p-value. 14 | } 15 | \description{ 16 | Use chi-squared function to aggregate p-values derived from different hypothesis tests 17 | } 18 | -------------------------------------------------------------------------------- /man/dist_point_to_line.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/find_tip.R 3 | \name{dist_point_to_line} 4 | \alias{dist_point_to_line} 5 | \title{Calculates the distance between a point and a line.} 6 | \usage{ 7 | dist_point_to_line(equation, point) 8 | } 9 | \arguments{ 10 | \item{equation}{A vector c(intercept, slope) that defines a line in 2d Euclidean space.} 11 | 12 | \item{point}{A 2d vector of coordinates.} 13 | } 14 | \value{ 15 | A single real number. 16 | } 17 | \description{ 18 | Calculates the distance between a point and a line. 19 | } 20 | -------------------------------------------------------------------------------- /tests/testthat/test-calculate_perp_bisector.R: -------------------------------------------------------------------------------- 1 | 2 | point1 = c(0,1) 3 | point2 = c(0,2) 4 | 5 | line = perp_bisector(point1, point2) 6 | 7 | test_that("horizontal lines are correct", { 8 | expect_equal(line, c(1.5, 0)) 9 | }) 10 | 11 | point1 = c(1,0) 12 | point2 = c(2,0) 13 | 14 | #line = perp_bisector(point1, point2) 15 | 16 | # test_that("vertical lines lead to warning about default slope", { 17 | # expect_warning(perp_bisector(point1, point2)) 18 | # }) 19 | 20 | test_that("vertical lines are correct", { 21 | expect_equal(perp_bisector(point1, point2), c(1.5, 10^10)) 22 | }) 23 | 24 | 25 | -------------------------------------------------------------------------------- /man/mean_aggr.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fisher.R 3 | \name{mean_aggr} 4 | \alias{mean_aggr} 5 | \title{Mean aggregation of real values.} 6 | \usage{ 7 | mean_aggr(pvalues, r) 8 | } 9 | \arguments{ 10 | \item{pvalues}{Vector of real numbers.} 11 | 12 | \item{r}{Real number for the kind of mean which will be used to aggregate the p-values. 13 | For instance, r=1 is the arithmetic mean, r=-1 is the harmonic mean etc.} 14 | } 15 | \value{ 16 | Real number of the aggregated p-value. 17 | } 18 | \description{ 19 | Mean aggregation of real values. 20 | } 21 | -------------------------------------------------------------------------------- /man/perp_bisector.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/calculate_perp_bisector.R 3 | \name{perp_bisector} 4 | \alias{perp_bisector} 5 | \title{Calculate the perpendicular bisector line to the line segment defined by two points in 2d Euclidean space.} 6 | \usage{ 7 | perp_bisector(center1, center2) 8 | } 9 | \arguments{ 10 | \item{center1}{A point in 2d Euclidean space.} 11 | 12 | \item{center2}{A point in 2d Euclidean space.} 13 | } 14 | \value{ 15 | Two dimensional vector c(intercept, slope) 16 | } 17 | \description{ 18 | Calculate the perpendicular bisector line to the line segment defined by two points in 2d Euclidean space. 19 | } 20 | -------------------------------------------------------------------------------- /man/cell_calling_plot.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plot_eD.R 3 | \name{cell_calling_plot} 4 | \alias{cell_calling_plot} 5 | \title{Creates the cell calling plot.} 6 | \usage{ 7 | cell_calling_plot(x_axis, y_axis, colors, title) 8 | } 9 | \arguments{ 10 | \item{x_axis}{Vector with values for the x-coordinate.} 11 | 12 | \item{y_axis}{Vector with values for the y-coordinate.} 13 | 14 | \item{colors}{Vector with values for the color to be used in the scatter plot.} 15 | 16 | \item{title}{character to be used as title for the plot.} 17 | } 18 | \value{ 19 | invisible(NULL) 20 | } 21 | \description{ 22 | Creates the cell calling plot. 23 | } 24 | -------------------------------------------------------------------------------- /man/call_cells.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/cellranger_k_means_v2.R 3 | \name{call_cells} 4 | \alias{call_cells} 5 | \title{Call cells using k-means and store this information in is_cell.} 6 | \usage{ 7 | call_cells(data, verbose = TRUE) 8 | } 9 | \arguments{ 10 | \item{data}{Dataframe with columns 'atac_count' (int), 'rna_count' (int), 'excluded' (bool), 'is_cell'.} 11 | 12 | \item{verbose}{if TRUE various intermediate steps and plots are printed.} 13 | } 14 | \value{ 15 | Dataframe with columns 'atac_count' (int), 'rna_count' (int), 'excluded' (bool), 'is_cell'. 16 | } 17 | \description{ 18 | Call cells using k-means and store this information in is_cell. 19 | } 20 | -------------------------------------------------------------------------------- /tests/testthat/test-aggr_p_values.R: -------------------------------------------------------------------------------- 1 | 2 | e.out1 <- data.frame( "PValue"=c(1,1,1,0,0,0,0.5,0.5) ) 3 | rownames(e.out1) <- as.character(c(seq_along(e.out1$PValue)) ) 4 | 5 | e.out2 <- data.frame( "PValue"=c(1,1,0,0,0,1,0.5, 0.5,0.5,0.5) ) 6 | rownames(e.out2) <- c(rownames(e.out1)[seq(1,7)], as.character(c(9,10,11)) ) 7 | 8 | e_multi.out <- aggr_p_values( e.out1, e.out2) 9 | 10 | test_that("merging doesn't lose droplets", { 11 | expect_equal( sort(union(rownames(e.out1), rownames(e.out2) )) , rownames(e_multi.out) ) 12 | }) 13 | 14 | 15 | # test_that("fischer+mean works", { 16 | # expect_equal(e_multi.out[as.character(c( seq(1,6), seq(8,11) )),]$PValue_multi , c(1,1,0,0,0,0, NA,NA,NA,NA) ) 17 | # }) 18 | -------------------------------------------------------------------------------- /tests/testthat/test-fischer.R: -------------------------------------------------------------------------------- 1 | 2 | pvalues = c(1,1,1) 3 | 4 | test_that("aggregating 1's gives 1", { 5 | expect_equal(fisher_v2(pvalues) ,1) 6 | }) 7 | 8 | pvalues = c(0.3457261,0.187543,10e-319) 9 | 10 | test_that("aggregating anything with 0 gives 0", { 11 | expect_equal(fisher_v2(pvalues), 0) 12 | }) 13 | 14 | 15 | pvalues = c(0.3457261,0.187543, NA) 16 | 17 | test_that("aggregating anything with NA gives NA", { 18 | expect_equal(fisher_v2(pvalues), NA) 19 | }) 20 | 21 | 22 | # 23 | # pvalues = c(1,1,1) 24 | # 25 | # test_that("aggregating 1's gives 1", { 26 | # expect_equal(ave_aggr(pvalues,2) ,1) 27 | # expect_equal(ave_aggr(pvalues,-1) ,1) 28 | # expect_equal(ave_aggr(pvalues,1) ,1) 29 | # }) 30 | # 31 | 32 | 33 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: EmptyDropsMultiome 2 | Title: Sensitive and specific selection of nuclei-containing droplets in multiome datasets 3 | Version: 0.0.0.9000 4 | Authors@R: 5 | person("Stathis", "Megas", , "stathismegas@gmail.com", role = c("aut", "cre"), 6 | comment = c(ORCID = "0000-0002-2038-3040")) 7 | Description: Sensitive and specific selection of nuclei-containing droplets in multiome datasets without hard cut-off thresholds. 8 | License: GPL (>= 3) + file LICENSE 9 | Encoding: UTF-8 10 | Roxygen: list(markdown = TRUE) 11 | RoxygenNote: 7.2.3 12 | Suggests: 13 | testthat (>= 3.0.0) 14 | Config/testthat/edition: 3 15 | Imports: 16 | DropletUtils, 17 | ggplot2, 18 | Matrix, 19 | mixtools, 20 | S4Vectors, 21 | stats 22 | -------------------------------------------------------------------------------- /man/balanced_aggr.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fisher.R 3 | \name{balanced_aggr} 4 | \alias{balanced_aggr} 5 | \title{Aggregate p-values using the average of the Fisher aggregation value and the mean aggregation method.} 6 | \usage{ 7 | balanced_aggr(pvalues, r) 8 | } 9 | \arguments{ 10 | \item{pvalues}{Vector of real numbers in the range from 0 to 1.} 11 | 12 | \item{r}{r Real number for the kind of mean which will be used to aggregate the p-values. 13 | For instance, r=1 is the arithmetic mean, r=-1 is the harmonic mean etc.} 14 | } 15 | \value{ 16 | Real number of the aggregated p-value. 17 | } 18 | \description{ 19 | Aggregate p-values using the average of the Fisher aggregation value and the mean aggregation method. 20 | } 21 | -------------------------------------------------------------------------------- /man/calc_lower_line.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/find_tip.R 3 | \name{calc_lower_line} 4 | \alias{calc_lower_line} 5 | \title{Calculate a line that is parallel to a given line and passes through the point (x, y).} 6 | \usage{ 7 | calc_lower_line(x, y, equation) 8 | } 9 | \arguments{ 10 | \item{x}{A real number for the x coordinate of the point.} 11 | 12 | \item{y}{A real number for the y coordinate of the point.} 13 | 14 | \item{equation}{A 2d vector c(intercept, slope) defining a line in 2d Euclidean space.} 15 | } 16 | \value{ 17 | A 2d vector c(intercept, slope) defining a line in 2d Euclidean space. 18 | } 19 | \description{ 20 | Calculate a line that is parallel to a given line and passes through the point (x, y). 21 | } 22 | -------------------------------------------------------------------------------- /man/transfer_labels_to_dedupl_v3.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/cellranger_k_means_v2.R 3 | \name{transfer_labels_to_dedupl_v3} 4 | \alias{transfer_labels_to_dedupl_v3} 5 | \title{Assigns the value is_cell of the unique elements to the value is_cell of their corresponding duplicates.} 6 | \usage{ 7 | transfer_labels_to_dedupl_v3(data) 8 | } 9 | \arguments{ 10 | \item{data}{Dataframe with columns 'atac_count' (int), 'rna_count' (int), 'excluded' (bool), 'is_cell' (bool), 'dup' (bool). 11 | data is sorted wrt 'atac_count' (int), 'rna_count' (int), 'dup' (bool).} 12 | } 13 | \value{ 14 | Dataframe with altered is_cell column. 15 | } 16 | \description{ 17 | Assigns the value is_cell of the unique elements to the value is_cell of their corresponding duplicates. 18 | } 19 | -------------------------------------------------------------------------------- /man/calc_intercept_of_parallel_line.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/find_tip.R 3 | \name{calc_intercept_of_parallel_line} 4 | \alias{calc_intercept_of_parallel_line} 5 | \title{Calculate the equation of a line that is parallel to a given line and a given distance from it.} 6 | \usage{ 7 | calc_intercept_of_parallel_line(equation, dist) 8 | } 9 | \arguments{ 10 | \item{equation}{A 2d vector c(intercept, slope) defining a line in 2d Euclidean space.} 11 | 12 | \item{dist}{A real number specifying the distance between the given line and the line to be calculated.} 13 | } 14 | \value{ 15 | A 2d vector c(intercept, slope) defining a line in 2d Euclidean space 16 | } 17 | \description{ 18 | Calculate the equation of a line that is parallel to a given line and a given distance from it. 19 | } 20 | -------------------------------------------------------------------------------- /man/fit_3_normals.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fit_3_normals.R 3 | \name{fit_3_normals} 4 | \alias{fit_3_normals} 5 | \title{Fits a mixture of three normal distributions to histogram of RNA counts, to infer the parameters lower and barhop_end 6 | which are used in emptydrops.} 7 | \usage{ 8 | fit_3_normals(exp_counts_per_cell, verbose = TRUE) 9 | } 10 | \arguments{ 11 | \item{exp_counts_per_cell}{a vector with RNA library size per barcode.} 12 | 13 | \item{verbose}{if TRUE various intermediate steps and plots are printed.} 14 | } 15 | \value{ 16 | A 2d vector with the values lower and barhop_end for RNA. 17 | } 18 | \description{ 19 | Fits a mixture of three normal distributions to histogram of RNA counts, to infer the parameters lower and barhop_end 20 | which are used in emptydrops. 21 | } 22 | -------------------------------------------------------------------------------- /man/find_tip.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/find_tip.R 3 | \name{find_tip} 4 | \alias{find_tip} 5 | \title{Finds the droplets that are in 1) the top 1\% of RNA counts and in the top 0.1\% of atac counts, and then 6 | calculates their mean RNA counts and mean ATAC counts.} 7 | \usage{ 8 | find_tip(data, equation) 9 | } 10 | \arguments{ 11 | \item{data}{Dataframe with data$rna being the number of RNA counts, and data$atac being the number of ATAC counts.} 12 | 13 | \item{equation}{A vector c(intercept, slope) that defines a line in 2d Euclidean space.} 14 | } 15 | \value{ 16 | A real vector with the two mean values. 17 | } 18 | \description{ 19 | Finds the droplets that are in 1) the top 1\% of RNA counts and in the top 0.1\% of atac counts, and then 20 | calculates their mean RNA counts and mean ATAC counts. 21 | } 22 | -------------------------------------------------------------------------------- /man/fit_3_normals_atac.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fit_3_normals.R 3 | \name{fit_3_normals_atac} 4 | \alias{fit_3_normals_atac} 5 | \title{Fits a mixture of three normal distributions to histogram of ATAC counts, to infer the parameters lower and barhop_end 6 | which are used in emptydrops.} 7 | \usage{ 8 | fit_3_normals_atac(exp_counts_per_cell, verbose = TRUE) 9 | } 10 | \arguments{ 11 | \item{exp_counts_per_cell}{a vector with the ATAC library size per barcode.} 12 | 13 | \item{verbose}{if TRUE various intermediate steps and plots are printed.} 14 | } 15 | \value{ 16 | A 2d vector with the values lower and barhop_end for ATAC. 17 | } 18 | \description{ 19 | Fits a mixture of three normal distributions to histogram of ATAC counts, to infer the parameters lower and barhop_end 20 | which are used in emptydrops. 21 | } 22 | -------------------------------------------------------------------------------- /R/plot_eD.R: -------------------------------------------------------------------------------- 1 | #' Creates the cell calling plot. 2 | #' 3 | #' @param x_axis Vector with values for the x-coordinate. 4 | #' @param y_axis Vector with values for the y-coordinate. 5 | #' @param colors Vector with values for the color to be used in the scatter plot. 6 | #' @param title character to be used as title for the plot. 7 | #' 8 | #' @return invisible(NULL) 9 | #' @export 10 | #' 11 | cell_calling_plot <- function(x_axis, y_axis, colors, title){ 12 | 13 | 14 | plot(x_axis, y_axis, 15 | # xlim=c(0,1510) , ylim=c(0,8), 16 | pch=".", 17 | # cex=2, 18 | col=colors, 19 | xlab="log10(atac_count)", ylab="log10(rna_count)", 20 | main=paste0(title) 21 | )+ggplot2::theme(axis.title.x=ggplot2::element_text(size=14,face="bold"), 22 | axis.title.y=ggplot2::element_text(size=14,face="bold")) 23 | 24 | 25 | return(invisible(NULL)) 26 | 27 | } 28 | -------------------------------------------------------------------------------- /tests/testthat/test-cellranger_k_means_v2.R: -------------------------------------------------------------------------------- 1 | 2 | data <- data.frame( "dup" = 1 - c(T,T,F,F,T,F,F,F,T,F,T,T,F), 3 | "is_cell" = c(1,1,0,0,1,0,0,0,0,0,0,1,0) ) 4 | corrected_is_cell = c(rep(1,8), c(0,0,0), c(1,1)) 5 | 6 | reconstructed_is_cell = transfer_labels_to_dedupl_v3(data)$is_cell 7 | 8 | test_that("label transfer works", { 9 | expect_equal(corrected_is_cell, reconstructed_is_cell) 10 | }) 11 | 12 | n=1000 13 | rna_count = c( runif(n, 0, 500), runif(n, 700, 5000) ) 14 | atac_count = c( runif(n, 0, 200), runif(n, 400, 6000) ) 15 | df <- data.frame( "rna_count"= rna_count, "atac_count"= atac_count, 16 | "excluded"= rep(F,2*n), 17 | "is_cell"= rep(0,2*n) ) 18 | df_out <- call_cells(df) 19 | 20 | test_that("we have 1000 cells", { 21 | expect_equal(sum(df_out[[1]]$is_cell), n) 22 | }) 23 | 24 | test_that("we have 1000 empty droplets", { 25 | expect_equal(sum(! df_out[[1]]$is_cell), n) 26 | }) 27 | 28 | -------------------------------------------------------------------------------- /man/equil_of_normals.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fit_3_normals.R 3 | \name{equil_of_normals} 4 | \alias{equil_of_normals} 5 | \title{Find the point of equal probability between two Gaussian components of a Gaussian Mixture Model} 6 | \usage{ 7 | equil_of_normals(mu1, sd1, lam1, mu2, sd2, lam2) 8 | } 9 | \arguments{ 10 | \item{mu1}{the mean of the first Gaussian distribution} 11 | 12 | \item{sd1}{the standard deviation of the first Gaussian distribution} 13 | 14 | \item{lam1}{the mixing ratio of the first Gaussian distribution} 15 | 16 | \item{mu2}{the mean of the second Gaussian distribution} 17 | 18 | \item{sd2}{the standard deviation of the second Gaussian distribution} 19 | 20 | \item{lam2}{the mixing ratio of the second Gaussian distribution} 21 | } 22 | \value{ 23 | Real number for the point of intersection of the Gaussians 24 | } 25 | \description{ 26 | Find the point of equal probability between two Gaussian components of a Gaussian Mixture Model 27 | } 28 | -------------------------------------------------------------------------------- /man/accept_k_means.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/accept_k_means.R 3 | \name{accept_k_means} 4 | \alias{accept_k_means} 5 | \title{After using emptydrops, set FDR_multi<-1 for cells above the ambiguous area, and set FDR_multi<-0 in cells below the lower line.} 6 | \usage{ 7 | accept_k_means(e_multi.out, lower_atac, lower_rna) 8 | } 9 | \arguments{ 10 | \item{e_multi.out}{Dataframe with columns for Total_RNA, Total_chromatin, rownames, barhop_amb_tent_chromatin, barhop_amb_tent_rna, FDR_multi} 11 | 12 | \item{lower_atac}{A single number to act as the value of the lower parameter in ATAC} 13 | 14 | \item{lower_rna}{A single number to act as the value of the lower parameter in RNA} 15 | } 16 | \value{ 17 | Dataframe with columns for Total_RNA, Total_chromatin, rownames, barhop_amb_tent_chromatin, 18 | barhop_amb_tent_rna, FDR_multi, FDR, above_ambiguous, k_means 19 | } 20 | \description{ 21 | After using emptydrops, set FDR_multi<-1 for cells above the ambiguous area, and set FDR_multi<-0 in cells below the lower line. 22 | } 23 | -------------------------------------------------------------------------------- /man/plot_counts.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fit_3_normals.R 3 | \name{plot_counts} 4 | \alias{plot_counts} 5 | \title{Plot histogram of counts for lower and barhop_end inference} 6 | \usage{ 7 | plot_counts( 8 | nCount, 9 | mu1, 10 | sigma1, 11 | lam1, 12 | mu2, 13 | sigma2, 14 | lam2, 15 | max = 50000, 16 | vline1, 17 | vline2, 18 | label 19 | ) 20 | } 21 | \arguments{ 22 | \item{nCount}{vector with the RNA or ATAC counts} 23 | 24 | \item{mu1}{mu of first Gaussian} 25 | 26 | \item{sigma1}{sigma of first Gaussian} 27 | 28 | \item{lam1}{lambda of first Gaussian} 29 | 30 | \item{mu2}{mu of first Gaussian} 31 | 32 | \item{sigma2}{sigma of first Gaussian} 33 | 34 | \item{lam2}{lambda of first Gaussian} 35 | 36 | \item{max}{upper limit of RNA range} 37 | 38 | \item{vline1}{x value of first vertical line} 39 | 40 | \item{vline2}{x value of second vertical line} 41 | 42 | \item{label}{label for x axis} 43 | } 44 | \value{ 45 | None 46 | } 47 | \description{ 48 | Plot histogram of counts for lower and barhop_end inference 49 | } 50 | -------------------------------------------------------------------------------- /man/calc_ambiguous_above.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/find_tip.R 3 | \name{calc_ambiguous_above} 4 | \alias{calc_ambiguous_above} 5 | \title{Calculate a line that is parallel to the k-means line and a distance from it that is equal to 66\% of the distance 6 | between the droplets with the biggest library size and the k-means line. The area bound by the k-means line and this 7 | line is referred to as ambiguous area and in it droplets are rejected by thresholding FDR_multi. 8 | Above this ambiguous area, droplets are assumed to contain nuclei/cells and their FDR_multi is set to 0 by default.} 9 | \usage{ 10 | calc_ambiguous_above(data, equation) 11 | } 12 | \arguments{ 13 | \item{data}{Dataframe of droplets with columns Total_RNA and Total_chromatin.} 14 | 15 | \item{equation}{2d vector c(intercept, slope) defining the k-means line.} 16 | } 17 | \value{ 18 | 2d vector c(intercept, slope) defining the k-means line. 19 | } 20 | \description{ 21 | Calculate a line that is parallel to the k-means line and a distance from it that is equal to 66\% of the distance 22 | between the droplets with the biggest library size and the k-means line. The area bound by the k-means line and this 23 | line is referred to as ambiguous area and in it droplets are rejected by thresholding FDR_multi. 24 | Above this ambiguous area, droplets are assumed to contain nuclei/cells and their FDR_multi is set to 0 by default. 25 | } 26 | -------------------------------------------------------------------------------- /R/calculate_perp_bisector.R: -------------------------------------------------------------------------------- 1 | #' log-transform the data 2 | #' 3 | #' @param data Dataframe with column x and column y 4 | #' 5 | #' @return Dataframe with with log-transformed column values 6 | #' 7 | #' 8 | log_transform_v2 <- function(data){ 9 | # data: dataframe with column "atac_count" and "rna_count" 10 | # output: dataframe with log10 transformed columns 11 | data["x"] <- log10(data["x"]+0.1) 12 | data["y"] <- log10(data["y"]+0.1) 13 | return(data) 14 | } 15 | 16 | #' Calculate the perpendicular bisector line to the line segment defined by two points in 2d Euclidean space. 17 | #' 18 | #' @param center1 A point in 2d Euclidean space. 19 | #' @param center2 A point in 2d Euclidean space. 20 | #' 21 | #' @return Two dimensional vector c(intercept, slope) 22 | #' 23 | perp_bisector <- function(center1, center2){ 24 | # center1: numeric vector with position coordinates 25 | # center2: numeric vector with position coordinates 26 | # output: calculate slope (b) and intercept (a) of perpendicular bisector: y = b * x +a 27 | 28 | dy = center2[2]-center1[2] 29 | y_mean = (center2[2]+center1[2])/2 30 | 31 | dx = center2[1]-center1[1] 32 | x_mean = (center2[1]+center1[1])/2 33 | 34 | a = y_mean+ x_mean *(dx / dy) 35 | b = - dx / dy 36 | 37 | if (b==Inf || b==-Inf){ 38 | #warning('slope became Infinite, default to slope=10^10') 39 | b=10^10 40 | a=x_mean 41 | } 42 | 43 | return( c(a,b) ) 44 | 45 | 46 | } 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /tests/testthat/test-accept_k_means.R: -------------------------------------------------------------------------------- 1 | 2 | n=1000 3 | m=200 4 | lower = 100 5 | barhop_end = 10 6 | rna_count = c( runif(n, 0, 500), runif(n, 700, 5000), runif(m, 0, 500), runif(m, 700, 5000) ) 7 | atac_count = c( runif(n, 0, 200), runif(n, 400, 6000), runif(m, 700, 5000), runif(m, 0, 500) ) 8 | df <- S4Vectors::DataFrame( "Total_RNA"= rna_count, "Total_chromatin"= atac_count, 9 | "excluded"= rep(F,2*(n+m)), 10 | "is_cell"= rep(0,2*(n+m)), 11 | "FDR_multi"=runif(2*(n+m), 0, 0.002), 12 | "barhop_amb_tent_RNA" = as.numeric(rna_countlower) *3, 13 | "barhop_amb_tent_chromatin" = as.numeric(atac_countlower) *3 14 | ) 15 | 16 | rownames(df)<- as.character(seq_along(rna_count)) 17 | #df_out <- call_cells(df) 18 | df_out <- accept_k_means(df, lower, lower) 19 | 20 | 21 | 22 | test_that("all droplets above ambiguous have been labelled as cells", { 23 | expect_equal(sum(df_out$FDR_multi[df_out$above_ambiguous==1]<0.001 ) , sum(df_out$above_ambiguous)) 24 | }) 25 | 26 | test_that("all droplets below barhop_end have been labelled as non cells", { 27 | expect_equal(sum(df_out$FDR_multi[df_out$Total_RNA=barhop_end) ) 22 | expect_equal( sum(out@listData[["barhop_amb_tent"]]==2) , sum( Matrix::colSums(count_matrix)lower) ) 24 | }) 25 | 26 | 27 | # 28 | # # Identify likely cell-containing droplets. 29 | # out <- emptyDrops(my.counts) 30 | # out 31 | # 32 | # is.cell <- out$FDR <= 0.001 33 | # sum(is.cell, na.rm=TRUE) 34 | # 35 | # # Subsetting the matrix to the cell-containing droplets. 36 | # # (using 'which()' to handle NAs smoothly). 37 | # cell.counts <- my.counts[,which(is.cell),drop=FALSE] 38 | # dim(cell.counts) 39 | # 40 | # # Check if p-values are lower-bounded by 'niters' 41 | # # (increase 'niters' if any Limited==TRUE and Sig==FALSE) 42 | # table(Sig=is.cell, Limited=out$Limited) 43 | # 44 | # 45 | # test_that("multiplication works", { 46 | # expect_equal(2 * 2, 4) 47 | # }) 48 | -------------------------------------------------------------------------------- /tests/testthat/test-fit_3_normals.R: -------------------------------------------------------------------------------- 1 | # simulate scRNA reads 2 | hops = 500 3 | soups = 100 4 | cells = 100 5 | mean_hops = 7 6 | mean_soups = 300 7 | mean_cells = 1300 8 | atac_downsampling = 0.8 9 | nCount = round(c( rnorm(hops, mean=mean_hops, sd=1), rnorm(soups, mean=mean_soups, sd=50) , rnorm(cells, mean=mean_cells, sd=150) )) 10 | out = fit_3_normals(nCount) 11 | 12 | # simulate scATAC reads 13 | hops = 500 14 | soups = 100 15 | cells = 100 16 | mean_hops = 7 17 | mean_soups = 300 18 | mean_cells = 20000 19 | nCount_atac = round(c( rnorm(hops, mean=mean_hops, sd=1), rnorm(soups, mean=mean_soups, sd=50) , rnorm(cells, mean=mean_cells, sd=150) )) 20 | out_atac = fit_3_normals_atac(nCount_atac) 21 | 22 | test_that("RNA: lower is bigger than barhop_end", { 23 | expect_equal(out[1]>out[2], TRUE) 24 | }) 25 | test_that("RNA: barhop_end is between the mean of barhops and the mean of ambient", { 26 | expect_equal(mean_hopsout[2] , TRUE) 27 | }) 28 | test_that("RNA: lower is larger than the mean of ambient", { 29 | expect_equal(mean_hopsout[2] , TRUE) 30 | }) 31 | 32 | test_that("lower atac is bigger than barhop_end", { 33 | expect_equal(out_atac[1]>out_atac[2], TRUE) 34 | }) 35 | 36 | test_that("ATAC: barhop_end is between the mean of barhops and the mean of ambient", { 37 | expect_equal(mean_hops*atac_downsamplingout_atac[2] , TRUE) 38 | }) 39 | 40 | 41 | 42 | # Cause bad convergence in ATAC and RNA 43 | hops = 1 44 | soups = 1 45 | cells = 1 46 | max_hops = 10 47 | max_soups = 50 48 | mean_cells = 20000 49 | nCount_atac = round(c( runif(hops, min=0, max=max_hops), runif(soups, min=max_hops, max=max_soups) , rnorm(cells, mean=mean_cells, sd=150) )) 50 | out_atac = fit_3_normals_atac(nCount_atac) 51 | nCount = round(c( runif(hops, min=0, max=max_hops), runif(soups, min=max_hops, max=max_soups) , rnorm(cells, mean=mean_cells, sd=150) )) 52 | out = fit_3_normals(nCount) 53 | test_that("in case of bad convergence test default parameters are activated", { 54 | expect_equal( out_atac[1], 160 ) 55 | expect_equal( out_atac[2], 4.625116 ) 56 | expect_equal( out[1], 290.00000 ) 57 | expect_equal( out[2], 29.567552 ) 58 | }) 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /man/aggr_p_values.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/aggr_p_values.R 3 | \name{aggr_p_values} 4 | \alias{aggr_p_values} 5 | \title{Aggregates the p-values from the two modalities (RNA and epigenomics) and then corrects them using the Benjamini-Hochberg method} 6 | \usage{ 7 | aggr_p_values(e.out1, e.out2) 8 | } 9 | \arguments{ 10 | \item{e.out1}{a DataFrame (in the format of the emptyDrops outputs) with the following components: 11 | Total: 12 | Integer, the total count for each barcode. 13 | LogProb: 14 | Numeric, the log-probability of observing the barcode's count vector under the null model. 15 | PValue: 16 | Numeric, the Monte Carlo p-value against the null model. 17 | Limited: 18 | Logical, indicating whether a lower p-value could be obtained by increasing niters. 19 | FDR: 20 | Numeric, the p-values corrected using the Benjamini-Hochberg method} 21 | 22 | \item{e.out2}{a DataFrame (in the format of the emptyDrops outputs) like e.out1} 23 | } 24 | \value{ 25 | a DataFrame (in the format of the emptyDrops outputs) with the following components: 26 | Total_RNA: 27 | Integer, the total count for each barcode. 28 | LogProb_RNA: 29 | Numeric, the log-probability of observing the barcode's count vector under the null model. 30 | PValue_RNA: 31 | Numeric, the Monte Carlo p-value against the null model. 32 | Limited_RNA: 33 | Logical, indicating whether a lower p-value could be obtained by increasing niters. 34 | FDR_RNA: 35 | Numeric, the p-values corrected using the Benjamini-Hochberg method 36 | Total_chromatin: 37 | Integer, the total count for each barcode. 38 | LogProb_chromatin: 39 | Numeric, the log-probability of observing the barcode's count vector under the null model. 40 | PValue_chromatin: 41 | Numeric, the Monte Carlo p-value against the null model. 42 | Limited_chromatin: 43 | Logical, indicating whether a lower p-value could be obtained by increasing niters. 44 | FDR_chromatin: 45 | Numeric, the p-values corrected using the Benjamini-Hochberg method 46 | PValue_multi: 47 | Numeric, the p-values of the droplets after aggregating PValue_chromatin and PValue_RNA for each droplet 48 | FDR_multi: 49 | Numeric, the result of the correction of PValue_multi using the Benjamini-Hochberg method 50 | } 51 | \description{ 52 | Aggregates the p-values from the two modalities (RNA and epigenomics) and then corrects them using the Benjamini-Hochberg method 53 | } 54 | -------------------------------------------------------------------------------- /tests/testthat/test-emptydrops_multiome.R: -------------------------------------------------------------------------------- 1 | # test output dataframe is not empty when user specifies lowers and barhops and ATAC matrix has fewer droplets than RNA matrix 2 | set.seed(0) 3 | count_matrix <- DropletUtils:::simCounts() 4 | colnames(count_matrix) <- paste0("C", as.character(seq(dim(count_matrix)[2]) ) ) 5 | count_matrix_rna <- as.matrix(count_matrix) 6 | set.seed(1) 7 | count_matrix1 <- DropletUtils:::simCounts() 8 | colnames(count_matrix1) <- paste0("C", as.character(seq(dim(count_matrix1)[2]) ) ) 9 | count_matrix_atac <- as.matrix(count_matrix1)[, seq(1,11090)] 10 | 11 | lower_rna = 200 12 | barhop_rna = 10 13 | lower_atac = 200 14 | barhop_atac = 7 15 | 16 | eD.out_multi <- emptydrops_multiome(count_matrix_rna, lower_rna, barhop_rna, count_matrix_atac, lower_atac, barhop_atac ) 17 | print("the number of cells detected is: ") 18 | print(sum(eD.out_multi$FDR_multi<0.001 & ! is.na(eD.out_multi$FDR_multi))) 19 | 20 | test_that("dataframe is not empty", { 21 | expect_equal(sum(eD.out_multi$Total_RNA) > 0, TRUE) 22 | expect_equal(sum(eD.out_multi$Total_chromatin) > 0, TRUE) 23 | expect_equal(sum(eD.out_multi$FDR_multi) > 0, TRUE) 24 | }) 25 | 26 | 27 | 28 | 29 | # test output dataframe is not empty when lowers and barhops are inferred automatically and ATAC matrix has fewer droplets than RNA matrix 30 | lower_rna = NULL 31 | barhop_rna = NULL 32 | lower_atac = NULL 33 | barhop_atac = NULL 34 | 35 | eD.out_multi <- emptydrops_multiome(count_matrix_rna, lower_rna, barhop_rna, count_matrix_atac, lower_atac, barhop_atac ) 36 | print("the number of cells detected is: ") 37 | print(sum(eD.out_multi$FDR_multi<0.001 & ! is.na(eD.out_multi$FDR_multi))) 38 | 39 | test_that("dataframe is not empty", { 40 | expect_equal(sum(eD.out_multi$Total_RNA) > 0, TRUE) 41 | expect_equal(sum(eD.out_multi$Total_chromatin) > 0, TRUE) 42 | expect_equal(sum(eD.out_multi$FDR_multi) > 0, TRUE) 43 | }) 44 | 45 | 46 | # when there are only 2 droplets in each of the count matrices expect error 47 | tiny_count_matrix_rna <- count_matrix_rna[,1:2] 48 | tiny_count_matrix_atac <- count_matrix_atac[,1:2] 49 | 50 | lower_rna = NULL 51 | barhop_rna = NULL 52 | lower_atac = NULL 53 | barhop_atac = NULL 54 | 55 | test_that("when there are only two droplets expect error", { 56 | expect_error( emptydrops_multiome(tiny_count_matrix_rna, lower_rna, barhop_rna, tiny_count_matrix_atac, lower_atac, barhop_atac ) ) 57 | }) 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /R/fisher.R: -------------------------------------------------------------------------------- 1 | #' Use chi-squared function to aggregate p-values derived from different hypothesis tests 2 | #' 3 | #' @param pvalues Vector of real numbers. 4 | #' 5 | #' @return Real number of the aggregated p-value. 6 | #' 7 | fisher_v2 <- function(pvalues) 8 | { 9 | # use chi-squared function to aggregate p-values derived from different hypothesis tests 10 | # input: pvalues vector of real numbers 11 | # output: real number of the aggregated p-value 12 | if (any(is.na(pvalues)) ) 13 | { 14 | return(NA) 15 | } 16 | if(length(pvalues)==0) 17 | { 18 | return(NA) 19 | } 20 | if(any(pvalues <0) || any(pvalues >1)) 21 | { 22 | stop('p-values must be in [0, 1]') 23 | } 24 | if(length(pvalues)==1) 25 | { 26 | return(pvalues) 27 | } 28 | 29 | chisq = -2 * sum(log(pvalues)) 30 | dof <- 2* length(pvalues) 31 | stats::pchisq(chisq, dof, lower.tail = FALSE) 32 | } 33 | 34 | 35 | 36 | #' Mean aggregation of real values. 37 | #' 38 | #' @param pvalues Vector of real numbers. 39 | #' @param r Real number for the kind of mean which will be used to aggregate the p-values. 40 | #' For instance, r=1 is the arithmetic mean, r=-1 is the harmonic mean etc. 41 | #' 42 | #' @return Real number of the aggregated p-value. 43 | #' 44 | mean_aggr <- function(pvalues, r){ 45 | if(r==0) 46 | { 47 | stop('r must be non zero') 48 | } 49 | if (is.na(r) ) 50 | { 51 | stop('r must have a value') 52 | } 53 | if (any(is.na(pvalues)) ) 54 | { 55 | return(NA) 56 | } 57 | 58 | aggr <- ( sum(pvalues^r)/length(pvalues) )^(1/r) 59 | return(aggr) 60 | 61 | } 62 | 63 | #' Aggregate p-values using the average of the Fisher aggregation value and the mean aggregation method. 64 | #' 65 | #' @param pvalues Vector of real numbers in the range from 0 to 1. 66 | #' @param r r Real number for the kind of mean which will be used to aggregate the p-values. 67 | #' For instance, r=1 is the arithmetic mean, r=-1 is the harmonic mean etc. 68 | #' 69 | #' @return Real number of the aggregated p-value. 70 | #' 71 | balanced_aggr <- function(pvalues, r){ 72 | if(r==0) 73 | { 74 | stop('r must be non zero') 75 | } 76 | if (is.na(r) ) 77 | { 78 | stop('r must have a value') 79 | } 80 | if (any(is.na(pvalues)) ) 81 | { 82 | return(NA) 83 | } 84 | 85 | #balanced <- ( mean_aggr(pvalues, r) + fisher_v2(pvalues) ) /2 86 | balanced <- mean_aggr(pvalues, r) 87 | return(balanced) 88 | 89 | } 90 | -------------------------------------------------------------------------------- /R/emptydrops_with_barhop.R: -------------------------------------------------------------------------------- 1 | #' Calls cells using emptydrops on a single modality. It models the soup using droplets with counts between barhop_end and lower. 2 | #' 3 | #' @param count_matrix dgCMatrix with the counts. 4 | #' @param lower single real number at or below which droplets are used to model the RNA soup. 5 | #' @param barhop_end single real number below which droplets are assumed to be full of barhops and they are excluded from modeling the soup. 6 | #' @param niters the number of iterations to use for the simulations that compare the profile of each droplet to the ambient profile. 7 | #' @param seed the value at which to set the seed. 8 | #' @return a DataFrame (in the format of the emptyDrops outputs) with the following components: 9 | #' Total*: 10 | #' Integer, the total count for each barcode. 11 | #' LogProb: 12 | #' Numeric, the log-probability of observing the barcode's count vector under the null model. 13 | #' PValue: 14 | #' Numeric, the Monte Carlo p-value against the null model. 15 | #' Limited: 16 | #' Logical, indicating whether a lower p-value could be obtained by increasing niters. 17 | #' FDR: 18 | #' Numeric, the p-values corrected using the Benjamini-Hochberg method 19 | #' @export 20 | #' 21 | emptydrops_with_barhop <- function(count_matrix, lower, barhop_end, niters=10000, seed=42){ 22 | # calls cells using a single modality 23 | # inputs: count_matrix is a features-by-cell matrix, 24 | # lower is the upper bound on the count for a droplet to be used to model the soup 25 | # barhop_end is the lower bound on the count for a droplet to be used to model the soup 26 | # outputs: dataframe like e.out 27 | 28 | 29 | # subset out the barhops from count matrix to feed it into emptydrops 30 | 31 | barhops <- Matrix::colSums(count_matrix)lower) *3 57 | 58 | return(eD.out) 59 | } 60 | 61 | -------------------------------------------------------------------------------- /R/aggr_p_values.R: -------------------------------------------------------------------------------- 1 | #' Aggregates the p-values from the two modalities (RNA and epigenomics) and then corrects them using the Benjamini-Hochberg method 2 | #' 3 | #' @param e.out1 a DataFrame (in the format of the emptyDrops outputs) with the following components: 4 | #' Total: 5 | #' Integer, the total count for each barcode. 6 | #' LogProb: 7 | #' Numeric, the log-probability of observing the barcode's count vector under the null model. 8 | #' PValue: 9 | #' Numeric, the Monte Carlo p-value against the null model. 10 | #' Limited: 11 | #' Logical, indicating whether a lower p-value could be obtained by increasing niters. 12 | #' FDR: 13 | #' Numeric, the p-values corrected using the Benjamini-Hochberg method 14 | #' 15 | #' @param e.out2 a DataFrame (in the format of the emptyDrops outputs) like e.out1 16 | #' 17 | #' 18 | #' @return 19 | #' a DataFrame (in the format of the emptyDrops outputs) with the following components: 20 | #' Total_RNA: 21 | #' Integer, the total count for each barcode. 22 | #' LogProb_RNA: 23 | #' Numeric, the log-probability of observing the barcode's count vector under the null model. 24 | #' PValue_RNA: 25 | #' Numeric, the Monte Carlo p-value against the null model. 26 | #' Limited_RNA: 27 | #' Logical, indicating whether a lower p-value could be obtained by increasing niters. 28 | #' FDR_RNA: 29 | #' Numeric, the p-values corrected using the Benjamini-Hochberg method 30 | #' Total_chromatin: 31 | #' Integer, the total count for each barcode. 32 | #' LogProb_chromatin: 33 | #' Numeric, the log-probability of observing the barcode's count vector under the null model. 34 | #' PValue_chromatin: 35 | #' Numeric, the Monte Carlo p-value against the null model. 36 | #' Limited_chromatin: 37 | #' Logical, indicating whether a lower p-value could be obtained by increasing niters. 38 | #' FDR_chromatin: 39 | #' Numeric, the p-values corrected using the Benjamini-Hochberg method 40 | #' PValue_multi: 41 | #' Numeric, the p-values of the droplets after aggregating PValue_chromatin and PValue_RNA for each droplet 42 | #' FDR_multi: 43 | #' Numeric, the result of the correction of PValue_multi using the Benjamini-Hochberg method 44 | #' 45 | #' 46 | #' 47 | aggr_p_values <- function( e.out1, e.out2){ 48 | # rename columns to before taking their disjoint union during merging 49 | colnames(e.out1) <- paste0(colnames(e.out1), "_RNA") 50 | colnames(e.out2) <- paste0(colnames(e.out2), "_chromatin") 51 | e_multi.out <- S4Vectors::merge(e.out1,e.out2, by=0, all=TRUE) # by="col1" 52 | rownames(e_multi.out) <- e_multi.out$Row.names 53 | 54 | # aggregate p-values 55 | #aggr_pval <- apply( e_multi.out[,c('PValue_chromatin','PValue_RNA')], 1, function(x) fisher_v2(x) ) 56 | aggr_pval <- apply( e_multi.out[,c('PValue_chromatin','PValue_RNA')], 1, function(x) balanced_aggr(x,r=1) ) 57 | 58 | 59 | # correct aggregated p-values by the BH method to control the fdr 60 | fdr_of_aggr <- stats::p.adjust(aggr_pval, method="BH") 61 | 62 | e_multi.out["PValue_multi"] <- unname(aggr_pval) 63 | e_multi.out["FDR_multi"] <- unname(fdr_of_aggr) 64 | 65 | return(e_multi.out) 66 | 67 | } 68 | -------------------------------------------------------------------------------- /man/emptydrops_multiome.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/emptydrops_multiome.R 3 | \name{emptydrops_multiome} 4 | \alias{emptydrops_multiome} 5 | \title{Calls cells using emptydrops in two genomic modalities.} 6 | \usage{ 7 | emptydrops_multiome( 8 | count_matrix_rna, 9 | lower_rna = NULL, 10 | barhop_rna = NULL, 11 | count_matrix_atac, 12 | lower_atac = NULL, 13 | barhop_atac = NULL, 14 | niter_rna = 10000, 15 | niter_atac = 25000, 16 | verbose = TRUE 17 | ) 18 | } 19 | \arguments{ 20 | \item{count_matrix_rna}{dgCMatrix with the counts for the rna modality.} 21 | 22 | \item{lower_rna}{single real number at or below which droplets are used to model the RNA soup.} 23 | 24 | \item{barhop_rna}{single real number below which droplets are assumed to be full of barhops and they are excluded from modeling the soup.} 25 | 26 | \item{count_matrix_atac}{dgCMatrix with the counts for the ATAC modality.} 27 | 28 | \item{lower_atac}{single real number at or below which droplets are used to model the ATAC soup.} 29 | 30 | \item{barhop_atac}{single real number below which droplets are assumed to be full of barhops and they are excluded from modeling the soup.} 31 | 32 | \item{niter_rna}{single real number for the number of iteration to be performed to statistically compare the RNA modality with the ambient profile.} 33 | 34 | \item{niter_atac}{single real number for the number of iteration to be performed to statistically compare the ATAC modality with the ambient profile.} 35 | 36 | \item{verbose}{if TRUE various intermediate steps and plots are printed.} 37 | } 38 | \value{ 39 | a DataFrame object (from the S4Vectors package) with the following components: 40 | Total_RNA: 41 | Integer, the total count for each barcode. 42 | LogProb_RNA: 43 | Numeric, the log-probability of observing the barcode's count vector under the null model. 44 | PValue_RNA: 45 | Numeric, the Monte Carlo p-value against the null model. 46 | Limited_RNA: 47 | Logical, indicating whether a lower p-value could be obtained by increasing niters. 48 | FDR_RNA: 49 | Numeric, the p-values corrected using the Benjamini-Hochberg method 50 | Total_chromatin: 51 | Integer, the total count for each barcode. 52 | LogProb_chromatin: 53 | Numeric, the log-probability of observing the barcode's count vector under the null model. 54 | PValue_chromatin: 55 | Numeric, the Monte Carlo p-value against the null model. 56 | Limited_chromatin: 57 | Logical, indicating whether a lower p-value could be obtained by increasing niters. 58 | FDR_chromatin: 59 | Numeric, the p-values corrected using the Benjamini-Hochberg method 60 | PValue_multi: 61 | Numeric, the p-values of the droplets after aggregating PValue_chromatin and PValue_RNA for each droplet 62 | FDR_multi: 63 | Numeric, the result of the correction of PValue_multi using the Benjamini-Hochberg method 64 | k_means: 65 | Logical, indicating whether droplet lies above the k-means line 66 | above_ambiguous: 67 | Logical, indicating whether droplet lies above the ambiguous area, where droplets are assumed to unambiguously contain cells. 68 | } 69 | \description{ 70 | Calls cells using emptydrops in two genomic modalities. 71 | } 72 | -------------------------------------------------------------------------------- /tests/testthat/test-find_tip.R: -------------------------------------------------------------------------------- 1 | 2 | x = 1 3 | y = 1 4 | line = c(5,-1) 5 | 6 | line_new = calc_lower_line(x,y, line) 7 | 8 | test_that("multiplication works", { 9 | expect_equal(line_new, c(2,-1)) 10 | }) 11 | 12 | line = c(0,-1) 13 | 14 | test_that("expect correct intercept", { 15 | expect_equal(calc_intercept_of_parallel_line(line, 1.41421356), c(2,-1)) 16 | }) 17 | 18 | 19 | test_that("expect correct intercept", { 20 | expect_equal(dist_point_to_line(line, c(1,1)), 1.41421356) 21 | }) 22 | 23 | set.seed(0) 24 | count_matrix <- DropletUtils:::simCounts() 25 | colnames(count_matrix) <- paste0("C", as.character(seq(dim(count_matrix)[2]) ) ) 26 | count_matrix_rna <- as.matrix(count_matrix) 27 | set.seed(1) 28 | count_matrix1 <- DropletUtils:::simCounts() 29 | colnames(count_matrix1) <- paste0("C", as.character(seq(dim(count_matrix1)[2]) ) ) 30 | count_matrix_atac <- as.matrix(count_matrix1) 31 | 32 | Total_RNA =Matrix::colSums(count_matrix_rna) 33 | Total_chromatin=Matrix::colSums(count_matrix_atac) 34 | 35 | df <- data.frame("Total_RNA"=Total_RNA, "Total_chromatin"=Total_chromatin) 36 | equation_k_means <- c(1,-1) 37 | equation_parallel <- calc_ambiguous_above(df, equation_k_means) 38 | 39 | test_that("slopes match", { 40 | expect_equal(equation_parallel[2], equation_k_means[2]) 41 | }) 42 | 43 | plot(log10(df$Total_chromatin + 0.1), log10(df$Total_RNA + 0.1), 44 | # xlim=c(0,1510) , ylim=c(0,8), 45 | pch=".", 46 | # cex=2, 47 | #col=factor(df$FDR_RNA <= 0.001 & !is.na(eD.out_multi$FDR_RNA) ), 48 | xlab="log10(atac_count)", ylab="log10(rna_count)", 49 | main=paste0() 50 | ) 51 | abline(a=equation_k_means[1],b=equation_k_means[2], col="blue") 52 | abline(a=equation_parallel[1],b=equation_parallel[2], col="blue") 53 | abline(a=3.13+3.15,b=-1, col="blue") 54 | print(dist_point_to_line(equation_parallel, c(3.13,3.15))) 55 | print(dist_point_to_line(equation_k_means, c(3.13,3.15))) 56 | 57 | # plotBarcodes <- function(ranks, totals, fitted=NULL, subset=NULL, ...) { 58 | # xlim <- range(ranks[ranks>0]) 59 | # ylim <- range(totals[totals>0]) 60 | # 61 | # # Dropping non-unique points to save space. 62 | # # Subsetting performed after range() to create comparable plots, if desired. 63 | # keep <- !duplicated(totals) 64 | # if (!is.null(subset)) { 65 | # alt.keep <- keep 66 | # keep[] <- FALSE 67 | # keep[subset] <- alt.keep[subset] 68 | # } 69 | # Rx <- ranks[keep] 70 | # Tx <- totals[keep] 71 | # 72 | # # Actually making the plot, also plotting the fitted values if requested. 73 | # plot(Rx, Tx, log="xy", xlab="Rank", ylab="Total count", xlim=xlim, ylim=ylim, ...) 74 | # if (!is.null(fitted)) { 75 | # Fx <- fitted[keep] 76 | # o <- order(Rx) 77 | # lines(Rx[o], Fx[o], col="red", lwd=2) 78 | # } 79 | # return(invisible(NULL)) 80 | # } 81 | # 82 | 83 | # logtotals <- log10(Total_RNA+0.1) + log10(Total_chromatin+0.1) 84 | # o <- order(logtotals, decreasing=TRUE) 85 | # ot <- logtotals[o] 86 | # r <- seq_along(o) 87 | # plotBarcodes(r, ot, pch=16, main="logtotals") 88 | # 89 | # 90 | # prod <- Total_RNA * Total_chromatin^(-equation_k_means[2]) 91 | # o <- order(prod, decreasing=TRUE) 92 | # ot <- prod[o] 93 | # r <- seq_along(o) 94 | # plotBarcodes(r, ot, pch=16, main="prod") 95 | 96 | 97 | # line = c(5, -1.2) 98 | # point = c(2,1) 99 | # 100 | # calc_lower_line(line, point[1], point[2]) 101 | 102 | 103 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EmptyDropsMultiome 2 | [EmptyDropsMultiome](https://genomebiology.biomedcentral.com/articles/10.1186/s13059-024-03259-x) is a framework for statistically powerful and accurate detection of nuclei-containing droplets in single-cell GEX+ATAC multiome data. The method builds on a cell calling method for droplet-based scRNA data called EmptyDrops (Lun et al, Genome Biology, 2019). It can deal with diverse samples (from highly homogeneous to highly heterogeneous) by creating the ATAC and RNA profile of the ambient noise and then testing each droplet for deviations from it. 3 | 4 | ## Installation 5 | 6 | ``` 7 | 8 | conda create -n eDm_env -c conda-forge r-base=4.3.0 -y 9 | conda activate eDm_env 10 | mamba install -c conda-forge r-devtools 11 | R 12 | > library(devtools) 13 | > if (!require("BiocManager", quietly = TRUE)) 14 | install.packages("BiocManager") 15 | > BiocManager::install("DropletUtils") 16 | > devtools::install_github("MarioniLab/emptyDrops_multiome", 17 | ref="main") 18 | 19 | # don't worry about curl package 20 | 21 | ``` 22 | 23 | ## Vignette in R: for automatic detection of lower_rna and lower_atac 24 | 25 | ``` 26 | library(Seurat) 27 | library(EmptyDropsMultiome) 28 | sce <- Read10X_h5("/path/to/folder/raw_feature_bc_matrix.h5") 29 | rna <- sce[["Gene Expression"]] 30 | atac <- sce[["Peaks"]] 31 | eD.out <- emptydrops_multiome(count_matrix_rna=rna, count_matrix_atac=atac) 32 | print("the number of cells detected is: ") 33 | print(sum(eD.out$FDR_multi<0.001 & ! is.na(eD.out$FDR_multi))) 34 | 35 | ``` 36 | 37 | ## Vignette in R: for manual choice of lower_rna, barhop_rna, lower_atac and barhop_atac 38 | 39 | ``` 40 | library(Seurat) 41 | library(EmptyDropsMultiome) 42 | sce <- Read10X_h5("/path/to/folder/raw_feature_bc_matrix.h5") 43 | rna <- sce[["Gene Expression"]] 44 | atac <- sce[["Peaks"]] 45 | eD.out <- emptydrops_multiome(count_matrix_rna=rna, count_matrix_atac=atac, lower_rna=20, barhop_rna=200, lower_atac=10, barhop_atac=200) 46 | print("the number of cells detected is: ") 47 | print(sum(eD.out$FDR_multi<0.001 & ! is.na(eD.out$FDR_multi))) 48 | 49 | ``` 50 | 51 | 52 | ## EmptyDropsMultiome Output 53 | 54 | EmptyDropsMultiome returns a DataFrame object (from the S4Vectors package) with the following columns: 55 | - Total_RNA: Integer, the total count for each barcode. 56 | - LogProb_RNA: Numeric, the log-probability of observing the barcode's count vector under the null model. 57 | - PValue_RNA: Numeric, the Monte Carlo p-value against the null model. 58 | - Limited_RNA: Logical, indicating whether a lower p-value could be obtained by increasing niters. 59 | - FDR_RNA: Numeric, the p-values corrected using the Benjamini-Hochberg method 60 | - Total_chromatin: Integer, the total count for each barcode. 61 | - LogProb_chromatin: Numeric, the log-probability of observing the barcode's count vector under the null model. 62 | - PValue_chromatin: Numeric, the Monte Carlo p-value against the null model. 63 | - Limited_chromatin: Logical, indicating whether a lower p-value could be obtained by increasing niters. 64 | - FDR_chromatin: Numeric, the p-values corrected using the Benjamini-Hochberg method. 65 | - PValue_multi: Numeric, the p-values of the droplets after aggregating PValue_chromatin and PValue_RNA for each droplet. 66 | - FDR: Numeric, the result of the correction of PValue_multi using the Benjamini-Hochberg method 67 | - FDR_multi: Numeric, similar to FDR, except for droplets below the lower line (which have FDR_multi equal to 1) and the droplets above the higher line (which have FDR_multi equal to 0). 68 | - k_means: Logical, indicating whether droplet lies above the k-means line 69 | - above_ambiguous: Logical, indicating whether droplet lies above the ambiguous area, where droplets are assumed to unambiguously contain cells. 70 | 71 | 72 | ## Method overview 73 | 74 |

75 | 76 |

77 | 78 | EmptyDropsMultiome creates the RNA and ATAC profile of the ambient noise by selecting the ambient cluster of droplets in the histograms of RNA and ATAC counts. It then statistically compares droplets to it using a DirichletMultinomial model to calculate p-values. It also calculates the k-means line in the space of logarithmic counts and two lines parallel to it. The lower line passes through the point (lower_rna,lower_atac) and the higher line is 2/3 of the way from the k-means line to the top percentile of the distribution of counts of droplets. 79 | 80 | 81 | -------------------------------------------------------------------------------- /R/find_tip.R: -------------------------------------------------------------------------------- 1 | #' Finds the droplets that are in 1) the top 1% of RNA counts and in the top 0.1% of atac counts, and then 2 | #' calculates their mean RNA counts and mean ATAC counts. 3 | #' 4 | #' @param data Dataframe with data$rna being the number of RNA counts, and data$atac being the number of ATAC counts. 5 | #' @param equation A vector c(intercept, slope) that defines a line in 2d Euclidean space. 6 | #' 7 | #' @return A real vector with the two mean values. 8 | #' 9 | find_tip <- function(data, equation){ 10 | # data: dataframe with data$rna being the number of RNA counts, and data$atac being the number of ATAC counts 11 | # output: center coordinates of the center of the droplets in the top percentile 12 | 13 | counts = log10(data$Total_RNA+0.1) - equation[2] * log10(data$Total_chromatin + 0.1) 14 | p99_counts = stats::quantile(counts, probs = c(0.99), na.rm=TRUE ) 15 | tip = counts > p99_counts 16 | 17 | tip_center <- c( mean(data$Total_RNA[tip]), mean(data$Total_chromatin[tip]) ) 18 | 19 | print("the tip has rna count ") 20 | print(log10(tip_center[1]+0.1)) 21 | print("the tip has atac count ") 22 | print(log10(tip_center[2]+0.1)) 23 | 24 | return(tip_center) 25 | 26 | } 27 | 28 | #' Calculates the distance between a point and a line. 29 | #' 30 | #' @param equation A vector c(intercept, slope) that defines a line in 2d Euclidean space. 31 | #' @param point A 2d vector of coordinates. 32 | #' 33 | #' @return A single real number. 34 | #' 35 | dist_point_to_line <- function(equation, point){ 36 | # equation: numeric vector for intercept=equation[1] and slope=equation[2] 37 | # point: numeric vector for coordinates of point 38 | # output: dist, the distance of the point to the line (in 2d) 39 | 40 | intercept = equation[1] 41 | slope = equation[2] 42 | 43 | # if line has the form a*x+b*y+c=0 44 | a = slope 45 | b = -1 46 | c = intercept 47 | 48 | # point coordinates 49 | x0 = point[1] 50 | y0 = point[2] 51 | 52 | dist = abs(a*x0+b*y0+c)/sqrt(a^2+b^2) 53 | return(dist) 54 | 55 | } 56 | 57 | #' Calculate the equation of a line that is parallel to a given line and a given distance from it. 58 | #' 59 | #' @param equation A 2d vector c(intercept, slope) defining a line in 2d Euclidean space. 60 | #' @param dist A real number specifying the distance between the given line and the line to be calculated. 61 | #' 62 | #' @return A 2d vector c(intercept, slope) defining a line in 2d Euclidean space 63 | #' 64 | calc_intercept_of_parallel_line <- function(equation, dist){ 65 | # equation: numeric vector for intercept=equation[1] and slope=equation[2] 66 | # dist: real number for the distance between the given line and the line to be calculated 67 | # output: equation2, equation for the line to be calculated 68 | 69 | intercept1 = equation[1] 70 | slope = equation[2] 71 | 72 | intercept2 = intercept1 + dist * sqrt(slope^2 + 1) 73 | 74 | return( c( intercept2, slope) ) 75 | 76 | } 77 | 78 | #' Calculate a line that is parallel to the k-means line and a distance from it that is equal to 66% of the distance 79 | #' between the droplets with the biggest library size and the k-means line. The area bound by the k-means line and this 80 | #' line is referred to as ambiguous area and in it droplets are rejected by thresholding FDR_multi. 81 | #' Above this ambiguous area, droplets are assumed to contain nuclei/cells and their FDR_multi is set to 0 by default. 82 | #' 83 | #' @param data Dataframe of droplets with columns Total_RNA and Total_chromatin. 84 | #' @param equation 2d vector c(intercept, slope) defining the k-means line. 85 | #' 86 | #' @return 2d vector c(intercept, slope) defining the k-means line. 87 | #' 88 | calc_ambiguous_above <- function(data, equation){ 89 | # given the data, calculate the ambiguous above area (specifically the line outlining its upper bound) (i.e. the area just north of the cellranger-arc line) 90 | tip_center <- find_tip(data, equation) 91 | 92 | # log transform the coordinates 93 | tip_center = c( log10(tip_center[1]+0.1), log10(tip_center[2]+0.1) ) 94 | 95 | dist = dist_point_to_line(equation, tip_center) *2 / 3 96 | 97 | equation_parallel = calc_intercept_of_parallel_line(equation, dist) 98 | 99 | print("equation_parallel") 100 | print(equation_parallel) 101 | print("equation") 102 | print(equation) 103 | 104 | return(equation_parallel) 105 | 106 | 107 | } 108 | 109 | 110 | 111 | 112 | #' Calculate a line that is parallel to a given line and passes through the point (x, y). 113 | #' 114 | #' @param x A real number for the x coordinate of the point. 115 | #' @param y A real number for the y coordinate of the point. 116 | #' @param equation A 2d vector c(intercept, slope) defining a line in 2d Euclidean space. 117 | #' 118 | #' @return A 2d vector c(intercept, slope) defining a line in 2d Euclidean space. 119 | #' 120 | calc_lower_line <- function(x, y, equation){ 121 | # calculate a line equation_lower which is parallel to equation and goes through the point (x, y) 122 | 123 | slope = equation[2] 124 | intercept = y - slope * x 125 | 126 | if(intercept>equation[1]){ 127 | intercept = equation[1] 128 | } 129 | 130 | print("lower_line") 131 | print(c( intercept, slope)) 132 | 133 | return( c( intercept, slope) ) 134 | } 135 | 136 | 137 | -------------------------------------------------------------------------------- /R/accept_k_means.R: -------------------------------------------------------------------------------- 1 | #' After using emptydrops, set FDR_multi<-1 for cells above the ambiguous area, and set FDR_multi<-0 in cells below the lower line. 2 | #' 3 | #' @param e_multi.out Dataframe with columns for Total_RNA, Total_chromatin, rownames, barhop_amb_tent_chromatin, barhop_amb_tent_rna, FDR_multi 4 | #' @param lower_atac A single number to act as the value of the lower parameter in ATAC 5 | #' @param lower_rna A single number to act as the value of the lower parameter in RNA 6 | #' 7 | #' @return Dataframe with columns for Total_RNA, Total_chromatin, rownames, barhop_amb_tent_chromatin, 8 | #' barhop_amb_tent_rna, FDR_multi, FDR, above_ambiguous, k_means 9 | #' @export 10 | #' 11 | accept_k_means <- function( e_multi.out, lower_atac, lower_rna){ 12 | # it changes to 0 the FDR_multi value of droplets that lie above the k-means threshold 13 | # input: e_multi.out with a column "FDR_multi" 14 | # output: e_multi.out with adjusted column "FDR_multi" 15 | 16 | # create count dataframe with columns 'atac_count' (int), 'rna_count' (int), 'excluded' (bool), 'is_cell' 17 | 18 | count_df <- data.frame("rownames" = rownames(e_multi.out), 19 | "atac_count" = e_multi.out$Total_chromatin, 20 | "rna_count" = e_multi.out$Total_RNA, 21 | "excluded" = rep(F, length(e_multi.out$Total_RNA)), 22 | "is_cell" = rep(0, length(e_multi.out$Total_RNA)) 23 | ) 24 | count_df$atac_count[is.na(count_df$atac_count)] <- 0 25 | count_df$rna_count[is.na(count_df$rna_count)] <- 0 26 | 27 | list_output <- call_cells(count_df) 28 | count_df_new <- list_output[[1]] 29 | equation_k_means <- list_output[[2]] 30 | 31 | e_multi.out_new <- e_multi.out 32 | 33 | # replace NA values with 0 34 | e_multi.out_new$Total_RNA[is.na(e_multi.out_new$Total_RNA)] = 0 35 | e_multi.out_new$Total_chromatin[is.na(e_multi.out_new$Total_chromatin)] = 0 36 | 37 | # tag according to k_means (ie cellranger-arc) 38 | cell_barcodes <- count_df_new$rownames[which(count_df_new$is_cell==1) ] 39 | e_multi.out_new$k_means <- 0 40 | e_multi.out_new[cell_barcodes, ]$k_means <- 1 41 | 42 | # calculate the ambiguous_above area and tag cells 43 | equation_parallel <- calc_ambiguous_above(e_multi.out_new[,c("Total_RNA", "Total_chromatin")], equation_k_means) 44 | # cells_above_ambiguous <- e_multi.out_new$Total_chromatin - equation_k_means[2] * e_multi.out_new$Total_RNA > equation_k_means[1] & e_multi.out_new$Total_chromatin - equation_k_means[2] * e_multi.out_new$Total_RNA > equation_parallel[1] 45 | print(equation_parallel) 46 | cells_above_ambiguous <- log10(e_multi.out_new$Total_RNA+0.1) - equation_parallel[2] * log10(e_multi.out_new$Total_chromatin + 0.1) > equation_parallel[1] 47 | e_multi.out_new$above_ambiguous <- 0 48 | e_multi.out_new[cells_above_ambiguous, ]$above_ambiguous <- 1 49 | 50 | 51 | 52 | # cell calling plots 53 | graphics::par(mfrow = c(2, 2)) # Create a 2 x 2 plotting matrix 54 | graphics::par(mar=c(5,5,4,1)+.1) 55 | 56 | cell_calling_plot(log10(e_multi.out$Total_chromatin + 0.1), log10(e_multi.out$Total_RNA + 0.1), factor(e_multi.out$FDR_multi<0.001 ), "eD_multi tentative") 57 | graphics::abline(a=equation_k_means[1],b=equation_k_means[2], col="blue") 58 | graphics::abline(a=equation_parallel[1],b=equation_parallel[2], col="blue") 59 | 60 | cell_calling_plot(log10(e_multi.out$Total_chromatin + 0.1), log10(e_multi.out$Total_RNA + 0.1), factor(rownames(e_multi.out) %in% cell_barcodes ), "cR_multi calling") 61 | graphics::abline(a=equation_k_means[1],b=equation_k_means[2], col="blue") 62 | 63 | # reject by default droplets below both lowers or at least one of the barhops or the na 64 | e_multi.out_new$FDR_multi[e_multi.out_new$barhop_amb_tent_RNA==2] <- 1 65 | e_multi.out_new$FDR_multi[e_multi.out_new$barhop_amb_tent_chromatin==2] <- 1 66 | 67 | 68 | # calculate equation_lower and reject cells below it 69 | equation_lower = calc_lower_line(log10(lower_atac+0.1), log10(lower_rna+0.1), equation_k_means) 70 | e_multi.out_new$FDR_multi[log10(e_multi.out_new$Total_RNA+0.1) < equation_lower[2] * log10(e_multi.out_new$Total_chromatin + 0.1) + equation_lower[1] ] <- 1 71 | 72 | # turn FDR_multi==NA to FDR_multi==1 73 | e_multi.out_new$FDR_multi[is.na(e_multi.out_new$FDR_multi)] <- 1 74 | 75 | # plot effect of rejecting below lower and FDR_multi NA->1 76 | cell_calling_plot(log10(e_multi.out_new$Total_chromatin + 0.1), log10(e_multi.out_new$Total_RNA + 0.1), factor(e_multi.out_new$FDR_multi<0.001 ), "eD_multi after rejecting below lower") 77 | graphics::abline(a=equation_k_means[1],b=equation_k_means[2], col="blue") 78 | graphics::abline(a=equation_parallel[1],b=equation_parallel[2], col="blue") 79 | graphics::abline(a=equation_lower[1],b=equation_lower[2], col="blue") 80 | 81 | 82 | # accept by default all the droplets above the ambiguous area 83 | e_multi.out_new$FDR <- e_multi.out_new$FDR_multi 84 | e_multi.out_new[cells_above_ambiguous, ]$FDR_multi <- 0 85 | 86 | cell_calling_plot(log10(e_multi.out_new$Total_chromatin + 0.1), log10(e_multi.out_new$Total_RNA + 0.1), factor(e_multi.out_new$FDR_multi<0.001 ), "eD_multi after accepting above knee") 87 | graphics::abline(a=equation_k_means[1],b=equation_k_means[2], col="blue") 88 | graphics::abline(a=equation_parallel[1],b=equation_parallel[2], col="blue") 89 | graphics::abline(a=equation_lower[1],b=equation_lower[2], col="blue") 90 | 91 | # save the equations of the parallel lines in metadata 92 | e_multi.out_new@metadata["k_means_slope"] = equation_k_means[2] 93 | e_multi.out_new@metadata["k_means_intercept"] = equation_k_means[1] 94 | e_multi.out_new@metadata["higher_intercept"] = equation_parallel[1] 95 | e_multi.out_new@metadata["lower_intercept"] = equation_lower[1] 96 | 97 | return(e_multi.out_new) 98 | } 99 | -------------------------------------------------------------------------------- /R/cellranger_k_means_v2.R: -------------------------------------------------------------------------------- 1 | #' Finds a nice initialization for the K-means clustering 2 | #' 3 | #' @param x Vector of real values. 4 | #' 5 | #' @return Value roughly equal to 1/10 of the 99% percentile of values. 6 | #' 7 | simpler_ordmag <- function(x){ 8 | # This function finds a nice initialization for the K-means clustering: 9 | # finds 99% percentile cut-off, and retains cell with count>99%cutoff/10; 10 | # then removes the top 1% of these; 11 | # if that removes all cells, then return the initial 99%cutoff/10, else, then compute the new 99% percentile cutoff 12 | # and return new99%cutoff/10 13 | # x: vector with counts per cell 14 | # output: count number that separates tentative empty droplets and cell-containing droplets 15 | 16 | p99_1 = stats::quantile(x, probs = c(0.99), na.rm=TRUE ) 17 | ordmag = x > p99_1 / 10.0 18 | if (sum(ordmag) == 0){ 19 | return(0) 20 | } 21 | top_1_ordmag = stats::quantile(x[ordmag], 0.99, na.rm=TRUE) 22 | ordmag2 = x < top_1_ordmag 23 | # use the previous threshold 24 | if (sum(ordmag2) == 0){ 25 | return(p99_1 / 10.0) 26 | } 27 | p99_2 = stats::quantile(x[ordmag2], 0.99) 28 | #print(p99_2) 29 | 30 | return(p99_2 / 10.0) 31 | 32 | } 33 | 34 | #' Log-transform the data. 35 | #' 36 | #' @param data Dataframe with column atac_count and column rna_count 37 | #' 38 | #' @return Dataframe with with log-transformed column values 39 | #' 40 | log_transform <- function(data){ 41 | # data: dataframe with column "atac_count" and "rna_count" 42 | # output: dataframe with log10 transformed columns 43 | data["atac_count"] <- log10(data["atac_count"]+0.1) 44 | data["rna_count"] <- log10(data["rna_count"]+0.1) 45 | return(data) 46 | } 47 | 48 | 49 | 50 | 51 | #' Assigns the value is_cell of the unique elements to the value is_cell of their corresponding duplicates. 52 | #' 53 | #' @param data Dataframe with columns 'atac_count' (int), 'rna_count' (int), 'excluded' (bool), 'is_cell' (bool), 'dup' (bool). 54 | #' data is sorted wrt 'atac_count' (int), 'rna_count' (int), 'dup' (bool). 55 | #' @return Dataframe with altered is_cell column. 56 | #' 57 | transfer_labels_to_dedupl_v3 <- function(data){ 58 | # data: dataframe with columns 'atac_count' (int), 'rna_count' (int), 'excluded' (bool), 'is_cell' (bool), 'dup' (bool) 59 | # data is sorted wrt 'atac_count' (int), 'rna_count' (int), 'dup' (bool) 60 | # take in the data dataframe and pass to the duplicates the labels you've calculated for the corresponding unduplicated barcode 61 | # return data 62 | 63 | print(colnames(data)) 64 | 65 | uniques = which(data$dup==F) 66 | uniques = append(uniques, length(data$dup)+1) 67 | numb_of_duplicates = diff(uniques)-1 68 | 69 | i=1 70 | for (cell_no in uniques[seq(1, length(uniques)-1)]){ 71 | if (numb_of_duplicates[i]!=0){ 72 | data$is_cell[seq(cell_no+1, cell_no+numb_of_duplicates[i])] = data$is_cell[cell_no] 73 | } 74 | i = i+1 75 | } 76 | 77 | return(data) 78 | } 79 | 80 | 81 | 82 | #' Call cells using k-means and store this information in is_cell. 83 | #' 84 | #' @param data Dataframe with columns 'atac_count' (int), 'rna_count' (int), 'excluded' (bool), 'is_cell'. 85 | #' @param verbose if TRUE various intermediate steps and plots are printed. 86 | #' 87 | #' @return Dataframe with columns 'atac_count' (int), 'rna_count' (int), 'excluded' (bool), 'is_cell'. 88 | #' @export 89 | #' 90 | call_cells <- function(data, verbose=TRUE){ 91 | # data: dataframe with columns 'atac_count' (int), 'rna_count' (int), 'excluded' (bool), 'is_cell', 92 | # e.g. df <- data.frame( "rna_count"= seurat_024@meta.data[["nCount_RNA"]], "atac_count"= seurat_024@meta.data[["nCount_ATAC"]], 93 | # "excluded"= rep(F,each=length(colnames(seurat_024))), "is_cell"= rep(0,each=length(colnames(seurat_024))) ) 94 | # output data: dataframe with columns 'atac_count' (int), 'rna_count' (int), 'excluded' (bool), 'is_cell' (bool), "dup" (bool) 95 | # where the is_cell column has been calculated using K-means 96 | 97 | print("Call cells using cellranger-arc") 98 | data <- data[order(data$atac_count, data$rna_count, data$excluded),] 99 | exclude_rowname <- c("atac_count", "rna_count", "excluded", "is_cell") 100 | data["dup"] <- duplicated(data[, exclude_rowname]) 101 | print("finished ordering") 102 | keep <- !data["dup"] & !data$excluded & data$atac_count>0 & data$rna_count>0 # !data$is_cell & !data["dup"] #mask(data) 103 | print("calculated keep") 104 | 105 | 106 | threshold = vector(mode="numeric", length=2) 107 | names(threshold) <- c("atac", "rna") 108 | 109 | # 1: do ordmag calling and identify centroids 110 | for (assay in c("atac", "rna")){ 111 | threshold[assay]= simpler_ordmag(data[keep, paste0(assay,"_count")]) 112 | ordmag_filter <- data$atac_count > threshold["atac"] & data$rna_count > threshold["rna"] 113 | } 114 | 115 | print(paste0("thresholds are ", threshold)) 116 | 117 | # if ordmag calls everything a cell, then do that 118 | if (length(unique(ordmag_filter))==1){ 119 | data[keep, "is_cell"]=1 120 | 121 | print("all_called by ordmag") 122 | print(unique(ordmag_filter)) 123 | 124 | data <- transfer_labels_to_dedupl_v3(data) 125 | print("finished label transfer") 126 | 127 | equation = c(0, 0) 128 | }else{ 129 | set.seed(123) 130 | # Do scaling i.e. log transform 131 | df_for_km <- log_transform(data[,c("rna_count", "atac_count")]) 132 | 133 | mean_atac_cell <- mean(df_for_km[keep & ordmag_filter, c("atac_count")]) 134 | mean_rna_cell <- mean(df_for_km[keep & ordmag_filter, c("rna_count")]) 135 | mean_atac_empty <- mean(df_for_km[keep & !ordmag_filter, c("atac_count")]) 136 | mean_rna_empty <- mean(df_for_km[keep & !ordmag_filter, c("rna_count")]) 137 | 138 | print("the means of the two clusters are: ") 139 | print( data.frame( "rna_count"=c(mean_rna_empty ,mean_rna_cell), "atac_count"=c(mean_atac_empty, mean_atac_cell ) ) ) 140 | 141 | km <- stats::kmeans( df_for_km[keep, c("rna_count", "atac_count")], centers=data.frame( "rna_count"=c(mean_rna_empty ,mean_rna_cell), "atac_count"=c(mean_atac_empty, mean_atac_cell ) ) ) 142 | #print(paste0("number of cells in km object is ", sum(km[["cluster"]])-length(km[["cluster"]]) ) ) 143 | 144 | # take center information and then exchange rna and atac (since atac needs to be on the x axis) 145 | center1 = c( km$centers[1,2], km$centers[1,1] ) 146 | center2 = c( km$centers[2,2], km$centers[2,1] ) 147 | 148 | # calculate the perpendicular bisector line to the segment defined by the two centers (i.e. the k-means line) 149 | equation = perp_bisector(center2, center1) 150 | print(equation) 151 | 152 | 153 | # if k-means calls everything a cell, do that 154 | if (length(unique(km[["cluster"]]))==1 ){ 155 | data[keep, "is_cell"]=1 156 | }else{ 157 | mean_1 <- mean(km[["centers"]][1]) 158 | mean_2 <- mean(km[["centers"]][2]) 159 | km[["cluster"]] <- km[["cluster"]]-1 160 | if (mean_1 > mean_2){ 161 | km[["cluster"]] <- 1-km[["cluster"]] 162 | } 163 | data[keep, "is_cell"]= km[["cluster"]] 164 | 165 | } 166 | } 167 | 168 | 169 | # # plot cell calling before label transfer 170 | # cell_calling_plot(log10(data$atac_count + 0.1), log10(data$rna_count + 0.1), factor(data$is_cell ), paste0("cR-arc calling before label transfer: ", sum(data$is_cell), " cells;", equation)) 171 | # graphics::abline(a=equation[1],b=equation[2], col="blue") 172 | 173 | # transfer labels 174 | data <- transfer_labels_to_dedupl_v3(data) 175 | print("finished label transfer") 176 | 177 | # # plot cell calling after label transfer 178 | # cell_calling_plot(log10(data$atac_count + 0.1), log10(data$rna_count + 0.1), factor(data$is_cell ), paste0("cR-arc calling after label transfer: ", sum(data$is_cell), " cells;", equation)) 179 | # graphics::abline(a=equation[1],b=equation[2], col="blue") 180 | 181 | print("The number of cells called by k-means is ") 182 | print(paste0(sum(data$is_cell), " cells")) 183 | 184 | 185 | return(list(data, equation) ) 186 | 187 | } 188 | -------------------------------------------------------------------------------- /R/emptydrops_multiome.R: -------------------------------------------------------------------------------- 1 | #' Calls cells using emptydrops in two genomic modalities. 2 | #' 3 | #' @param count_matrix_rna dgCMatrix with the counts for the rna modality. 4 | #' @param lower_rna single real number at or below which droplets are used to model the RNA soup. 5 | #' @param barhop_rna single real number below which droplets are assumed to be full of barhops and they are excluded from modeling the soup. 6 | #' @param count_matrix_atac dgCMatrix with the counts for the ATAC modality. 7 | #' @param lower_atac single real number at or below which droplets are used to model the ATAC soup. 8 | #' @param barhop_atac single real number below which droplets are assumed to be full of barhops and they are excluded from modeling the soup. 9 | #' @param seed the value at which to set the seed. 10 | #' @param niter_rna single real number for the number of iteration to be performed to statistically compare the RNA modality with the ambient profile. 11 | #' @param niter_atac single real number for the number of iteration to be performed to statistically compare the ATAC modality with the ambient profile. 12 | #' @param verbose if TRUE various intermediate steps and plots are printed. 13 | #' 14 | #' 15 | #' 16 | #' @return a DataFrame object (from the S4Vectors package) with the following components: 17 | #' Total_RNA: 18 | #' Integer, the total count for each barcode. 19 | #' LogProb_RNA: 20 | #' Numeric, the log-probability of observing the barcode's count vector under the null model. 21 | #' PValue_RNA: 22 | #' Numeric, the Monte Carlo p-value against the null model. 23 | #' Limited_RNA: 24 | #' Logical, indicating whether a lower p-value could be obtained by increasing niters. 25 | #' FDR_RNA: 26 | #' Numeric, the p-values corrected using the Benjamini-Hochberg method 27 | #' Total_chromatin: 28 | #' Integer, the total count for each barcode. 29 | #' LogProb_chromatin: 30 | #' Numeric, the log-probability of observing the barcode's count vector under the null model. 31 | #' PValue_chromatin: 32 | #' Numeric, the Monte Carlo p-value against the null model. 33 | #' Limited_chromatin: 34 | #' Logical, indicating whether a lower p-value could be obtained by increasing niters. 35 | #' FDR_chromatin: 36 | #' Numeric, the p-values corrected using the Benjamini-Hochberg method 37 | #' PValue_multi: 38 | #' Numeric, the p-values of the droplets after aggregating PValue_chromatin and PValue_RNA for each droplet 39 | #' FDR_multi: 40 | #' Numeric, the result of the correction of PValue_multi using the Benjamini-Hochberg method 41 | #' k_means: 42 | #' Logical, indicating whether droplet lies above the k-means line 43 | #' above_ambiguous: 44 | #' Logical, indicating whether droplet lies above the ambiguous area, where droplets are assumed to unambiguously contain cells. 45 | #' 46 | #' 47 | #' @export 48 | #' 49 | emptydrops_multiome <- function(count_matrix_rna, lower_rna=NULL, barhop_rna=NULL, count_matrix_atac, lower_atac=NULL, barhop_atac=NULL, niter_rna=10000, niter_atac=25000, verbose=TRUE, seed=42 ){ 50 | 51 | if (!is.null(lower_rna) & !is.null(barhop_rna) & !is.null(lower_atac) & !is.null(barhop_atac) ){ 52 | if (lower_rna<0 | barhop_rna<0 | lower_atac<0 | barhop_atac<0){ 53 | stop("barhop and lower parameters should be non negative") 54 | } 55 | } 56 | 57 | if ( is.null(lower_rna) | is.null(barhop_rna) ){ 58 | exp_counts_per_cell = unname(Matrix::colSums(count_matrix_rna)) 59 | mu1 = fit_3_normals(exp_counts_per_cell, verbose) 60 | lower_rna = mu1[1] 61 | barhop_rna = mu1[2] 62 | print(paste0("the rna lower is ",lower_rna ) ) 63 | print(paste0("the rna barhop is ",barhop_rna ) ) 64 | }else{ 65 | exp_counts_per_cell_rna = unname(Matrix::colSums(count_matrix_rna)) 66 | observations = data.frame( "nCount_RNA" = exp_counts_per_cell_rna ) 67 | 68 | print(ggplot2::ggplot(observations, ggplot2::aes(x = nCount_RNA)) + 69 | ggplot2::geom_histogram(binwidth =1) + 70 | ggplot2::xlim(0, 700)+ 71 | ggplot2::scale_y_continuous( limit = c(0, 100000), oob = function(x, limits) x)+ 72 | ggplot2::geom_vline(xintercept = lower_rna, 73 | # linetype="dotted", 74 | color = "blue", 75 | size=0.5)+ 76 | ggplot2::geom_vline(xintercept = barhop_rna, 77 | # linetype="dotted", 78 | color = "red", 79 | size=0.5) ) 80 | 81 | 82 | } 83 | 84 | if ( is.null(lower_atac) | is.null(barhop_atac) ){ 85 | exp_counts_per_cell = unname(Matrix::colSums(count_matrix_atac)) 86 | 87 | mu2 = fit_3_normals_atac( exp_counts_per_cell, verbose ) 88 | lower_atac = mu2[1] 89 | barhop_atac = mu2[2] 90 | print(paste0("the atac lower is ", lower_atac ) ) 91 | print(paste0("the atac barhop is ", barhop_atac ) ) 92 | }else{ 93 | exp_counts_per_cell = unname(Matrix::colSums(count_matrix_atac)) 94 | observations = data.frame( "nCount_ATAC" = exp_counts_per_cell ) 95 | 96 | ggplot2::ggplot(observations, ggplot2::aes(x = nCount_ATAC)) + 97 | ggplot2::geom_histogram(binwidth =1) + 98 | ggplot2::scale_x_continuous( limit = c(0, 500), oob = function(x, limits) x)+ 99 | ggplot2::scale_y_continuous( limit = c(0, 100000), oob = function(x, limits) x)+ 100 | ggplot2::geom_vline(xintercept = lower_atac, 101 | # linetype="dotted", 102 | color = "blue", 103 | size=0.5)+ 104 | ggplot2::geom_vline(xintercept = barhop_atac, 105 | # linetype="dotted", 106 | color = "red", 107 | size=0.5) 108 | 109 | 110 | } 111 | 112 | # call cells based on RNA 113 | eD.out_rna <- emptydrops_with_barhop(count_matrix_rna, lower_rna, barhop_rna, niters=niter_rna, seed=seed) 114 | 115 | # call cells based on epigenetics 116 | eD.out_atac <- emptydrops_with_barhop(count_matrix_atac, lower_atac, barhop_atac, niters=niter_atac, seed=seed) 117 | 118 | # call cells based on both RNA and epigenetics 119 | e_multi.out <- aggr_p_values( eD.out_rna, eD.out_atac) 120 | 121 | # accept cells based on k_means 122 | e_multi.out <- accept_k_means(e_multi.out, lower_atac, lower_rna) 123 | 124 | # add metadata to e_multi.out 125 | # e_multi.out$lower_rna = lower_rna 126 | # e_multi.out$barhop_rna=barhop_rna 127 | # e_multi.out$lower_atac =lower_atac 128 | # e_multi.out$barhop_atac=barhop_atac 129 | 130 | e_multi.out@metadata["lower_rna"] = lower_rna 131 | e_multi.out@metadata["barhop_rna"]=barhop_rna 132 | e_multi.out@metadata["lower_atac"] =lower_atac 133 | e_multi.out@metadata["barhop_atac"]=barhop_atac 134 | 135 | return(e_multi.out) 136 | 137 | } 138 | 139 | 140 | #' #' Plots histogram of counts 141 | #' #' 142 | #' #' @param ct_matrix: a matrix of counts 143 | #' #' @param assay_name: the type of counts e.g. "RNA" or "ATAC" 144 | #' #' @param lower 145 | #' #' @param barhop_end 146 | #' #' 147 | #' #' @return plots 148 | #' #' 149 | #' ct_hist <- function(ct_matrix, assay_name, lower, barhop_end){ 150 | #' 151 | #' exp_counts_per_cell = unname(Matrix::colSums(ct_matrix)) 152 | #' observations = data.frame( "nCount" = exp_counts_per_cell ) 153 | #' colnames(observations) <- paste0("nCount_", assay_name) 154 | #' 155 | #' print(ggplot2::ggplot(observations, ggplot2::aes(x = nCount_RNA)) + 156 | #' ggplot2::geom_histogram(binwidth =1) + 157 | #' ggplot2::xlim(0, 500)+ 158 | #' ggplot2::scale_y_continuous( limit = c(0, 80000), oob = function(x, limits) x)+ 159 | #' ggplot2::geom_vline(xintercept = lower_rna, 160 | #' # linetype="dotted", 161 | #' color = "blue", 162 | #' size=0.5)+ 163 | #' ggplot2::geom_vline(xintercept = barhop_rna, 164 | #' # linetype="dotted", 165 | #' color = "red", 166 | #' size=0.5) ) 167 | #' 168 | #' ggplot2::ggplot(observations, ggplot2::aes(x = nCount_RNA)) + 169 | #' ggplot2::geom_histogram(binwidth =1) + 170 | #' ggplot2::scale_x_continuous( limit = c(0, 10000), oob = function(x, limits) x)+ 171 | #' ggplot2::scale_y_continuous( limit = c(0, 40), oob = function(x, limits) x)+ 172 | #' ggplot2::geom_vline(xintercept = lower_rna, 173 | #' # linetype="dotted", 174 | #' color = "blue", 175 | #' size=0.5)+ 176 | #' ggplot2::geom_vline(xintercept = barhop_rna, 177 | #' # linetype="dotted", 178 | #' color = "red", 179 | #' size=0.5) 180 | #' 181 | #' 182 | #' 183 | #' } 184 | 185 | -------------------------------------------------------------------------------- /R/fit_3_normals.R: -------------------------------------------------------------------------------- 1 | #' Fits a mixture of three normal distributions to histogram of RNA counts, to infer the parameters lower and barhop_end 2 | #' which are used in emptydrops. 3 | #' 4 | #' @param exp_counts_per_cell a vector with RNA library size per barcode. 5 | #' @param verbose if TRUE various intermediate steps and plots are printed. 6 | #' 7 | #' @return A 2d vector with the values lower and barhop_end for RNA. 8 | #' 9 | #' @export 10 | #' 11 | fit_3_normals <- function(exp_counts_per_cell, verbose=TRUE){ 12 | 13 | my_mix <- tryCatch( 14 | { 15 | mixtools::normalmixEM(exp_counts_per_cell, mu=c(5,500,1200), sigma=c(5,50,800) , epsilon=1e-09) 16 | }, 17 | error=function(cond) { 18 | message("Use default settings for barhop_end and lower") 19 | # Choose a default values in case of convergence error 20 | return(data.frame("mu"=c(25, 200, 1000 ), "sigma"=c(1, 60, 300 ), "lambda"= c(1/1.15, 0.10/1.15, 0.05/1.15))) 21 | }, 22 | warning=function(cond) {}, 23 | finally={} 24 | ) 25 | 26 | 27 | n = length(exp_counts_per_cell) 28 | mu_order = order(my_mix$mu) 29 | mu_barhop = my_mix$mu[mu_order[1]] 30 | mu_ambient = my_mix$mu[mu_order[2]] 31 | mu_true_cells = my_mix$mu[mu_order[3]] 32 | 33 | if (mu_barhop > 100 | mu_ambient >700 | mu_barhop>mu_ambient-15){ 34 | my_mix <- data.frame("mu"=c(25, 200, 1000 ), "sigma"=c(1, 60, 300 ), "lambda"= c(1/1.15, 0.10/1.15, 0.05/1.15)) 35 | n = length(exp_counts_per_cell) 36 | mu_order = order(my_mix$mu) 37 | mu_barhop = my_mix$mu[mu_order[1]] 38 | mu_ambient = my_mix$mu[mu_order[2]] 39 | mu_true_cells = my_mix$mu[mu_order[3]] 40 | } 41 | 42 | lower = my_mix$mu[mu_order[2]]+1.5*my_mix$sigma[mu_order[2]] 43 | equil_pt = equil_of_normals(mu_barhop, my_mix$sigma[mu_order[1]], my_mix$lambda[mu_order[1]], 44 | mu_ambient, my_mix$sigma[mu_order[2]], my_mix$lambda[mu_order[2]]) 45 | 46 | if (verbose){ 47 | 48 | print(paste0("the mu's are : ", my_mix$mu[1],", ", my_mix$mu[2],", ", my_mix$mu[3] )) 49 | my_mix$mu 50 | print(paste0("the sigma's are : ", my_mix$sigma[1],", ", my_mix$sigma[2],", ", my_mix$sigma[3] )) 51 | my_mix$sigma 52 | print(paste0("the lambdas are : ", my_mix$lambda[1],", ", my_mix$lambda[2],", ", my_mix$lambda[3] )) 53 | my_mix$lambda 54 | print(paste0("equil point is ", equil_pt) ) 55 | print(paste0("the lower is : ", lower )) 56 | 57 | plot_counts(exp_counts_per_cell, mu_barhop, my_mix$sigma[mu_order[1]], my_mix$lambda[mu_order[1]], 58 | mu_ambient, my_mix$sigma[mu_order[2]], my_mix$lambda[mu_order[2]], 59 | vline1 = equil_pt, vline2 = lower) 60 | 61 | } 62 | 63 | return(c(lower, equil_pt)) 64 | } 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | #' Fits a mixture of three normal distributions to histogram of ATAC counts, to infer the parameters lower and barhop_end 73 | #' which are used in emptydrops. 74 | #' 75 | #' @param exp_counts_per_cell a vector with the ATAC library size per barcode. 76 | #' @param verbose if TRUE various intermediate steps and plots are printed. 77 | #' 78 | #' @return A 2d vector with the values lower and barhop_end for ATAC. 79 | #' 80 | #' @export 81 | #' 82 | fit_3_normals_atac <- function(exp_counts_per_cell, verbose=TRUE){ 83 | 84 | # t <- try(my_mix <- mixtools::normalmixEM(exp_counts_per_cell, lambda=c(6*10^5/(7*10^5), 8*10^4/(7*10^5), 10^4/(7*10^5) ), 85 | # mu=c(5,100,10000), sigma=c(5,50,800) , epsilon=1e-09)) 86 | # print(inherits(t,"try-error")) 87 | # if( inherits(t,"try-error") ){ 88 | # my_mix <- data.frame("mu"=c(1, 40, 800 ), "sigma"=c(1, 60, 600 ), "lambda"= c(1,0.10,0.05)) 89 | # } 90 | # 91 | 92 | my_mix <- tryCatch( 93 | { 94 | mixtools::normalmixEM(exp_counts_per_cell, lambda=c(6*10^5/(7*10^5), 8*10^4/(7*10^5), 10^4/(7*10^5) ), 95 | mu=c(5,100,10000), sigma=c(5,50,800) , epsilon=1e-09) 96 | }, 97 | error=function(cond) { 98 | message("Use default settings for barhop_end and lower") 99 | # Choose a default values in case of convergence error 100 | return(data.frame("mu"=c(1, 40, 800 ), "sigma"=c(1, 60, 600 ), "lambda"= c(1,0.10,0.05))) 101 | }, 102 | warning=function(cond) {}, 103 | finally={} 104 | ) 105 | 106 | 107 | n = length(exp_counts_per_cell) 108 | mu_order = order(my_mix$mu) 109 | mu_barhop = my_mix$mu[mu_order[1]] 110 | mu_ambient = my_mix$mu[mu_order[2]] 111 | mu_true_cells = my_mix$mu[mu_order[3]] 112 | 113 | if (mu_barhop > 60 | mu_ambient >600 | mu_barhop>mu_ambient-15){ 114 | my_mix <- data.frame("mu"=c(1, 40, 800 ), "sigma"=c(1, 60, 600 ), "lambda"= c(1,0.10,0.05)) 115 | mu_order = order(my_mix$mu) 116 | mu_barhop = my_mix$mu[mu_order[1]] 117 | mu_ambient = my_mix$mu[mu_order[2]] 118 | mu_true_cells = my_mix$mu[mu_order[3]] 119 | } 120 | 121 | equil_pt = equil_of_normals(mu_barhop, my_mix$sigma[mu_order[1]], my_mix$lambda[mu_order[1]], 122 | mu_ambient, my_mix$sigma[mu_order[2]], my_mix$lambda[mu_order[2]]) 123 | lower = my_mix$mu[mu_order[2]]+2*my_mix$sigma[mu_order[2]] 124 | true_cells = my_mix$mu[mu_order[3]] 125 | 126 | 127 | if (verbose){ 128 | 129 | print(paste0("the mu's are : ", my_mix$mu[1],", ", my_mix$mu[2],", ", my_mix$mu[3] )) 130 | my_mix$mu 131 | print(paste0("the sigma's are : ", my_mix$sigma[1],", ", my_mix$sigma[2],", ", my_mix$sigma[3] )) 132 | my_mix$sigma 133 | print(paste0("the lambdas are : ", my_mix$lambda[1],", ", my_mix$lambda[2],", ", my_mix$lambda[3] )) 134 | my_mix$lambda 135 | print(paste0("equil point is ", equil_pt) ) 136 | print(paste0("the lower is : ", lower )) 137 | 138 | plot_counts(exp_counts_per_cell, mu_barhop, my_mix$sigma[mu_order[1]], my_mix$lambda[mu_order[1]], 139 | mu_ambient, my_mix$sigma[mu_order[2]], my_mix$lambda[mu_order[2]], 140 | vline1 = equil_pt, vline2 = lower) 141 | 142 | } 143 | 144 | 145 | return(c(lower, equil_pt)) 146 | } 147 | 148 | 149 | 150 | # Find point of equal probability 151 | 152 | #' Find the point of equal probability between two Gaussian components of a Gaussian Mixture Model 153 | #' 154 | #' @param mu1 the mean of the first Gaussian distribution 155 | #' @param sd1 the standard deviation of the first Gaussian distribution 156 | #' @param lam1 the mixing ratio of the first Gaussian distribution 157 | #' @param mu2 the mean of the second Gaussian distribution 158 | #' @param sd2 the standard deviation of the second Gaussian distribution 159 | #' @param lam2 the mixing ratio of the second Gaussian distribution 160 | #' 161 | #' @return Real number for the point of intersection of the Gaussians 162 | #' 163 | equil_of_normals <- function(mu1, sd1, lam1, mu2, sd2, lam2){ 164 | 165 | a = 1/sd1^2 - 1/sd2^2 166 | b = -2*( (mu1)/sd1^2 - (mu2)/sd2^2 ) 167 | c = mu1^2/sd1^2 - mu2^2/sd2^2 + 2*log( lam2*sd1 / (sd2*lam1) ) 168 | discr = b^2 - 4*a*c 169 | 170 | if (a==0){ 171 | return(-c/b) 172 | } 173 | 174 | if (discr<= 0 ){ 175 | equil_pt = NULL 176 | } else { 177 | equil_pt = ( -b + base::sqrt(discr) ) / (2*a) 178 | } 179 | 180 | return(equil_pt) 181 | 182 | } 183 | 184 | 185 | 186 | #' Plot histogram of counts for lower and barhop_end inference 187 | #' 188 | #' @param nCount vector with the RNA or ATAC counts 189 | #' @param mu1 mu of first Gaussian 190 | #' @param sigma1 sigma of first Gaussian 191 | #' @param lam1 lambda of first Gaussian 192 | #' @param mu2 mu of first Gaussian 193 | #' @param sigma2 sigma of first Gaussian 194 | #' @param lam2 lambda of first Gaussian 195 | #' @param max upper limit of RNA range 196 | #' @param vline1 x value of first vertical line 197 | #' @param vline2 x value of second vertical line 198 | #' @param label label for x axis 199 | #' 200 | #' @return None 201 | #' @export 202 | #' 203 | plot_counts <- function(nCount, mu1, sigma1, lam1, mu2, sigma2, lam2, max=50000, vline1, vline2, label){ 204 | 205 | observations = data.frame( "nCount" = nCount ) 206 | 207 | n = length(observations$nCount) 208 | 209 | # overview = ggplot2::ggplot(observations) + ggplot2::theme_bw() + 210 | # ggplot2::geom_histogram(ggplot2::aes(x = nCount), binwidth = 1, colour = "black", 211 | # fill = "black") + 212 | # ggplot2::stat_function(geom = "line", fun = function(x, mu, sigma, lam) { n*lam * stats::dnorm(x, mu, sigma) }, 213 | # args = list(mu1, sigma1, lam = lam1), 214 | # colour = "red", lwd = 1) + 215 | # ggplot2::stat_function(geom = "line", fun = function(x, mu, sigma, lam) {n* lam * stats::dnorm(x, mu, sigma) }, 216 | # args = list(mu2, sigma2, lam = lam2), 217 | # colour = "blue", lwd = 1) + 218 | # ggplot2::scale_x_continuous( limit = c(0, vline2+100), oob = function(x, limits) x)+ 219 | # ggplot2::scale_y_continuous( limit = c(0, max), oob = function(x, limits) x)+ 220 | # ggplot2::ylab("Frequency") + 221 | # ggplot2::xlab("nCount") + 222 | # ggplot2::ggtitle("Final GMM Fit")+ 223 | # ggplot2::geom_vline(xintercept = vline1, 224 | # # linetype="dotted", 225 | # color = "purple", 226 | # size=0.5)+ 227 | # ggplot2::geom_vline(xintercept = vline2, 228 | # # linetype="dotted", 229 | # color = "blue", 230 | # size=0.5) 231 | 232 | overview_nofit = ggplot2::ggplot(observations) + ggplot2::theme_bw() + 233 | ggplot2::geom_histogram(ggplot2::aes(x = nCount), binwidth = 1, colour = "black", 234 | fill = "black") + 235 | ggplot2::scale_x_continuous( limit = c(0, vline2+100), oob = function(x, limits) x)+ 236 | ggplot2::scale_y_continuous( limit = c(0, max), oob = function(x, limits) x)+ 237 | ggplot2::ylab("Frequency") + 238 | ggplot2::xlab("nCount") + 239 | ggplot2::ggtitle("GMM Fit")+ 240 | ggplot2::geom_vline(xintercept = vline1, 241 | # linetype="dotted", 242 | color = "purple", 243 | size=0.5)+ 244 | ggplot2::geom_vline(xintercept = vline2, 245 | # linetype="dotted", 246 | color = "blue", 247 | size=0.5) 248 | 249 | 250 | # zoomin = ggplot2::ggplot(observations) + ggplot2::theme_bw() + 251 | # ggplot2::geom_histogram(ggplot2::aes(x = nCount), binwidth = 1, colour = "black", 252 | # fill = "black") + 253 | # ggplot2::stat_function(geom = "line", fun = function(x, mu, sigma, lam) { n*lam * stats::dnorm(x, mu, sigma) }, 254 | # args = list(mu1, sigma1, lam = lam1), 255 | # colour = "red", lwd = 1) + 256 | # ggplot2::stat_function(geom = "line", fun = function(x, mu, sigma, lam) {n* lam * stats::dnorm(x, mu, sigma) }, 257 | # args = list(mu2, sigma2, lam = lam2), 258 | # colour = "blue", lwd = 1) + 259 | # ggplot2::scale_x_continuous( limit = c(0, vline2+100), oob = function(x, limits) x)+ 260 | # ggplot2::scale_y_continuous( limit = c(0, 3*n* lam2* stats::dnorm(mu2, mu2, sigma2)), oob = function(x, limits) x)+ 261 | # ggplot2::ylab("Frequency") + 262 | # ggplot2::xlab("nCount") + 263 | # ggplot2::ggtitle("Final GMM Fit")+ 264 | # ggplot2::geom_vline(xintercept = vline1, 265 | # # linetype="dotted", 266 | # color = "purple", 267 | # size=0.5)+ 268 | # ggplot2::geom_vline(xintercept = vline2, 269 | # # linetype="dotted", 270 | # color = "blue", 271 | # size=0.5) 272 | 273 | # print(overview) 274 | print(overview_nofit) 275 | # print(zoomin) 276 | 277 | } 278 | 279 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU General Public License 2 | ========================== 3 | 4 | _Version 3, 29 June 2007_ 5 | _Copyright © 2007 Free Software Foundation, Inc. <>_ 6 | 7 | Everyone is permitted to copy and distribute verbatim copies of this license 8 | document, but changing it is not allowed. 9 | 10 | ## Preamble 11 | 12 | The GNU General Public License is a free, copyleft license for software and other 13 | kinds of works. 14 | 15 | The licenses for most software and other practical works are designed to take away 16 | your freedom to share and change the works. By contrast, the GNU General Public 17 | License is intended to guarantee your freedom to share and change all versions of a 18 | program--to make sure it remains free software for all its users. We, the Free 19 | Software Foundation, use the GNU General Public License for most of our software; it 20 | applies also to any other work released this way by its authors. You can apply it to 21 | your programs, too. 22 | 23 | When we speak of free software, we are referring to freedom, not price. Our General 24 | Public Licenses are designed to make sure that you have the freedom to distribute 25 | copies of free software (and charge for them if you wish), that you receive source 26 | code or can get it if you want it, that you can change the software or use pieces of 27 | it in new 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 these rights or 30 | asking you to surrender the rights. Therefore, you have certain responsibilities if 31 | you distribute copies of the software, or if you modify it: responsibilities to 32 | respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether gratis or for a fee, 35 | you must pass on to the recipients the same freedoms that you received. You must make 36 | sure that they, too, receive or can get the source code. And you must show them these 37 | terms so they know their rights. 38 | 39 | Developers that use the GNU GPL protect your rights with two steps: **(1)** assert 40 | copyright on the software, and **(2)** offer you this License giving you legal permission 41 | to copy, distribute and/or modify it. 42 | 43 | For the developers' and authors' protection, the GPL clearly explains that there is 44 | no warranty for this free software. For both users' and authors' sake, the GPL 45 | requires that modified versions be marked as changed, so that their problems will not 46 | be attributed erroneously to authors of previous versions. 47 | 48 | Some devices are designed to deny users access to install or run modified versions of 49 | the software inside them, although the manufacturer can do so. This is fundamentally 50 | incompatible with the aim of protecting users' freedom to change the software. The 51 | systematic pattern of such abuse occurs in the area of products for individuals to 52 | use, which is precisely where it is most unacceptable. Therefore, we have designed 53 | this version of the GPL to prohibit the practice for those products. If such problems 54 | arise substantially in other domains, we stand ready to extend this provision to 55 | those domains in future versions of the GPL, as needed to protect the freedom of 56 | users. 57 | 58 | Finally, every program is threatened constantly by software patents. States should 59 | not allow patents to restrict development and use of software on general-purpose 60 | computers, but in those that do, we wish to avoid the special danger that patents 61 | applied to a free program could make it effectively proprietary. To prevent this, the 62 | GPL assures that patents cannot be used to render the program non-free. 63 | 64 | The precise terms and conditions for copying, distribution and modification follow. 65 | 66 | ## TERMS AND CONDITIONS 67 | 68 | ### 0. Definitions 69 | 70 | “This License” refers to version 3 of the GNU General Public License. 71 | 72 | “Copyright” also means copyright-like laws that apply to other kinds of 73 | works, such as semiconductor masks. 74 | 75 | “The Program” refers to any copyrightable work licensed under this 76 | License. Each licensee is addressed as “you”. “Licensees” and 77 | “recipients” may be individuals or organizations. 78 | 79 | To “modify” a work means to copy from or adapt all or part of the work in 80 | a fashion requiring copyright permission, other than the making of an exact copy. The 81 | resulting work is called a “modified version” of the earlier work or a 82 | work “based on” the earlier work. 83 | 84 | A “covered work” means either the unmodified Program or a work based on 85 | the Program. 86 | 87 | To “propagate” a work means to do anything with it that, without 88 | permission, would make you directly or secondarily liable for infringement under 89 | applicable copyright law, except executing it on a computer or modifying a private 90 | copy. Propagation includes copying, distribution (with or without modification), 91 | making available to the public, and in some countries other activities as well. 92 | 93 | To “convey” a work means any kind of propagation that enables other 94 | parties to make or receive copies. Mere interaction with a user through a computer 95 | network, with no transfer of a copy, is not conveying. 96 | 97 | An interactive user interface displays “Appropriate Legal Notices” to the 98 | extent that it includes a convenient and prominently visible feature that **(1)** 99 | displays an appropriate copyright notice, and **(2)** tells the user that there is no 100 | warranty for the work (except to the extent that warranties are provided), that 101 | licensees may convey the work under this License, and how to view a copy of this 102 | License. If the interface presents a list of user commands or options, such as a 103 | menu, a prominent item in the list meets this criterion. 104 | 105 | ### 1. Source Code 106 | 107 | The “source code” for a work means the preferred form of the work for 108 | making modifications to it. “Object code” means any non-source form of a 109 | work. 110 | 111 | A “Standard Interface” means an interface that either is an official 112 | standard defined by a recognized standards body, or, in the case of interfaces 113 | specified for a particular programming language, one that is widely used among 114 | developers working in that language. 115 | 116 | The “System Libraries” of an executable work include anything, other than 117 | the work as a whole, that **(a)** is included in the normal form of packaging a Major 118 | Component, but which is not part of that Major Component, and **(b)** serves only to 119 | enable use of the work with that Major Component, or to implement a Standard 120 | Interface for which an implementation is available to the public in source code form. 121 | A “Major Component”, in this context, means a major essential component 122 | (kernel, window system, and so on) of the specific operating system (if any) on which 123 | the executable work runs, or a compiler used to produce the work, or an object code 124 | interpreter used to run it. 125 | 126 | The “Corresponding Source” for a work in object code form means all the 127 | source code needed to generate, install, and (for an executable work) run the object 128 | code and to modify the work, including scripts to control those activities. However, 129 | it does not include the work's System Libraries, or general-purpose tools or 130 | generally available free programs which are used unmodified in performing those 131 | activities but which are not part of the work. For example, Corresponding Source 132 | includes interface definition files associated with source files for the work, and 133 | the source code for shared libraries and dynamically linked subprograms that the work 134 | is specifically designed to require, such as by intimate data communication or 135 | control flow between those subprograms and other parts of the work. 136 | 137 | The Corresponding Source need not include anything that users can regenerate 138 | automatically from other parts of the Corresponding Source. 139 | 140 | The Corresponding Source for a work in source code form is that same work. 141 | 142 | ### 2. Basic Permissions 143 | 144 | All rights granted under this License are granted for the term of copyright on the 145 | Program, and are irrevocable provided the stated conditions are met. This License 146 | explicitly affirms your unlimited permission to run the unmodified Program. The 147 | output from running a covered work is covered by this License only if the output, 148 | given its content, constitutes a covered work. This License acknowledges your rights 149 | of fair use or other equivalent, as provided by copyright law. 150 | 151 | You may make, run and propagate covered works that you do not convey, without 152 | conditions so long as your license otherwise remains in force. You may convey covered 153 | works to others for the sole purpose of having them make modifications exclusively 154 | for you, or provide you with facilities for running those works, provided that you 155 | comply with the terms of this License in conveying all material for which you do not 156 | control copyright. Those thus making or running the covered works for you must do so 157 | exclusively on your behalf, under your direction and control, on terms that prohibit 158 | them from making any copies of your copyrighted material outside their relationship 159 | with you. 160 | 161 | Conveying under any other circumstances is permitted solely under the conditions 162 | stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 163 | 164 | ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law 165 | 166 | No covered work shall be deemed part of an effective technological measure under any 167 | applicable law fulfilling obligations under article 11 of the WIPO copyright treaty 168 | adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention 169 | of such measures. 170 | 171 | When you convey a covered work, you waive any legal power to forbid circumvention of 172 | technological measures to the extent such circumvention is effected by exercising 173 | rights under this License with respect to the covered work, and you disclaim any 174 | intention to limit operation or modification of the work as a means of enforcing, 175 | against the work's users, your or third parties' legal rights to forbid circumvention 176 | of technological measures. 177 | 178 | ### 4. Conveying Verbatim Copies 179 | 180 | You may convey verbatim copies of the Program's source code as you receive it, in any 181 | medium, provided that you conspicuously and appropriately publish on each copy an 182 | appropriate copyright notice; keep intact all notices stating that this License and 183 | any non-permissive terms added in accord with section 7 apply to the code; keep 184 | intact all notices of the absence of any warranty; and give all recipients a copy of 185 | this License along with the Program. 186 | 187 | You may charge any price or no price for each copy that you convey, and you may offer 188 | support or warranty protection for a fee. 189 | 190 | ### 5. Conveying Modified Source Versions 191 | 192 | You may convey a work based on the Program, or the modifications to produce it from 193 | the Program, in the form of source code under the terms of section 4, provided that 194 | you also meet all of these conditions: 195 | 196 | * **a)** The work must carry prominent notices stating that you modified it, and giving a 197 | relevant date. 198 | * **b)** The work must carry prominent notices stating that it is released under this 199 | License and any conditions added under section 7. This requirement modifies the 200 | requirement in section 4 to “keep intact all notices”. 201 | * **c)** You must license the entire work, as a whole, under this License to anyone who 202 | comes into possession of a copy. This License will therefore apply, along with any 203 | applicable section 7 additional terms, to the whole of the work, and all its parts, 204 | regardless of how they are packaged. This License gives no permission to license the 205 | work in any other way, but it does not invalidate such permission if you have 206 | separately received it. 207 | * **d)** If the work has interactive user interfaces, each must display Appropriate Legal 208 | Notices; however, if the Program has interactive interfaces that do not display 209 | Appropriate Legal Notices, your work need not make them do so. 210 | 211 | A compilation of a covered work with other separate and independent works, which are 212 | not by their nature extensions of the covered work, and which are not combined with 213 | it such as to form a larger program, in or on a volume of a storage or distribution 214 | medium, is called an “aggregate” if the compilation and its resulting 215 | copyright are not used to limit the access or legal rights of the compilation's users 216 | beyond what the individual works permit. Inclusion of a covered work in an aggregate 217 | does not cause this License to apply to the other parts of the aggregate. 218 | 219 | ### 6. Conveying Non-Source Forms 220 | 221 | You may convey a covered work in object code form under the terms of sections 4 and 222 | 5, provided that you also convey the machine-readable Corresponding Source under the 223 | terms of this License, in one of these ways: 224 | 225 | * **a)** Convey the object code in, or embodied in, a physical product (including a 226 | physical distribution medium), accompanied by the Corresponding Source fixed on a 227 | durable physical medium customarily used for software interchange. 228 | * **b)** Convey the object code in, or embodied in, a physical product (including a 229 | physical distribution medium), accompanied by a written offer, valid for at least 230 | three years and valid for as long as you offer spare parts or customer support for 231 | that product model, to give anyone who possesses the object code either **(1)** a copy of 232 | the Corresponding Source for all the software in the product that is covered by this 233 | License, on a durable physical medium customarily used for software interchange, for 234 | a price no more than your reasonable cost of physically performing this conveying of 235 | source, or **(2)** access to copy the Corresponding Source from a network server at no 236 | charge. 237 | * **c)** Convey individual copies of the object code with a copy of the written offer to 238 | provide the Corresponding Source. This alternative is allowed only occasionally and 239 | noncommercially, and only if you received the object code with such an offer, in 240 | accord with subsection 6b. 241 | * **d)** Convey the object code by offering access from a designated place (gratis or for 242 | a charge), and offer equivalent access to the Corresponding Source in the same way 243 | through the same place at no further charge. You need not require recipients to copy 244 | the Corresponding Source along with the object code. If the place to copy the object 245 | code is a network server, the Corresponding Source may be on a different server 246 | (operated by you or a third party) that supports equivalent copying facilities, 247 | provided you maintain clear directions next to the object code saying where to find 248 | the Corresponding Source. Regardless of what server hosts the Corresponding Source, 249 | you remain obligated to ensure that it is available for as long as needed to satisfy 250 | these requirements. 251 | * **e)** Convey the object code using peer-to-peer transmission, provided you inform 252 | other peers where the object code and Corresponding Source of the work are being 253 | offered to the general public at no charge under subsection 6d. 254 | 255 | A separable portion of the object code, whose source code is excluded from the 256 | Corresponding Source as a System Library, need not be included in conveying the 257 | object code work. 258 | 259 | A “User Product” is either **(1)** a “consumer product”, which 260 | means any tangible personal property which is normally used for personal, family, or 261 | household purposes, or **(2)** anything designed or sold for incorporation into a 262 | dwelling. In determining whether a product is a consumer product, doubtful cases 263 | shall be resolved in favor of coverage. For a particular product received by a 264 | particular user, “normally used” refers to a typical or common use of 265 | that class of product, regardless of the status of the particular user or of the way 266 | in which the particular user actually uses, or expects or is expected to use, the 267 | product. A product is a consumer product regardless of whether the product has 268 | substantial commercial, industrial or non-consumer uses, unless such uses represent 269 | the only significant mode of use of the product. 270 | 271 | “Installation Information” for a User Product means any methods, 272 | procedures, authorization keys, or other information required to install and execute 273 | modified versions of a covered work in that User Product from a modified version of 274 | its Corresponding Source. The information must suffice to ensure that the continued 275 | functioning of the modified object code is in no case prevented or interfered with 276 | solely because modification has been made. 277 | 278 | If you convey an object code work under this section in, or with, or specifically for 279 | use in, a User Product, and the conveying occurs as part of a transaction in which 280 | the right of possession and use of the User Product is transferred to the recipient 281 | in perpetuity or for a fixed term (regardless of how the transaction is 282 | characterized), the Corresponding Source conveyed under this section must be 283 | accompanied by the Installation Information. But this requirement does not apply if 284 | neither you nor any third party retains the ability to install modified object code 285 | on the User Product (for example, the work has been installed in ROM). 286 | 287 | The requirement to provide Installation Information does not include a requirement to 288 | continue to provide support service, warranty, or updates for a work that has been 289 | modified or installed by the recipient, or for the User Product in which it has been 290 | modified or installed. Access to a network may be denied when the modification itself 291 | materially and adversely affects the operation of the network or violates the rules 292 | and protocols for communication across the network. 293 | 294 | Corresponding Source conveyed, and Installation Information provided, in accord with 295 | this section must be in a format that is publicly documented (and with an 296 | implementation available to the public in source code form), and must require no 297 | special password or key for unpacking, reading or copying. 298 | 299 | ### 7. Additional Terms 300 | 301 | “Additional permissions” are terms that supplement the terms of this 302 | License by making exceptions from one or more of its conditions. Additional 303 | permissions that are applicable to the entire Program shall be treated as though they 304 | were included in this License, to the extent that they are valid under applicable 305 | law. If additional permissions apply only to part of the Program, that part may be 306 | used separately under those permissions, but the entire Program remains governed by 307 | this License without regard to the additional permissions. 308 | 309 | When you convey a copy of a covered work, you may at your option remove any 310 | additional permissions from that copy, or from any part of it. (Additional 311 | permissions may be written to require their own removal in certain cases when you 312 | modify the work.) You may place additional permissions on material, added by you to a 313 | covered work, for which you have or can give appropriate copyright permission. 314 | 315 | Notwithstanding any other provision of this License, for material you add to a 316 | covered work, you may (if authorized by the copyright holders of that material) 317 | supplement the terms of this License with terms: 318 | 319 | * **a)** Disclaiming warranty or limiting liability differently from the terms of 320 | sections 15 and 16 of this License; or 321 | * **b)** Requiring preservation of specified reasonable legal notices or author 322 | attributions in that material or in the Appropriate Legal Notices displayed by works 323 | containing it; or 324 | * **c)** Prohibiting misrepresentation of the origin of that material, or requiring that 325 | modified versions of such material be marked in reasonable ways as different from the 326 | original version; or 327 | * **d)** Limiting the use for publicity purposes of names of licensors or authors of the 328 | material; or 329 | * **e)** Declining to grant rights under trademark law for use of some trade names, 330 | trademarks, or service marks; or 331 | * **f)** Requiring indemnification of licensors and authors of that material by anyone 332 | who conveys the material (or modified versions of it) with contractual assumptions of 333 | liability to the recipient, for any liability that these contractual assumptions 334 | directly impose on those licensors and authors. 335 | 336 | All other non-permissive additional terms are considered “further 337 | restrictions” within the meaning of section 10. If the Program as you received 338 | it, or any part of it, contains a notice stating that it is governed by this License 339 | along with a term that is a further restriction, you may remove that term. If a 340 | license document contains a further restriction but permits relicensing or conveying 341 | under this License, you may add to a covered work material governed by the terms of 342 | that license document, provided that the further restriction does not survive such 343 | relicensing or conveying. 344 | 345 | If you add terms to a covered work in accord with this section, you must place, in 346 | the relevant source files, a statement of the additional terms that apply to those 347 | files, or a notice indicating where to find the applicable terms. 348 | 349 | Additional terms, permissive or non-permissive, may be stated in the form of a 350 | separately written license, or stated as exceptions; the above requirements apply 351 | either way. 352 | 353 | ### 8. Termination 354 | 355 | You may not propagate or modify a covered work except as expressly provided under 356 | this License. Any attempt otherwise to propagate or modify it is void, and will 357 | automatically terminate your rights under this License (including any patent licenses 358 | granted under the third paragraph of section 11). 359 | 360 | However, if you cease all violation of this License, then your license from a 361 | particular copyright holder is reinstated **(a)** provisionally, unless and until the 362 | copyright holder explicitly and finally terminates your license, and **(b)** permanently, 363 | if the copyright holder fails to notify you of the violation by some reasonable means 364 | prior to 60 days after the cessation. 365 | 366 | Moreover, your license from a particular copyright holder is reinstated permanently 367 | if the copyright holder notifies you of the violation by some reasonable means, this 368 | is the first time you have received notice of violation of this License (for any 369 | work) from that copyright holder, and you cure the violation prior to 30 days after 370 | your receipt of the notice. 371 | 372 | Termination of your rights under this section does not terminate the licenses of 373 | parties who have received copies or rights from you under this License. If your 374 | rights have been terminated and not permanently reinstated, you do not qualify to 375 | receive new licenses for the same material under section 10. 376 | 377 | ### 9. Acceptance Not Required for Having Copies 378 | 379 | You are not required to accept this License in order to receive or run a copy of the 380 | Program. Ancillary propagation of a covered work occurring solely as a consequence of 381 | using peer-to-peer transmission to receive a copy likewise does not require 382 | acceptance. However, nothing other than this License grants you permission to 383 | propagate or modify any covered work. These actions infringe copyright if you do not 384 | accept this License. Therefore, by modifying or propagating a covered work, you 385 | indicate your acceptance of this License to do so. 386 | 387 | ### 10. Automatic Licensing of Downstream Recipients 388 | 389 | Each time you convey a covered work, the recipient automatically receives a license 390 | from the original licensors, to run, modify and propagate that work, subject to this 391 | License. You are not responsible for enforcing compliance by third parties with this 392 | License. 393 | 394 | An “entity transaction” is a transaction transferring control of an 395 | organization, or substantially all assets of one, or subdividing an organization, or 396 | merging organizations. If propagation of a covered work results from an entity 397 | transaction, each party to that transaction who receives a copy of the work also 398 | receives whatever licenses to the work the party's predecessor in interest had or 399 | could give under the previous paragraph, plus a right to possession of the 400 | Corresponding Source of the work from the predecessor in interest, if the predecessor 401 | has it or can get it with reasonable efforts. 402 | 403 | You may not impose any further restrictions on the exercise of the rights granted or 404 | affirmed under this License. For example, you may not impose a license fee, royalty, 405 | or other charge for exercise of rights granted under this License, and you may not 406 | initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging 407 | that any patent claim is infringed by making, using, selling, offering for sale, or 408 | importing the Program or any portion of it. 409 | 410 | ### 11. Patents 411 | 412 | A “contributor” is a copyright holder who authorizes use under this 413 | License of the Program or a work on which the Program is based. The work thus 414 | licensed is called the contributor's “contributor version”. 415 | 416 | A contributor's “essential patent claims” are all patent claims owned or 417 | controlled by the contributor, whether already acquired or hereafter acquired, that 418 | would be infringed by some manner, permitted by this License, of making, using, or 419 | selling its contributor version, but do not include claims that would be infringed 420 | only as a consequence of further modification of the contributor version. For 421 | purposes of this definition, “control” includes the right to grant patent 422 | sublicenses in a manner consistent with the requirements of this License. 423 | 424 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license 425 | under the contributor's essential patent claims, to make, use, sell, offer for sale, 426 | import and otherwise run, modify and propagate the contents of its contributor 427 | version. 428 | 429 | In the following three paragraphs, a “patent license” is any express 430 | agreement or commitment, however denominated, not to enforce a patent (such as an 431 | express permission to practice a patent or covenant not to sue for patent 432 | infringement). To “grant” such a patent license to a party means to make 433 | such an agreement or commitment not to enforce a patent against the party. 434 | 435 | If you convey a covered work, knowingly relying on a patent license, and the 436 | Corresponding Source of the work is not available for anyone to copy, free of charge 437 | and under the terms of this License, through a publicly available network server or 438 | other readily accessible means, then you must either **(1)** cause the Corresponding 439 | Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the 440 | patent license for this particular work, or **(3)** arrange, in a manner consistent with 441 | the requirements of this License, to extend the patent license to downstream 442 | recipients. “Knowingly relying” means you have actual knowledge that, but 443 | for the patent license, your conveying the covered work in a country, or your 444 | recipient's use of the covered work in a country, would infringe one or more 445 | identifiable patents in that country that you have reason to believe are valid. 446 | 447 | If, pursuant to or in connection with a single transaction or arrangement, you 448 | convey, or propagate by procuring conveyance of, a covered work, and grant a patent 449 | license to some of the parties receiving the covered work authorizing them to use, 450 | propagate, modify or convey a specific copy of the covered work, then the patent 451 | license you grant is automatically extended to all recipients of the covered work and 452 | works based on it. 453 | 454 | A patent license is “discriminatory” if it does not include within the 455 | scope of its coverage, prohibits the exercise of, or is conditioned on the 456 | non-exercise of one or more of the rights that are specifically granted under this 457 | License. You may not convey a covered work if you are a party to an arrangement with 458 | a third party that is in the business of distributing software, under which you make 459 | payment to the third party based on the extent of your activity of conveying the 460 | work, and under which the third party grants, to any of the parties who would receive 461 | the covered work from you, a discriminatory patent license **(a)** in connection with 462 | copies of the covered work conveyed by you (or copies made from those copies), or **(b)** 463 | primarily for and in connection with specific products or compilations that contain 464 | the covered work, unless you entered into that arrangement, or that patent license 465 | was granted, prior to 28 March 2007. 466 | 467 | Nothing in this License shall be construed as excluding or limiting any implied 468 | license or other defenses to infringement that may otherwise be available to you 469 | under applicable patent law. 470 | 471 | ### 12. No Surrender of Others' Freedom 472 | 473 | If conditions are imposed on you (whether by court order, agreement or otherwise) 474 | that contradict the conditions of this License, they do not excuse you from the 475 | conditions of this License. If you cannot convey a covered work so as to satisfy 476 | simultaneously your obligations under this License and any other pertinent 477 | obligations, then as a consequence you may not convey it at all. For example, if you 478 | agree to terms that obligate you to collect a royalty for further conveying from 479 | those to whom you convey the Program, the only way you could satisfy both those terms 480 | and this License would be to refrain entirely from conveying the Program. 481 | 482 | ### 13. Use with the GNU Affero General Public License 483 | 484 | Notwithstanding any other provision of this License, you have permission to link or 485 | combine any covered work with a work licensed under version 3 of the GNU Affero 486 | General Public License into a single combined work, and to convey the resulting work. 487 | The terms of this License will continue to apply to the part which is the covered 488 | work, but the special requirements of the GNU Affero General Public License, section 489 | 13, concerning interaction through a network will apply to the combination as such. 490 | 491 | ### 14. Revised Versions of this License 492 | 493 | The Free Software Foundation may publish revised and/or new versions of the GNU 494 | General Public License from time to time. Such new versions will be similar in spirit 495 | to the present version, but may differ in detail to address new problems or concerns. 496 | 497 | Each version is given a distinguishing version number. If the Program specifies that 498 | a certain numbered version of the GNU General Public License “or any later 499 | version” applies to it, you have the option of following the terms and 500 | conditions either of that numbered version or of any later version published by the 501 | Free Software Foundation. If the Program does not specify a version number of the GNU 502 | General Public License, you may choose any version ever published by the Free 503 | Software Foundation. 504 | 505 | If the Program specifies that a proxy can decide which future versions of the GNU 506 | General Public License can be used, that proxy's public statement of acceptance of a 507 | version permanently authorizes you to choose that version for the Program. 508 | 509 | Later license versions may give you additional or different permissions. However, no 510 | additional obligations are imposed on any author or copyright holder as a result of 511 | your choosing to follow a later version. 512 | 513 | ### 15. Disclaimer of Warranty 514 | 515 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 516 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 517 | PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER 518 | EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 519 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE 520 | QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 521 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 522 | 523 | ### 16. Limitation of Liability 524 | 525 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY 526 | COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS 527 | PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, 528 | INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 529 | PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE 530 | OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE 531 | WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 532 | POSSIBILITY OF SUCH DAMAGES. 533 | 534 | ### 17. Interpretation of Sections 15 and 16 535 | 536 | If the disclaimer of warranty and limitation of liability provided above cannot be 537 | given local legal effect according to their terms, reviewing courts shall apply local 538 | law that most closely approximates an absolute waiver of all civil liability in 539 | connection with the Program, unless a warranty or assumption of liability accompanies 540 | a copy of the Program in return for a fee. 541 | 542 | _END OF TERMS AND CONDITIONS_ 543 | 544 | ## How to Apply These Terms to Your New Programs 545 | 546 | If you develop a new program, and you want it to be of the greatest possible use to 547 | the public, the best way to achieve this is to make it free software which everyone 548 | can redistribute and change under these terms. 549 | 550 | To do so, attach the following notices to the program. It is safest to attach them 551 | to the start of each source file to most effectively state the exclusion of warranty; 552 | and each file should have at least the “copyright” line and a pointer to 553 | where the full notice is found. 554 | 555 | 556 | Copyright (C) 557 | 558 | This program is free software: you can redistribute it and/or modify 559 | it under the terms of the GNU General Public License as published by 560 | the Free Software Foundation, either version 3 of the License, or 561 | (at your option) any later version. 562 | 563 | This program is distributed in the hope that it will be useful, 564 | but WITHOUT ANY WARRANTY; without even the implied warranty of 565 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 566 | GNU General Public License for more details. 567 | 568 | You should have received a copy of the GNU General Public License 569 | along with this program. If not, see . 570 | 571 | Also add information on how to contact you by electronic and paper mail. 572 | 573 | If the program does terminal interaction, make it output a short notice like this 574 | when it starts in an interactive mode: 575 | 576 | Copyright (C) 577 | This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. 578 | This is free software, and you are welcome to redistribute it 579 | under certain conditions; type 'show c' for details. 580 | 581 | The hypothetical commands `show w` and `show c` should show the appropriate parts of 582 | the General Public License. Of course, your program's commands might be different; 583 | for a GUI interface, you would use an “about box”. 584 | 585 | You should also get your employer (if you work as a programmer) or school, if any, to 586 | sign a “copyright disclaimer” for the program, if necessary. For more 587 | information on this, and how to apply and follow the GNU GPL, see 588 | <>. 589 | 590 | The GNU General Public License does not permit incorporating your program into 591 | proprietary programs. If your program is a subroutine library, you may consider it 592 | more useful to permit linking proprietary applications with the library. If this is 593 | what you want to do, use the GNU Lesser General Public License instead of this 594 | License. But first, please read 595 | <>. 596 | --------------------------------------------------------------------------------