Last active
January 7, 2021 16:53
-
-
Save hypercompetent/51a3c428745e1c06d826d76c3671797c to your computer and use it in GitHub Desktop.
Pearson residuals function in R, from Lause, Berens, and Kobak
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pearson_residuals <- function(counts, theta = 100) { | |
counts_sum0 <- as(matrix(Matrix::colSums(counts),nrow=1),"dgCMatrix") | |
counts_sum1 <- as(matrix(Matrix::rowSums(counts),ncol=1),"dgCMatrix") | |
counts_sum <- sum(counts@x) | |
#get residuals | |
mu <- (counts_sum1 %*% counts_sum0) / counts_sum | |
z <- (counts - mu) / sqrt(mu + mu^2/theta) | |
#clip to sqrt(n) | |
n <- ncol(counts) | |
z[z > sqrt(n)] <- sqrt(n) | |
z[z < -sqrt(n)] <- -sqrt(n) | |
z | |
} | |
sparse_pearson_residuals <- function(counts, theta = 100) { | |
counts_sum0 <- Matrix::colSums(counts) | |
counts_sum1 <- Matrix::rowSums(counts) | |
counts_sum <- sum(counts@x) | |
#get residuals sparsely | |
mu <- Matrix::sparseMatrix(x = counts_sum1[counts@i + 1] * rep(counts_sum0, diff(counts@p)) / counts_sum, | |
i = counts@i, | |
p = counts@p, | |
dims = dim(counts), | |
index1 = FALSE) | |
z <- counts - mu | |
mu2 <- sqrt(mu + mu^2/theta) | |
z@x <- z@x / mu2@x | |
# clip to sqrt(n) | |
n <- ncol(counts) | |
z@x[z@x > sqrt(n)] <- sqrt(n) | |
z@x[z@x < -sqrt(n)] <- -sqrt(n) | |
z | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on Lause, Berens, and Kobak on bioRxiv:
https://www.biorxiv.org/content/10.1101/2020.12.01.405886v1.full
Original Python implementation:
https://github.com/berenslab/umi-normalization/blob/main/tools.py